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