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