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