1/* Remote utility routines for the remote server for GDB.
2   Copyright (C) 1986, 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3   2001, 2002, 2003, 2004, 2005, 2006, 2011
4   Free Software Foundation, Inc.
5
6   This file is part of GDB.
7   It has been modified to integrate it in valgrind
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19   You should have received a copy of the GNU General Public License
20   along with this program; if not, write to the Free Software
21   Foundation, Inc., 51 Franklin Street, Fifth Floor,
22   Boston, MA 02110-1301, USA.  */
23
24#include "pub_core_basics.h"
25#include "pub_core_vki.h"
26#include "pub_core_vkiscnums.h"
27#include "pub_core_libcsignal.h"
28#include "pub_core_options.h"
29
30#include "server.h"
31
32#  if defined(VGO_linux)
33#include <sys/prctl.h>
34#  endif
35
36/* Calls sr_perror with msg.
37   Outputs more information about Valgrind state if verbosity > 0
38   or debuglog_getlevel > 0. */
39static
40void sr_extended_perror (SysRes sr, const HChar *msg)
41{
42   sr_perror (sr, "%s", msg);
43   if (VG_(clo_verbosity) > 0 || VG_(debugLog_getLevel)() >= 1) {
44      Int i;
45      vki_sigset_t cursigset;
46      VG_(show_sched_status) (True,  // host_stacktrace
47                              True,  // valgrind_stack_usage
48                              True); // exited_threads
49      VG_(sigprocmask) (0,           // dummy how.
50                        NULL,        // do not change the sigmask
51                        &cursigset); //
52      VG_(dmsg)("current sigmask value { ");
53      for (i = 1; i <= _VKI_NSIG; i++) {
54         if (VG_(sigismember)(&cursigset, i))
55            VG_(dmsg)("%u ", i);
56      }
57      VG_(dmsg)("}\n");
58   }
59}
60
61/* Calls VG_(poll) with given arguments. If VG_(poll) fails due to EINTR,
62   restarts the syscall.
63   Normally, VG_(poll) gdbsrv syscalls are not supposed to be interrupted :
64     either gdbsrv has been called by the scheduler (so all async signals
65     are masked)
66     or gdbsrv has been forced invoked by vgdb+ptrace, and vgdb is queuing
67     the signals.
68
69   However, on old kernels (such as on RHEL5.5 2.6.18), when vgdb+ptrace
70   intercepts and queues an async signal, the poll syscall is not properly
71   restarted. Instead, it returns EINTR even if no signal was effectively
72   received by the ptraced process.
73   See red-hat "Bug 679129 - Change in behaviour between RH5.5 and RH6
74   with ptrace and syscalls bugzilla"
75   e.g. "Why rhel5 differs? Because unlike in rhel6, sys_poll() returns
76         -EINTR if interrupted, that is all. This old implementation does
77         not support the restart-if-eintr-is-spurious."
78
79   So in case VG_(poll) fails with EINTR, we retry. */
80static SysRes VG_(poll_no_eintr) (struct vki_pollfd *fds, Int nfds, Int timeout)
81{
82  const HChar* msg = "VG_(poll) failed (old kernel ?) retrying ... \n";
83  SysRes sr;
84  do {
85     sr = VG_(poll) (fds, nfds, timeout);
86     if (!sr_isError(sr) || sr_Err(sr) != VKI_EINTR)
87        return sr;
88     sr_perror (sr, "%s", msg);
89     if (VG_(debugLog_getLevel)() >= 1) {
90        sr_extended_perror (sr, msg);
91     }
92  } while (1);
93  /*NOTREACHED*/
94}
95
96Bool noack_mode;
97
98static int readchar (int single);
99
100void remote_utils_output_status(void);
101
102#define INVALID_DESCRIPTOR -1
103static int remote_desc = INVALID_DESCRIPTOR;
104
105static VgdbShared *shared;
106static int  last_looked_cntr = -1;
107static struct vki_pollfd remote_desc_pollfdread_activity;
108
109/* for a gdbserver embedded in valgrind, we read from a FIFO and write
110   to another FIFO So, we need two descriptors */
111static int write_remote_desc = INVALID_DESCRIPTOR;
112static int pid_from_to_creator;
113/* only this pid will remove the FIFOs: if an exec fails, we must avoid
114   that the exiting child believes it has to remove the FIFOs of its parent */
115static int mknod_done = 0;
116
117static char *from_gdb = NULL;
118static char *to_gdb = NULL;
119static char *shared_mem = NULL;
120
121static
122int open_fifo (const char *side, const char *path, int flags)
123{
124  SysRes o;
125  int fd;
126  dlog(1, "Opening %s side %s\n", side, path);
127  o = VG_(open) (path, flags, 0);
128  if (sr_isError (o)) {
129     sr_perror(o, "open fifo %s\n", path);
130     fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n");
131  } else {
132     fd = sr_Res(o);
133     dlog(1, "result fd %d\n", fd);
134  }
135  fd = VG_(safe_fd)(fd);
136  dlog(1, "result safe_fd %d\n", fd);
137  if (fd == -1)
138     fatal("safe_fd for vgdb FIFO failed\n");
139  return fd;
140}
141
142void remote_utils_output_status(void)
143{
144   if (shared == NULL)
145      VG_(umsg)("remote communication not initialized\n");
146   else
147      VG_(umsg)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n",
148                shared->written_by_vgdb, shared->seen_by_valgrind);
149}
150
151/* Returns 0 if vgdb and connection state looks good,
152   otherwise returns an int value telling which check failed. */
153static
154int vgdb_state_looks_bad(const char* where)
155{
156   if (VG_(kill)(shared->vgdb_pid, 0) != 0)
157      return 1; // vgdb process does not exist anymore.
158
159   if (remote_desc_activity(where) == 2)
160      return 2; // check for error on remote desc shows a problem
161
162   if (remote_desc == INVALID_DESCRIPTOR)
163      return 3; // after check, remote_desc not ok anymore
164
165   return 0; // all is ok.
166}
167
168void VG_(set_ptracer)(void)
169{
170#ifdef PR_SET_PTRACER
171   SysRes o;
172   const char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
173   int fd;
174   char ptrace_scope;
175   int ret;
176
177   o = VG_(open) (ptrace_scope_setting_file, VKI_O_RDONLY, 0);
178   if (sr_isError(o)) {
179      if (VG_(debugLog_getLevel)() >= 1) {
180         sr_perror(o, "error VG_(open) %s\n", ptrace_scope_setting_file);
181      }
182      /* can't read setting. Assuming ptrace can be called by vgdb. */
183      return;
184   }
185   fd = sr_Res(o);
186   if (VG_(read) (fd, &ptrace_scope, 1) == 1) {
187      dlog(1, "ptrace_scope %c\n", ptrace_scope);
188      if (ptrace_scope != '0') {
189         /* insufficient default ptrace_scope.
190            Indicate to the kernel that we accept to be ptraced. */
191#ifdef PR_SET_PTRACER_ANY
192         ret = VG_(prctl) (PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
193         dlog(1, "set_ptracer to PR_SET_PTRACER_ANY result %d\n", ret);
194#else
195         ret = VG_(prctl) (PR_SET_PTRACER, 1, 0, 0, 0);
196         dlog(1, "set_ptracer to 1 result %d\n", ret);
197#endif
198         if (ret)
199            VG_(umsg)("error calling PR_SET_PTRACER, vgdb might block\n");
200      }
201   } else {
202      dlog(0, "Could not read the ptrace_scope setting from %s\n",
203           ptrace_scope_setting_file);
204   }
205
206   VG_(close) (fd);
207#endif
208}
209
210/* returns 1 if one or more poll "errors" is set.
211   Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */
212static
213int poll_cond (short revents)
214{
215   return (revents & (VKI_POLLERR | VKI_POLLHUP | VKI_POLLNVAL));
216}
217
218/* Ensures we have a valid write file descriptor.
219   Returns 1 if we have a valid write file descriptor,
220   0 if the write fd is not valid/cannot be opened. */
221static
222int ensure_write_remote_desc(void)
223{
224   struct vki_pollfd write_remote_desc_ok;
225   SysRes ret;
226   if (write_remote_desc != INVALID_DESCRIPTOR) {
227      write_remote_desc_ok.fd = write_remote_desc;
228      write_remote_desc_ok.events = VKI_POLLOUT;
229      write_remote_desc_ok.revents = 0;
230      ret = VG_(poll_no_eintr)(&write_remote_desc_ok, 1, 0);
231      if (sr_isError(ret)
232          || (sr_Res(ret) > 0 && poll_cond(write_remote_desc_ok.revents))) {
233        if (sr_isError(ret)) {
234          sr_extended_perror(ret, "ensure_write_remote_desc: poll error\n");
235        } else {
236          dlog(0, "POLLcond %d closing write_remote_desc %d\n",
237               write_remote_desc_ok.revents, write_remote_desc);
238        }
239        VG_(close) (write_remote_desc);
240        write_remote_desc = INVALID_DESCRIPTOR;
241      }
242   }
243   if (write_remote_desc == INVALID_DESCRIPTOR) {
244      /* open_fifo write will block if the receiving vgdb
245         process is dead.  So, let's check for vgdb state to
246         be reasonably sure someone is reading on the other
247         side of the fifo. */
248      if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) {
249         write_remote_desc = open_fifo ("write", to_gdb, VKI_O_WRONLY);
250      }
251   }
252
253   return (write_remote_desc != INVALID_DESCRIPTOR);
254}
255
256#if defined(VGO_darwin)
257#define VKI_S_IFIFO 0010000
258#endif
259static
260void safe_mknod (char *nod)
261{
262   SysRes m;
263   m = VG_(mknod) (nod, VKI_S_IFIFO|0600, 0);
264   if (sr_isError (m)) {
265      if (sr_Err (m) == VKI_EEXIST) {
266         if (VG_(clo_verbosity) > 1) {
267            VG_(umsg)("%s already created\n", nod);
268         }
269      } else {
270         sr_perror(m, "mknod %s\n", nod);
271         VG_(umsg) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n");
272         VG_(exit)(1);
273      }
274   }
275}
276
277/* Open a connection to a remote debugger.
278   NAME is the filename used for communication.
279   For Valgrind, name is the prefix for the two read and write FIFOs
280   The two FIFOs names will be build by appending
281   -from-vgdb-to-pid-by-user-on-host and -to-vgdb-from-pid-by-user-on-host
282   with pid being the pidnr of the valgrind process These two FIFOs
283   will be created if not existing yet. They will be removed when
284   the gdbserver connection is closed or the process exits */
285
286void remote_open (const HChar *name)
287{
288   const HChar *user, *host;
289   int save_fcntl_flags, len;
290   VgdbShared vgdbinit =
291      {0, 0, (Addr) VG_(invoke_gdbserver),
292       (Addr) VG_(threads), sizeof(ThreadState),
293       offsetof(ThreadState, status),
294       offsetof(ThreadState, os_state) + offsetof(ThreadOSstate, lwpid),
295       0};
296   const int pid = VG_(getpid)();
297   Addr addr_shared;
298   SysRes o;
299   int shared_mem_fd = INVALID_DESCRIPTOR;
300
301   user = VG_(getenv)("LOGNAME");
302   if (user == NULL) user = VG_(getenv)("USER");
303   if (user == NULL) user = "???";
304
305   host = VG_(getenv)("HOST");
306   if (host == NULL) host = VG_(getenv)("HOSTNAME");
307   if (host == NULL) host = "???";
308
309   len = strlen(name) + strlen(user) + strlen(host) + 40;
310
311   if (from_gdb != NULL)
312      free (from_gdb);
313   from_gdb = malloc (len);
314   if (to_gdb != NULL)
315      free (to_gdb);
316   to_gdb = malloc (len);
317   if (shared_mem != NULL)
318      free (shared_mem);
319   shared_mem = malloc (len);
320   /* below 3 lines must match the equivalent in vgdb.c */
321   VG_(sprintf) (from_gdb,   "%s-from-vgdb-to-%d-by-%s-on-%s",    name,
322                 pid, user, host);
323   VG_(sprintf) (to_gdb,     "%s-to-vgdb-from-%d-by-%s-on-%s",    name,
324                 pid, user, host);
325   VG_(sprintf) (shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", name,
326                 pid, user, host);
327   if (VG_(clo_verbosity) > 1) {
328      VG_(umsg)("embedded gdbserver: reading from %s\n", from_gdb);
329      VG_(umsg)("embedded gdbserver: writing to   %s\n", to_gdb);
330      VG_(umsg)("embedded gdbserver: shared mem   %s\n", shared_mem);
331      VG_(umsg)("\n");
332      VG_(umsg)("TO CONTROL THIS PROCESS USING vgdb (which you probably\n"
333                "don't want to do, unless you know exactly what you're doing,\n"
334                "or are doing some strange experiment):\n"
335                "  %s/../../bin/vgdb%s%s --pid=%d ...command...\n",
336                VG_(libdir),
337                (VG_(arg_vgdb_prefix) ? " " : ""),
338                (VG_(arg_vgdb_prefix) ? VG_(arg_vgdb_prefix) : ""),
339                pid);
340   }
341   if (VG_(clo_verbosity) > 1
342       || VG_(clo_vgdb_error) < 999999999
343       || VG_(clo_vgdb_stop_at) != 0) {
344      VG_(umsg)("\n");
345      VG_(umsg)(
346         "TO DEBUG THIS PROCESS USING GDB: start GDB like this\n"
347         "  /path/to/gdb %s\n"
348         "and then give GDB the following command\n"
349         "  target remote | %s/../../bin/vgdb%s%s --pid=%d\n",
350         VG_(args_the_exename),
351         VG_(libdir),
352         (VG_(arg_vgdb_prefix) ? " " : ""),
353         (VG_(arg_vgdb_prefix) ? VG_(arg_vgdb_prefix) : ""),
354         pid
355      );
356      VG_(umsg)("--pid is optional if only one valgrind process is running\n");
357      VG_(umsg)("\n");
358   }
359
360   if (!mknod_done) {
361      mknod_done++;
362      VG_(set_ptracer)();
363      /*
364       * Unlink just in case a previous process with the same PID had been
365       * killed and hence Valgrind hasn't had the chance yet to remove these.
366       */
367      VG_(unlink)(from_gdb);
368      VG_(unlink)(to_gdb);
369      VG_(unlink)(shared_mem);
370
371      safe_mknod(from_gdb);
372      safe_mknod(to_gdb);
373
374      pid_from_to_creator = pid;
375
376      o = VG_(open) (shared_mem, VKI_O_CREAT|VKI_O_RDWR, 0600);
377      if (sr_isError (o)) {
378         sr_perror(o, "cannot create shared_mem file %s\n", shared_mem);
379         fatal("");
380      } else {
381         shared_mem_fd = sr_Res(o);
382      }
383
384      if (VG_(write)(shared_mem_fd, &vgdbinit, sizeof(VgdbShared))
385          != sizeof(VgdbShared)) {
386         fatal("error writing %d bytes to shared mem %s\n",
387               (int) sizeof(VgdbShared), shared_mem);
388      }
389      {
390         SysRes res = VG_(am_shared_mmap_file_float_valgrind)
391            (sizeof(VgdbShared), VKI_PROT_READ|VKI_PROT_WRITE,
392             shared_mem_fd, (Off64T)0);
393         if (sr_isError(res)) {
394            sr_perror(res, "error VG_(am_shared_mmap_file_float_valgrind) %s\n",
395                      shared_mem);
396            fatal("");
397         }
398         addr_shared = sr_Res (res);
399      }
400      shared = (VgdbShared*) addr_shared;
401      VG_(close) (shared_mem_fd);
402   }
403
404   if (remote_desc == INVALID_DESCRIPTOR) {
405      /* we open the read side FIFO in non blocking mode
406         We then set the fd in blocking mode.
407         Opening in non-blocking read mode always succeeds while opening
408         in non-blocking write mode succeeds only if the fifo is already
409         opened in read mode. So, we wait till we have read the first
410         character from the read side before opening the write side. */
411      remote_desc = open_fifo ("read", from_gdb, VKI_O_RDONLY|VKI_O_NONBLOCK);
412      save_fcntl_flags = VG_(fcntl) (remote_desc, VKI_F_GETFL, 0);
413      VG_(fcntl) (remote_desc, VKI_F_SETFL, save_fcntl_flags & ~VKI_O_NONBLOCK);
414   }
415   remote_desc_pollfdread_activity.fd = remote_desc;
416   remote_desc_pollfdread_activity.events = VKI_POLLIN;
417   remote_desc_pollfdread_activity.revents = 0;
418}
419
420/* sync_gdb_connection wait a time long enough to let the connection
421   be properly closed if needed when closing the connection (in case
422   of detach or error), if we reopen it too quickly, it seems there
423   are some events queued in the kernel concerning the "old"
424   connection/remote_desc which are discovered with poll or select on
425   the "new" connection/remote_desc.  We bypass this by waiting some
426   time to let a proper cleanup to be donex */
427void sync_gdb_connection(void)
428{
429   SysRes ret;
430   ret = VG_(poll_no_eintr)(0, 0, 100);
431   if (sr_isError(ret))
432      sr_extended_perror(ret, "sync_gdb_connection: poll error\n");
433}
434
435static
436const char * ppFinishReason (FinishReason reason)
437{
438   switch (reason) {
439   case orderly_finish:    return "orderly_finish";
440   case reset_after_error: return "reset_after_error";
441   case reset_after_fork:  return "reset_after_fork";
442   default: vg_assert (0);
443   }
444}
445
446void remote_finish (FinishReason reason)
447{
448   dlog(1, "remote_finish (reason %s) %d %d\n",
449        ppFinishReason(reason), remote_desc, write_remote_desc);
450   reset_valgrind_sink(ppFinishReason(reason));
451   if (write_remote_desc != INVALID_DESCRIPTOR)
452      VG_(close) (write_remote_desc);
453   write_remote_desc = INVALID_DESCRIPTOR;
454
455   if (remote_desc != INVALID_DESCRIPTOR && reason != reset_after_error) {
456      /* Fully close the connection, either due to orderly_finish or
457         to reset_after_fork.
458         For reset_after_error, keep the reading side opened, to always be
459         ready to accept new vgdb connection. */
460      vg_assert (reason == reset_after_fork || reason == orderly_finish);
461      remote_desc_pollfdread_activity.fd = INVALID_DESCRIPTOR;
462      remote_desc_pollfdread_activity.events = 0;
463      remote_desc_pollfdread_activity.revents = 0;
464      VG_(close) (remote_desc);
465      remote_desc = INVALID_DESCRIPTOR;
466   }
467   noack_mode = False;
468
469   /* ensure the child will create its own FIFOs */
470   if (reason == reset_after_fork)
471      mknod_done = 0;
472
473   if (reason == reset_after_error)
474      sync_gdb_connection();
475}
476
477/* orderly close, cleans up everything */
478void remote_close (void)
479{
480   const int pid = VG_(getpid)();
481   remote_finish(orderly_finish);
482   dlog(1, "%d (creator %d) maybe unlinking \n    %s\n    %s\n    %s\n",
483        pid, pid_from_to_creator,
484        from_gdb ? from_gdb : "NULL",
485        to_gdb ? to_gdb : "NULL",
486        shared_mem ? shared_mem : "NULL");
487   if (pid == pid_from_to_creator && from_gdb && VG_(unlink) (from_gdb) == -1)
488      warning ("could not unlink %s\n", from_gdb);
489   if (pid == pid_from_to_creator && to_gdb && VG_(unlink) (to_gdb) == -1)
490      warning ("could not unlink %s\n", to_gdb);
491   if (pid == pid_from_to_creator && shared_mem && VG_(unlink) (shared_mem) == -1)
492      warning ("could not unlink %s\n", shared_mem);
493   free (from_gdb);
494   from_gdb = NULL;
495   free (to_gdb);
496   to_gdb = NULL;
497   free (shared_mem);
498   shared_mem = NULL;
499}
500
501Bool remote_connected(void)
502{
503   return write_remote_desc != INVALID_DESCRIPTOR;
504}
505
506/* cleanup after an error detected by poll_cond */
507static
508void error_poll_cond(void)
509{
510   /* if we will close the connection, we assume either that
511      all characters have been seen or that they will be dropped. */
512   shared->seen_by_valgrind = shared->written_by_vgdb;
513   remote_finish(reset_after_error);
514}
515
516/* remote_desc_activity might be used at high frequency if the user
517   gives a small value to --vgdb-poll. So, the function avoids
518   doing repetitively system calls by rather looking at the
519   counter values maintained in shared memory by vgdb. */
520int remote_desc_activity(const char *msg)
521{
522   int retval;
523   SysRes ret;
524   const int looking_at = shared->written_by_vgdb;
525   if (shared->seen_by_valgrind == looking_at)
526      return 0;
527   if (remote_desc == INVALID_DESCRIPTOR)
528      return 0;
529
530   /* poll the remote desc */
531   remote_desc_pollfdread_activity.revents = 0;
532   ret = VG_(poll_no_eintr) (&remote_desc_pollfdread_activity, 1, 0);
533   if (sr_isError(ret)
534       || (sr_Res(ret) && poll_cond(remote_desc_pollfdread_activity.revents))) {
535     if (sr_isError(ret)) {
536       sr_extended_perror(ret, "remote_desc_activity: poll error\n");
537     } else {
538       dlog(0, "POLLcond %d remote_desc_pollfdread %d\n",
539            remote_desc_pollfdread_activity.revents, remote_desc);
540       error_poll_cond();
541     }
542     retval = 2;
543   } else {
544     retval = sr_Res(ret);
545   }
546   dlog(1,
547        "remote_desc_activity %s %d last_looked_cntr %d looking_at %d"
548        " shared->written_by_vgdb %d shared->seen_by_valgrind %d"
549        " retval %d\n",
550        msg, remote_desc, last_looked_cntr, looking_at,
551        shared->written_by_vgdb, shared->seen_by_valgrind,
552        retval);
553   /* if no error from poll, indicate we have "seen" up to looking_at */
554   if (retval == 1)
555      last_looked_cntr = looking_at;
556   return retval;
557}
558
559/* Convert hex digit A to a number.  */
560
561static
562int fromhex (int a)
563{
564   if (a >= '0' && a <= '9')
565      return a - '0';
566   else if (a >= 'a' && a <= 'f')
567      return a - 'a' + 10;
568   else
569      error ("Reply contains invalid hex digit 0x%x\n", a);
570   return 0;
571}
572
573int unhexify (char *bin, const char *hex, int count)
574{
575   int i;
576
577   for (i = 0; i < count; i++) {
578      if (hex[0] == 0 || hex[1] == 0) {
579         /* Hex string is short, or of uneven length.
580            Return the count that has been converted so far. */
581         return i;
582      }
583      *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
584      hex += 2;
585   }
586   return i;
587}
588
589void decode_address (CORE_ADDR *addrp, const char *start, int len)
590{
591   CORE_ADDR addr;
592   char ch;
593   int i;
594
595   addr = 0;
596   for (i = 0; i < len; i++) {
597      ch = start[i];
598      addr = addr << 4;
599      addr = addr | (fromhex (ch) & 0x0f);
600   }
601   *addrp = addr;
602}
603
604/* Convert number NIB to a hex digit.  */
605
606static
607int tohex (int nib)
608{
609   if (nib < 10)
610      return '0' + nib;
611   else
612      return 'a' + nib - 10;
613}
614
615int hexify (char *hex, const char *bin, int count)
616{
617   int i;
618
619   /* May use a length, or a nul-terminated string as input. */
620   if (count == 0)
621      count = strlen (bin);
622
623  for (i = 0; i < count; i++) {
624     *hex++ = tohex ((*bin >> 4) & 0xf);
625     *hex++ = tohex (*bin++ & 0xf);
626  }
627  *hex = 0;
628  return i;
629}
630
631/* builds an image of bin according to byte order of the architecture
632   Useful for register and int image */
633char* heximage (char *buf, char *bin, int count)
634{
635#if defined(VGA_x86) || defined(VGA_amd64)
636   char rev[count];
637   /* note: no need for trailing \0, length is known with count */
638  int i;
639  for (i = 0; i < count; i++)
640    rev[i] = bin[count - i - 1];
641  hexify (buf, rev, count);
642#else
643  hexify (buf, bin, count);
644#endif
645  return buf;
646}
647
648void* C2v(CORE_ADDR addr)
649{
650   return (void*) addr;
651}
652
653
654/* Convert BUFFER, binary data at least LEN bytes long, into escaped
655   binary data in OUT_BUF.  Set *OUT_LEN to the length of the data
656   encoded in OUT_BUF, and return the number of bytes in OUT_BUF
657   (which may be more than *OUT_LEN due to escape characters).  The
658   total number of bytes in the output buffer will be at most
659   OUT_MAXLEN.  */
660
661int
662remote_escape_output (const gdb_byte *buffer, int len,
663		      gdb_byte *out_buf, int *out_len,
664		      int out_maxlen)
665{
666   int input_index, output_index;
667
668   output_index = 0;
669   for (input_index = 0; input_index < len; input_index++) {
670      gdb_byte b = buffer[input_index];
671
672      if (b == '$' || b == '#' || b == '}' || b == '*') {
673         /* These must be escaped.  */
674         if (output_index + 2 > out_maxlen)
675	    break;
676         out_buf[output_index++] = '}';
677         out_buf[output_index++] = b ^ 0x20;
678      } else {
679         if (output_index + 1 > out_maxlen)
680	    break;
681         out_buf[output_index++] = b;
682      }
683   }
684
685   *out_len = input_index;
686   return output_index;
687}
688
689/* Convert BUFFER, escaped data LEN bytes long, into binary data
690   in OUT_BUF.  Return the number of bytes written to OUT_BUF.
691   Raise an error if the total number of bytes exceeds OUT_MAXLEN.
692
693   This function reverses remote_escape_output.  It allows more
694   escaped characters than that function does, in particular because
695   '*' must be escaped to avoid the run-length encoding processing
696   in reading packets.  */
697
698static
699int remote_unescape_input (const gdb_byte *buffer, int len,
700		       gdb_byte *out_buf, int out_maxlen)
701{
702   int input_index, output_index;
703   int escaped;
704
705   output_index = 0;
706   escaped = 0;
707   for (input_index = 0; input_index < len; input_index++) {
708      gdb_byte b = buffer[input_index];
709
710      if (output_index + 1 > out_maxlen)
711         error ("Received too much data (len %d) from the target.\n", len);
712
713      if (escaped) {
714         out_buf[output_index++] = b ^ 0x20;
715         escaped = 0;
716      } else if (b == '}') {
717         escaped = 1;
718      } else {
719         out_buf[output_index++] = b;
720      }
721   }
722
723   if (escaped)
724      error ("Unmatched escape character in target response.\n");
725
726   return output_index;
727}
728
729/* Look for a sequence of characters which can be run-length encoded.
730   If there are any, update *CSUM and *P.  Otherwise, output the
731   single character.  Return the number of characters consumed.  */
732
733static
734int try_rle (char *buf, int remaining, unsigned char *csum, char **p)
735{
736   int n;
737
738   /* Always output the character.  */
739   *csum += buf[0];
740   *(*p)++ = buf[0];
741
742   /* Don't go past '~'.  */
743   if (remaining > 97)
744      remaining = 97;
745
746   for (n = 1; n < remaining; n++)
747      if (buf[n] != buf[0])
748         break;
749
750   /* N is the index of the first character not the same as buf[0].
751      buf[0] is counted twice, so by decrementing N, we get the number
752      of characters the RLE sequence will replace.  */
753   n--;
754
755   if (n < 3)
756      return 1;
757
758   /* Skip the frame characters.  The manual says to skip '+' and '-'
759      also, but there's no reason to.  Unfortunately these two unusable
760      characters double the encoded length of a four byte zero
761      value.  */
762   while (n + 29 == '$' || n + 29 == '#')
763      n--;
764
765   *csum += '*';
766   *(*p)++ = '*';
767   *csum += n + 29;
768   *(*p)++ = n + 29;
769
770   return n + 1;
771}
772
773/* Send a packet to the remote machine, with error checking.
774   The data of the packet is in BUF, and the length of the
775   packet is in CNT.  Returns >= 0 on success, -1 otherwise.  */
776
777int putpkt_binary (char *buf, int cnt)
778{
779   int i;
780   unsigned char csum = 0;
781   char *buf2;
782   char *p;
783   int cc;
784
785   buf2 = malloc (PBUFSIZ+POVERHSIZ);
786   // should malloc PBUFSIZ, but bypass GDB bug (see gdbserver_init in server.c)
787   vg_assert (5 == POVERHSIZ);
788   vg_assert (cnt <= PBUFSIZ); // be tolerant for GDB bug.
789
790   /* Copy the packet into buffer BUF2, encapsulating it
791      and giving it a checksum.  */
792
793   p = buf2;
794   *p++ = '$';
795
796   for (i = 0; i < cnt;)
797      i += try_rle (buf + i, cnt - i, &csum, &p);
798
799   *p++ = '#';
800   *p++ = tohex ((csum >> 4) & 0xf);
801   *p++ = tohex (csum & 0xf);
802
803   *p = '\0';
804
805   /* we might have to write a pkt when out FIFO not yet/anymore opened */
806   if (!ensure_write_remote_desc()) {
807      warning ("putpkt(write) error: no write_remote_desc\n");
808      return -1;
809   }
810
811   /* Send it once (noack_mode)
812      or send it over and over until we get a positive ack.  */
813
814   do {
815      if (VG_(write) (write_remote_desc, buf2, p - buf2) != p - buf2) {
816         warning ("putpkt(write) error\n");
817         return -1;
818      }
819
820      if (noack_mode)
821         dlog(1, "putpkt (\"%s\"); [no ack]\n", buf2);
822      else
823         dlog(1,"putpkt (\"%s\"); [looking for ack]\n", buf2);
824
825      if (noack_mode)
826         break;
827
828      cc = readchar (1);
829      if (cc > 0)
830         dlog(1, "[received '%c' (0x%x)]\n", cc, cc);
831
832      if (cc <= 0) {
833         if (cc == 0)
834            dlog(1, "putpkt(read): Got EOF\n");
835         else
836	    warning ("putpkt(read) error\n");
837
838         free (buf2);
839         return -1;
840      }
841
842      /* Check for an input interrupt while we're here.  */
843      if (cc == '\003')
844         dlog(1, "Received 0x03 character (SIGINT)\n");
845   }
846   while (cc != '+');
847
848   free (buf2);
849   return 1;			/* Success! */
850}
851
852/* Send a packet to the remote machine, with error checking.  The data
853   of the packet is in BUF, and the packet should be a NUL-terminated
854   string.  Returns >= 0 on success, -1 otherwise.  */
855
856int putpkt (char *buf)
857{
858   return putpkt_binary (buf, strlen (buf));
859}
860
861void monitor_output (char *s)
862{
863   if (remote_connected()) {
864      const int len = strlen(s);
865      char *buf = malloc(1 + 2*len + 1);
866
867      buf[0] = 'O';
868      hexify(buf+1, s, len);
869      if (putpkt (buf) < 0) {
870         /* We probably have lost the connection with vgdb. */
871         reset_valgrind_sink("Error writing monitor output");
872         /* write again after reset */
873         VG_(printf) ("%s", s);
874      }
875
876      free (buf);
877   } else {
878      print_to_initial_valgrind_sink (s);
879   }
880}
881
882/* Returns next char from remote GDB.  -1 if error.  */
883/* if single, only one character maximum can be read with
884   read system call. Otherwise, when reading an ack character
885   we might pile up the next gdb command in the static buf.
886   The read loop is then blocked in poll till gdb times out. */
887static
888int readchar (int single)
889{
890   static unsigned char buf[PBUFSIZ];
891   static int bufcnt = 0;
892   static unsigned char *bufp;
893   SysRes ret;
894
895   if (bufcnt-- > 0)
896      return *bufp++;
897
898   if (remote_desc == INVALID_DESCRIPTOR)
899      return -1;
900
901   /* No characters available in buf =>
902      wait for some characters to arrive */
903   remote_desc_pollfdread_activity.revents = 0;
904   ret = VG_(poll_no_eintr)(&remote_desc_pollfdread_activity, 1, -1);
905   if (sr_isError(ret) || sr_Res(ret) != 1) {
906     if (sr_isError(ret)) {
907        sr_extended_perror(ret, "readchar: poll error\n");
908     } else {
909        dlog(0, "readchar: poll got %d, expecting 1\n", (int)sr_Res(ret));
910     }
911     return -1;
912   }
913   if (single)
914      bufcnt = VG_(read) (remote_desc, buf, 1);
915   else
916      bufcnt = VG_(read) (remote_desc, buf, sizeof (buf));
917
918   if (bufcnt <= 0) {
919      if (bufcnt == 0)
920         dlog (1, "readchar: Got EOF\n");
921      else
922         warning ("readchar read error\n");
923
924      return -1;
925   }
926
927   shared->seen_by_valgrind += bufcnt;
928
929   /* If we have received a character and we do not yet have a
930      connection, we better open our "write" fifo to let vgdb open its
931      read fifo side */
932   if (write_remote_desc == INVALID_DESCRIPTOR
933       && !ensure_write_remote_desc()) {
934      dlog(1, "reachar: write_remote_desc could not be created");
935   }
936
937   bufp = buf;
938   bufcnt--;
939
940   if (poll_cond(remote_desc_pollfdread_activity.revents)) {
941      dlog(1, "readchar: POLLcond got %d\n",
942           remote_desc_pollfdread_activity.revents);
943      error_poll_cond();
944   }
945
946   return *bufp++;
947}
948
949
950/* Read a packet from the remote machine, with error checking,
951   and store it in BUF.  Returns length of packet, or negative if error. */
952
953int getpkt (char *buf)
954{
955   char *bp;
956   unsigned char csum, c1, c2;
957   int c;
958
959   while (1) {
960      csum = 0;
961
962      while (1) {
963         c = readchar (0);
964         if (c == '$')
965	    break;
966         dlog(1, "[getpkt: discarding char '%c']\n", c);
967         if (c < 0)
968	    return -1;
969      }
970
971      bp = buf;
972      while (1) {
973         c = readchar (0);
974         if (c < 0)
975	    return -1;
976         if (c == '#')
977	    break;
978         *bp++ = c;
979         csum += c;
980      }
981      *bp = 0;
982
983      c1 = fromhex (readchar (0));
984      c2 = fromhex (readchar (0));
985
986      if (csum == (c1 << 4) + c2)
987         break;
988
989      dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
990            (c1 << 4) + c2, csum, buf);
991      if (!ensure_write_remote_desc()) {
992         dlog(1, "getpkt(write nack) no write_remote_desc");
993      }
994      VG_(write) (write_remote_desc, "-", 1);
995   }
996
997   if (noack_mode)
998      dlog(1, "getpkt (\"%s\");  [no ack] \n", buf);
999   else
1000      dlog(1, "getpkt (\"%s\");  [sending ack] \n", buf);
1001
1002   if (!noack_mode) {
1003      if (!ensure_write_remote_desc()) {
1004         dlog(1, "getpkt(write ack) no write_remote_desc");
1005      }
1006      VG_(write) (write_remote_desc, "+", 1);
1007      dlog(1, "[sent ack]\n");
1008   }
1009
1010   return bp - buf;
1011}
1012
1013void write_ok (char *buf)
1014{
1015   buf[0] = 'O';
1016   buf[1] = 'K';
1017   buf[2] = '\0';
1018}
1019
1020void write_enn (char *buf)
1021{
1022   /* Some day, we should define the meanings of the error codes... */
1023   buf[0] = 'E';
1024   buf[1] = '0';
1025   buf[2] = '1';
1026   buf[3] = '\0';
1027}
1028
1029void convert_int_to_ascii (const unsigned char *from, char *to, int n)
1030{
1031   int nib;
1032   int ch;
1033   while (n--) {
1034      ch = *from++;
1035      nib = ((ch & 0xf0) >> 4) & 0x0f;
1036      *to++ = tohex (nib);
1037      nib = ch & 0x0f;
1038      *to++ = tohex (nib);
1039   }
1040   *to++ = 0;
1041}
1042
1043
1044void convert_ascii_to_int (const char *from, unsigned char *to, int n)
1045{
1046   int nib1, nib2;
1047   while (n--) {
1048      nib1 = fromhex (*from++);
1049      nib2 = fromhex (*from++);
1050      *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
1051   }
1052}
1053
1054static
1055char * outreg (int regno, char *buf)
1056{
1057   if ((regno >> 12) != 0)
1058      *buf++ = tohex ((regno >> 12) & 0xf);
1059   if ((regno >> 8) != 0)
1060      *buf++ = tohex ((regno >> 8) & 0xf);
1061   *buf++ = tohex ((regno >> 4) & 0xf);
1062   *buf++ = tohex (regno & 0xf);
1063   *buf++ = ':';
1064   collect_register_as_string (regno, buf);
1065   buf += 2 * register_size (regno);
1066   *buf++ = ';';
1067
1068   return buf;
1069}
1070
1071void prepare_resume_reply (char *buf, char status, unsigned char sig)
1072{
1073   int nib;
1074
1075   *buf++ = status;
1076
1077   nib = ((sig & 0xf0) >> 4);
1078   *buf++ = tohex (nib);
1079   nib = sig & 0x0f;
1080   *buf++ = tohex (nib);
1081
1082   if (status == 'T') {
1083      const char **regp = gdbserver_expedite_regs;
1084
1085      if (valgrind_stopped_by_watchpoint()) {
1086         CORE_ADDR addr;
1087         int i;
1088
1089         strncpy (buf, "watch:", 6);
1090         buf += 6;
1091
1092         addr = valgrind_stopped_data_address ();
1093
1094         /* Convert each byte of the address into two hexadecimal chars.
1095            Note that we take sizeof (void *) instead of sizeof (addr);
1096            this is to avoid sending a 64-bit address to a 32-bit GDB.  */
1097         for (i = sizeof (void *) * 2; i > 0; i--) {
1098            *buf++ = tohex ((addr >> (i - 1) * 4) & 0xf);
1099         }
1100         *buf++ = ';';
1101      }
1102
1103      while (*regp) {
1104         buf = outreg (find_regno (*regp), buf);
1105         regp ++;
1106      }
1107
1108      {
1109         unsigned int gdb_id_from_wait;
1110
1111         /* FIXME right place to set this? */
1112         thread_from_wait =
1113            ((struct inferior_list_entry *)current_inferior)->id;
1114         gdb_id_from_wait = thread_to_gdb_id (current_inferior);
1115
1116         dlog(1, "Writing resume reply for %ld\n", thread_from_wait);
1117         /* This if (1) ought to be unnecessary.  But remote_wait in GDB
1118            will claim this event belongs to inferior_ptid if we do not
1119            specify a thread, and there's no way for gdbserver to know
1120            what inferior_ptid is.  */
1121         if (1 || old_thread_from_wait != thread_from_wait) {
1122            general_thread = thread_from_wait;
1123            VG_(sprintf) (buf, "thread:%x;", gdb_id_from_wait);
1124            buf += strlen (buf);
1125            old_thread_from_wait = thread_from_wait;
1126         }
1127      }
1128   }
1129   /* For W and X, we're done.  */
1130   *buf++ = 0;
1131}
1132
1133void decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1134{
1135   int i = 0, j = 0;
1136   char ch;
1137   *mem_addr_ptr = *len_ptr = 0;
1138
1139   while ((ch = from[i++]) != ',') {
1140      *mem_addr_ptr = *mem_addr_ptr << 4;
1141      *mem_addr_ptr |= fromhex (ch) & 0x0f;
1142   }
1143
1144   for (j = 0; j < 4; j++) {
1145      if ((ch = from[i++]) == 0)
1146         break;
1147      *len_ptr = *len_ptr << 4;
1148      *len_ptr |= fromhex (ch) & 0x0f;
1149   }
1150}
1151
1152void decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1153		 unsigned char *to)
1154{
1155   int i = 0;
1156   char ch;
1157   *mem_addr_ptr = *len_ptr = 0;
1158
1159   while ((ch = from[i++]) != ',') {
1160      *mem_addr_ptr = *mem_addr_ptr << 4;
1161      *mem_addr_ptr |= fromhex (ch) & 0x0f;
1162   }
1163
1164   while ((ch = from[i++]) != ':') {
1165      *len_ptr = *len_ptr << 4;
1166      *len_ptr |= fromhex (ch) & 0x0f;
1167   }
1168
1169   convert_ascii_to_int (&from[i++], to, *len_ptr);
1170}
1171
1172int decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1173		 unsigned int *len_ptr, unsigned char *to)
1174{
1175   int i = 0;
1176   char ch;
1177   *mem_addr_ptr = *len_ptr = 0;
1178
1179   while ((ch = from[i++]) != ',') {
1180      *mem_addr_ptr = *mem_addr_ptr << 4;
1181      *mem_addr_ptr |= fromhex (ch) & 0x0f;
1182   }
1183
1184   while ((ch = from[i++]) != ':') {
1185      *len_ptr = *len_ptr << 4;
1186      *len_ptr |= fromhex (ch) & 0x0f;
1187   }
1188
1189   if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1190                              to, *len_ptr) != *len_ptr)
1191      return -1;
1192
1193   return 0;
1194}
1195
1196
1197/* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
1198   to communicate with valgrind */
1199HChar *
1200VG_(vgdb_prefix_default)(void)
1201{
1202   static HChar *prefix;
1203
1204   if (prefix == NULL) {
1205     const HChar *tmpdir = VG_(tmpdir)();
1206     prefix = malloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
1207     strcpy(prefix, tmpdir);
1208     strcat(prefix, "/vgdb-pipe");
1209   }
1210   return prefix;
1211}
1212