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