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