FreeBSD Helgrind: turn off check for locks held on exit for FreeBSD 14.2
[valgrind.git] / coregrind / m_gdbserver / remote-utils.c
blobb22dc4482bf006f985022533773997d1e04170f0
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.
6 This file is part of GDB.
7 It has been modified to integrate it in valgrind
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.
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.
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. */
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 #include "pub_core_syswrap.h"
32 #include "server.h"
34 # if defined(VGO_linux)
35 #include <sys/prctl.h>
36 # endif
38 /* Calls sr_perror with msg.
39 Outputs more information about Valgrind state if verbosity > 0
40 or debuglog_getlevel > 0. */
41 static
42 void sr_extended_perror (SysRes sr, const HChar *msg)
44 sr_perror (sr, "%s", msg);
45 if (VG_(clo_verbosity) > 0 || VG_(debugLog_getLevel)() >= 1) {
46 Int i;
47 vki_sigset_t cursigset;
48 VG_(show_sched_status) (True, // host_stacktrace
49 True, // stack_usage
50 True); // exited_threads
51 VG_(sigprocmask) (0, // dummy how.
52 NULL, // do not change the sigmask
53 &cursigset); //
54 VG_(dmsg)("current sigmask value { ");
55 for (i = 1; i <= _VKI_NSIG; i++) {
56 if (VG_(sigismember)(&cursigset, i))
57 VG_(dmsg)("%d ", i);
59 VG_(dmsg)("}\n");
63 /* Calls VG_(poll) with given arguments. If VG_(poll) fails due to EINTR,
64 restarts the syscall.
65 Normally, VG_(poll) gdbsrv syscalls are not supposed to be interrupted :
66 either gdbsrv has been called by the scheduler (so all async signals
67 are masked)
68 or gdbsrv has been forced invoked by vgdb+ptrace, and vgdb is queuing
69 the signals.
71 However, on old kernels (such as on RHEL5.5 2.6.18), when vgdb+ptrace
72 intercepts and queues an async signal, the poll syscall is not properly
73 restarted. Instead, it returns EINTR even if no signal was effectively
74 received by the ptraced process.
75 See red-hat "Bug 679129 - Change in behaviour between RH5.5 and RH6
76 with ptrace and syscalls bugzilla"
77 e.g. "Why rhel5 differs? Because unlike in rhel6, sys_poll() returns
78 -EINTR if interrupted, that is all. This old implementation does
79 not support the restart-if-eintr-is-spurious."
81 So in case VG_(poll) fails with EINTR, we retry. */
82 static SysRes VG_(poll_no_eintr) (struct vki_pollfd *fds, Int nfds, Int timeout)
84 const HChar* msg = "VG_(poll) failed (old kernel ?) retrying ... \n";
85 SysRes sr;
86 do {
87 sr = VG_(poll) (fds, nfds, timeout);
88 if (!sr_isError(sr) || sr_Err(sr) != VKI_EINTR)
89 return sr;
90 sr_perror (sr, "%s", msg);
91 if (VG_(debugLog_getLevel)() >= 1) {
92 sr_extended_perror (sr, msg);
94 } while (1);
95 /*NOTREACHED*/
98 Bool noack_mode;
100 static int readchar (int single);
102 void remote_utils_output_status(void);
104 #define INVALID_DESCRIPTOR -1
105 static int remote_desc = INVALID_DESCRIPTOR;
107 static VgdbShared *shared;
108 static int last_looked_cntr = -1;
109 static struct vki_pollfd remote_desc_pollfdread_activity;
111 /* for a gdbserver embedded in valgrind, we read from a FIFO and write
112 to another FIFO So, we need two descriptors */
113 static int write_remote_desc = INVALID_DESCRIPTOR;
114 static int pid_from_to_creator;
115 /* only this pid will remove the FIFOs: if an exec fails, we must avoid
116 that the exiting child believes it has to remove the FIFOs of its parent */
117 static int mknod_done = 0;
119 static char *from_gdb = NULL;
120 static char *to_gdb = NULL;
121 static char *shared_mem = NULL;
123 static
124 int open_fifo (const char *side, const char *path, int flags)
126 SysRes o;
127 int fd;
128 dlog(1, "Opening %s side %s\n", side, path);
129 o = VG_(open) (path, flags, 0);
130 if (sr_isError (o)) {
131 sr_perror(o, "open fifo %s\n", path);
132 fatal ("valgrind: fatal error: vgdb FIFO cannot be opened.\n");
133 } else {
134 fd = sr_Res(o);
135 dlog(1, "result fd %d\n", fd);
137 fd = VG_(safe_fd)(fd);
138 dlog(1, "result safe_fd %d\n", fd);
139 if (fd == -1)
140 fatal("safe_fd for vgdb FIFO failed\n");
141 return fd;
144 void remote_utils_output_status(void)
146 if (shared == NULL)
147 VG_(umsg)("remote communication not initialized\n");
148 else
149 VG_(umsg)("shared->written_by_vgdb %d shared->seen_by_valgrind %d\n",
150 shared->written_by_vgdb, shared->seen_by_valgrind);
153 /* Returns 0 if vgdb and connection state looks good,
154 otherwise returns an int value telling which check failed. */
155 static
156 int vgdb_state_looks_bad(const char* where)
158 if (VG_(kill)(shared->vgdb_pid, 0) != 0)
159 return 1; // vgdb process does not exist anymore.
161 if (remote_desc_activity(where) == 2)
162 return 2; // check for error on remote desc shows a problem
164 if (remote_desc == INVALID_DESCRIPTOR)
165 return 3; // after check, remote_desc not ok anymore
167 return 0; // all is ok.
170 void VG_(set_ptracer)(void)
172 #ifdef PR_SET_PTRACER
173 SysRes o;
174 const char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
175 int fd;
176 char ptrace_scope;
177 int ret;
179 o = VG_(open) (ptrace_scope_setting_file, VKI_O_RDONLY, 0);
180 if (sr_isError(o)) {
181 if (VG_(debugLog_getLevel)() >= 1) {
182 sr_perror(o, "error VG_(open) %s\n", ptrace_scope_setting_file);
184 /* can't read setting. Assuming ptrace can be called by vgdb. */
185 return;
187 fd = sr_Res(o);
188 if (VG_(read) (fd, &ptrace_scope, 1) == 1) {
189 dlog(1, "ptrace_scope %c\n", ptrace_scope);
190 if (ptrace_scope != '0') {
191 /* insufficient default ptrace_scope.
192 Indicate to the kernel that we accept to be ptraced. */
193 #ifdef PR_SET_PTRACER_ANY
194 ret = VG_(prctl) (PR_SET_PTRACER, PR_SET_PTRACER_ANY, 0, 0, 0);
195 dlog(1, "set_ptracer to PR_SET_PTRACER_ANY result %d\n", ret);
196 #else
197 ret = VG_(prctl) (PR_SET_PTRACER, 1, 0, 0, 0);
198 dlog(1, "set_ptracer to 1 result %d\n", ret);
199 #endif
200 if (ret)
201 VG_(umsg)("error calling PR_SET_PTRACER, vgdb might block\n");
203 } else {
204 dlog(0, "Could not read the ptrace_scope setting from %s\n",
205 ptrace_scope_setting_file);
208 VG_(close) (fd);
209 #endif
212 /* returns 1 if one or more poll "errors" is set.
213 Errors are: VKI_POLLERR or VKI_POLLHUP or VKI_POLLNAL */
214 static
215 int poll_cond (short revents)
217 return (revents & (VKI_POLLERR | VKI_POLLHUP | VKI_POLLNVAL));
220 /* Ensures we have a valid write file descriptor.
221 Returns 1 if we have a valid write file descriptor,
222 0 if the write fd is not valid/cannot be opened. */
223 static
224 int ensure_write_remote_desc(void)
226 struct vki_pollfd write_remote_desc_ok;
227 SysRes ret;
228 if (write_remote_desc != INVALID_DESCRIPTOR) {
229 write_remote_desc_ok.fd = write_remote_desc;
230 write_remote_desc_ok.events = VKI_POLLOUT;
231 write_remote_desc_ok.revents = 0;
232 ret = VG_(poll_no_eintr)(&write_remote_desc_ok, 1, 0);
233 if (sr_isError(ret)
234 || (sr_Res(ret) > 0 && poll_cond(write_remote_desc_ok.revents))) {
235 if (sr_isError(ret)) {
236 sr_extended_perror(ret, "ensure_write_remote_desc: poll error\n");
237 } else {
238 dlog(0, "POLLcond %d closing write_remote_desc %d\n",
239 write_remote_desc_ok.revents, write_remote_desc);
241 VG_(close) (write_remote_desc);
242 write_remote_desc = INVALID_DESCRIPTOR;
245 if (write_remote_desc == INVALID_DESCRIPTOR) {
246 /* open_fifo write will block if the receiving vgdb
247 process is dead. So, let's check for vgdb state to
248 be reasonably sure someone is reading on the other
249 side of the fifo. */
250 if (!vgdb_state_looks_bad("bad?@ensure_write_remote_desc")) {
251 write_remote_desc = open_fifo ("write", to_gdb, VKI_O_WRONLY);
255 return (write_remote_desc != INVALID_DESCRIPTOR);
258 #if defined(VGO_darwin)
259 #define VKI_S_IFIFO 0010000
260 #endif
261 static
262 void safe_mknod (char *nod)
264 SysRes m;
265 m = VG_(mknod) (nod, VKI_S_IFIFO|0600, 0);
266 if (sr_isError (m)) {
267 if (sr_Err (m) == VKI_EEXIST) {
268 if (VG_(clo_verbosity) > 1) {
269 VG_(umsg)("%s already created\n", nod);
271 } else {
272 sr_perror(m, "mknod %s\n", nod);
273 VG_(umsg) ("valgrind: fatal error: vgdb FIFOs cannot be created.\n");
274 VG_(exit)(1);
279 /* If remote_desc is not opened, open it.
280 Setup remote_desc_pollfdread_activity. */
281 static void setup_remote_desc_for_reading (void)
283 int save_fcntl_flags;
285 if (remote_desc == INVALID_DESCRIPTOR) {
286 /* we open the read side FIFO in non blocking mode
287 We then set the fd in blocking mode.
288 Opening in non-blocking read mode always succeeds while opening
289 in non-blocking write mode succeeds only if the fifo is already
290 opened in read mode. So, we wait till we have read the first
291 character from the read side before opening the write side. */
292 remote_desc = open_fifo ("read", from_gdb, VKI_O_RDONLY|VKI_O_NONBLOCK);
293 save_fcntl_flags = VG_(fcntl) (remote_desc, VKI_F_GETFL, 0);
294 VG_(fcntl) (remote_desc, VKI_F_SETFL, save_fcntl_flags & ~VKI_O_NONBLOCK);
296 remote_desc_pollfdread_activity.fd = remote_desc;
297 remote_desc_pollfdread_activity.events = VKI_POLLIN;
298 remote_desc_pollfdread_activity.revents = 0;
301 /* Open a connection to a remote debugger.
302 NAME is the filename used for communication.
303 For Valgrind, name is the prefix for the two read and write FIFOs
304 The two FIFOs names will be build by appending
305 -from-vgdb-to-pid-by-user-on-host and -to-vgdb-from-pid-by-user-on-host
306 with pid being the pidnr of the valgrind process These two FIFOs
307 will be created if not existing yet. They will be removed when
308 the gdbserver connection is closed or the process exits */
310 void remote_open (const HChar *name)
312 const HChar *user, *host;
313 int len;
314 VgdbShared vgdbinit;
315 const int pid = VG_(getpid)();
316 Addr addr_shared;
317 SysRes o;
318 int shared_mem_fd = INVALID_DESCRIPTOR;
320 VG_(memset) (&vgdbinit, 0, sizeof (VgdbShared));
321 vgdbinit = (VgdbShared)
322 {0, 0, (Addr) VG_(invoke_gdbserver),
323 (Addr) VG_(threads), VG_N_THREADS, sizeof(ThreadState),
324 offsetof(ThreadState, status),
325 offsetof(ThreadState, os_state) + offsetof(ThreadOSstate, lwpid),
327 #if VEX_HOST_WORDSIZE == 8
329 #endif
332 user = VG_(getenv)("LOGNAME");
333 if (user == NULL) user = VG_(getenv)("USER");
334 if (user == NULL) user = "???";
335 if (VG_(strchr)(user, '/')) user = "???";
337 host = VG_(getenv)("HOST");
338 if (host == NULL) host = VG_(getenv)("HOSTNAME");
339 if (host == NULL) host = "???";
340 if (VG_(strchr)(host, '/')) host = "???";
342 len = strlen(name) + strlen(user) + strlen(host) + 40;
344 if (from_gdb != NULL)
345 free (from_gdb);
346 from_gdb = malloc (len);
347 if (to_gdb != NULL)
348 free (to_gdb);
349 to_gdb = malloc (len);
350 if (shared_mem != NULL)
351 free (shared_mem);
352 shared_mem = malloc (len);
353 /* below 3 lines must match the equivalent in vgdb.c */
354 VG_(sprintf) (from_gdb, "%s-from-vgdb-to-%d-by-%s-on-%s", name,
355 pid, user, host);
356 VG_(sprintf) (to_gdb, "%s-to-vgdb-from-%d-by-%s-on-%s", name,
357 pid, user, host);
358 VG_(sprintf) (shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", name,
359 pid, user, host);
360 if (VG_(clo_verbosity) > 1) {
361 VG_(umsg)("embedded gdbserver: reading from %s\n", from_gdb);
362 VG_(umsg)("embedded gdbserver: writing to %s\n", to_gdb);
363 VG_(umsg)("embedded gdbserver: shared mem %s\n", shared_mem);
364 VG_(umsg)("\n");
365 VG_(umsg)("TO CONTROL THIS PROCESS USING vgdb (which you probably\n"
366 "don't want to do, unless you know exactly what you're doing,\n"
367 "or are doing some strange experiment):\n"
368 " %s/../../bin/vgdb%s%s --pid=%d ...command...\n",
369 VG_(libdir),
370 (VG_(arg_vgdb_prefix) ? " " : ""),
371 (VG_(arg_vgdb_prefix) ? VG_(arg_vgdb_prefix) : ""),
372 pid);
374 if (VG_(clo_verbosity) > 1
375 || ((VG_(clo_vgdb_error) < 999999999
376 || VG_(clo_vgdb_stop_at) != 0)
377 && !(VG_(clo_launched_with_multi)))) {
378 VG_(umsg)("\n");
379 VG_(umsg)(
380 "TO DEBUG THIS PROCESS USING GDB: start GDB like this\n"
381 " /path/to/gdb %s\n"
382 "and then give GDB the following command\n"
383 " target remote | %s/../../bin/vgdb%s%s --pid=%d\n",
384 VG_(args_the_exename),
385 VG_(libdir),
386 (VG_(arg_vgdb_prefix) ? " " : ""),
387 (VG_(arg_vgdb_prefix) ? VG_(arg_vgdb_prefix) : ""),
390 VG_(umsg)("--pid is optional if only one valgrind process is running\n");
391 VG_(umsg)("\n");
394 if (!mknod_done) {
395 mknod_done++;
396 VG_(set_ptracer)();
398 * Unlink just in case a previous process with the same PID had been
399 * killed and hence Valgrind hasn't had the chance yet to remove these.
401 VG_(unlink)(from_gdb);
402 VG_(unlink)(to_gdb);
403 VG_(unlink)(shared_mem);
405 o = VG_(open) (shared_mem, VKI_O_CREAT|VKI_O_RDWR, 0600);
406 if (sr_isError (o)) {
407 sr_perror(o, "cannot create shared_mem file %s\n", shared_mem);
408 fatal("Cannot recover from previous error. Good-bye.");
409 } else {
410 shared_mem_fd = sr_Res(o);
413 if (VG_(write)(shared_mem_fd, &vgdbinit, sizeof(VgdbShared))
414 != sizeof(VgdbShared)) {
415 fatal("error writing %d bytes to shared mem %s\n",
416 (int) sizeof(VgdbShared), shared_mem);
419 SysRes res = VG_(am_shared_mmap_file_float_valgrind)
420 (sizeof(VgdbShared), VKI_PROT_READ|VKI_PROT_WRITE,
421 shared_mem_fd, (Off64T)0);
422 if (sr_isError(res)) {
423 sr_perror(res, "error VG_(am_shared_mmap_file_float_valgrind) %s\n",
424 shared_mem);
425 fatal("Cannot recover from previous error. Good-bye.");
427 addr_shared = sr_Res (res);
429 shared = (VgdbShared*) addr_shared;
430 VG_(close) (shared_mem_fd);
432 safe_mknod(to_gdb);
433 safe_mknod(from_gdb);
434 /* from_gdb is the last resource created: vgdb searches such FIFOs
435 to detect the presence of a valgrind process.
436 So, we better create this resource when all the rest needed by
437 vgdb is ready : the other FIFO and the shared memory. */
439 pid_from_to_creator = pid;
442 setup_remote_desc_for_reading ();
445 /* sync_gdb_connection wait a time long enough to let the connection
446 be properly closed if needed when closing the connection (in case
447 of detach or error), if we reopen it too quickly, it seems there
448 are some events queued in the kernel concerning the "old"
449 connection/remote_desc which are discovered with poll or select on
450 the "new" connection/remote_desc. We bypass this by waiting some
451 time to let a proper cleanup to be donex */
452 void sync_gdb_connection(void)
454 SysRes ret;
455 ret = VG_(poll_no_eintr)(0, 0, 100);
456 if (sr_isError(ret))
457 sr_extended_perror(ret, "sync_gdb_connection: poll error\n");
460 static
461 const char * ppFinishReason (FinishReason reason)
463 switch (reason) {
464 case orderly_finish: return "orderly_finish";
465 case reset_after_error: return "reset_after_error";
466 case reset_after_fork: return "reset_after_fork";
467 default: vg_assert (0);
471 void remote_finish (FinishReason reason)
473 dlog(1, "remote_finish (reason %s) %d %d\n",
474 ppFinishReason(reason), remote_desc, write_remote_desc);
475 reset_valgrind_sink(ppFinishReason(reason));
476 if (write_remote_desc != INVALID_DESCRIPTOR)
477 VG_(close) (write_remote_desc);
478 write_remote_desc = INVALID_DESCRIPTOR;
480 if (remote_desc != INVALID_DESCRIPTOR) {
481 /* Fully close the connection, either due to orderly_finish or
482 to reset_after_fork or reset_after_error. For
483 reset_after_error, the FIFO will be re-opened soon. This
484 leaves a small window during which a race condition can
485 happen between vgdb and a forking process: Just after fork,
486 both the parent and the child have the FIFO open. The child
487 will close it asap (as part of the 'after fork cleanup'). If
488 2 vgdbs are launched very quickly just after the fork, the
489 parent will close its FIFO when the 1st vgdb exits. Then if
490 the 2nd vgdb is started before the parent has the time to
491 re-open the FIFO, the 2nd vgdb will be able to open the FIFO
492 (as it is still opened by the child). The 2nd vgdb can then
493 have a 'write' error when the child closes the FIFO. After
494 the 1st vgdb closes its FIFO write side, the parent gets EOF
495 on its reading FIFO till it is closed and re-opened. Opening
496 a 2nd time the FIFO before closing the 'previous fd' solves
497 this race condition, but causes other (not understood)
498 problems due to too early re-invocation of gdbsrv. Rather
499 than to handle this race condition in gdbsrv side, we put a
500 'retry' loop in vgdb for the initial write on the write
501 FIFO. */
502 remote_desc_pollfdread_activity.fd = INVALID_DESCRIPTOR;
503 remote_desc_pollfdread_activity.events = 0;
504 remote_desc_pollfdread_activity.revents = 0;
505 VG_(close) (remote_desc);
506 remote_desc = INVALID_DESCRIPTOR;
508 noack_mode = False;
510 /* ensure the child will create its own FIFOs */
511 if (reason == reset_after_fork)
512 mknod_done = 0;
514 if (reason == reset_after_error)
515 sync_gdb_connection();
518 /* orderly close, cleans up everything */
519 void remote_close (void)
521 const int pid = VG_(getpid)();
522 remote_finish(orderly_finish);
523 dlog(1, "%d (creator %d) maybe unlinking \n %s\n %s\n %s\n",
524 pid, pid_from_to_creator,
525 from_gdb ? from_gdb : "NULL",
526 to_gdb ? to_gdb : "NULL",
527 shared_mem ? shared_mem : "NULL");
529 // PJF this is not ideal
530 // if the guest enters capability mode then the unlink calls will fail
531 // this may well also apply to Linux and seccomp
532 // I don't have any thoughts on how to fix it, other than forking early on
533 // having the child run the guest and the parent wait()ing and then
534 // the parent doing the cleanup
536 Bool unlinkPossible = True;
537 #if defined(VGO_freebsd)
538 unlinkPossible = (VG_(get_capability_mode)() == False);
539 #endif
541 if (unlinkPossible == True) {
542 if (pid == pid_from_to_creator && from_gdb && VG_(unlink) (from_gdb) == -1)
543 warning ("could not unlink %s\n", from_gdb);
544 if (pid == pid_from_to_creator && to_gdb && VG_(unlink) (to_gdb) == -1)
545 warning ("could not unlink %s\n", to_gdb);
546 if (pid == pid_from_to_creator && shared_mem && VG_(unlink) (shared_mem) == -1)
547 warning ("could not unlink %s\n", shared_mem);
548 } else {
549 VG_(debugLog)(1, "remote close",
550 "cannot unlink gdb pipes\n");
552 free (from_gdb);
553 from_gdb = NULL;
554 free (to_gdb);
555 to_gdb = NULL;
556 free (shared_mem);
557 shared_mem = NULL;
560 Bool remote_connected(void)
562 return write_remote_desc != INVALID_DESCRIPTOR;
565 /* cleanup after an error detected by poll_cond */
566 static
567 void error_poll_cond(void)
569 /* if we will close the connection, we assume either that
570 all characters have been seen or that they will be dropped. */
571 shared->seen_by_valgrind = shared->written_by_vgdb;
572 remote_finish(reset_after_error);
575 /* remote_desc_activity might be used at high frequency if the user
576 gives a small value to --vgdb-poll. So, the function avoids
577 doing repetitively system calls by rather looking at the
578 counter values maintained in shared memory by vgdb. */
579 int remote_desc_activity(const char *msg)
581 int retval;
582 SysRes ret;
583 const int looking_at = shared->written_by_vgdb;
584 if (shared->seen_by_valgrind == looking_at)
585 return 0;
586 if (remote_desc == INVALID_DESCRIPTOR)
587 return 0;
589 /* poll the remote desc */
590 remote_desc_pollfdread_activity.revents = 0;
591 ret = VG_(poll_no_eintr) (&remote_desc_pollfdread_activity, 1, 0);
592 if (sr_isError(ret)
593 || (sr_Res(ret) && poll_cond(remote_desc_pollfdread_activity.revents))) {
594 if (sr_isError(ret)) {
595 sr_extended_perror(ret, "remote_desc_activity: poll error\n");
596 } else {
597 dlog(0, "POLLcond %d remote_desc_pollfdread %d\n",
598 remote_desc_pollfdread_activity.revents, remote_desc);
599 error_poll_cond();
601 retval = 2;
602 } else {
603 retval = sr_Res(ret);
605 dlog(1,
606 "remote_desc_activity %s %d last_looked_cntr %d looking_at %d"
607 " shared->written_by_vgdb %d shared->seen_by_valgrind %d"
608 " retval %d\n",
609 msg, remote_desc, last_looked_cntr, looking_at,
610 shared->written_by_vgdb, shared->seen_by_valgrind,
611 retval);
612 /* if no error from poll, indicate we have "seen" up to looking_at */
613 if (retval == 1)
614 last_looked_cntr = looking_at;
615 return retval;
618 /* Convert hex digit A to a number. */
620 static
621 int fromhex (int a)
623 if (a >= '0' && a <= '9')
624 return a - '0';
625 else if (a >= 'a' && a <= 'f')
626 return a - 'a' + 10;
627 else
628 error ("Reply contains invalid hex digit 0x%x\n", (unsigned)a);
629 return 0;
632 int unhexify (char *bin, const char *hex, int count)
634 int i;
636 for (i = 0; i < count; i++) {
637 if (hex[0] == 0 || hex[1] == 0) {
638 /* Hex string is short, or of uneven length.
639 Return the count that has been converted so far. */
640 return i;
642 *bin++ = fromhex (hex[0]) * 16 + fromhex (hex[1]);
643 hex += 2;
645 return i;
648 void decode_address (CORE_ADDR *addrp, const char *start, int len)
650 CORE_ADDR addr;
651 char ch;
652 int i;
654 addr = 0;
655 for (i = 0; i < len; i++) {
656 ch = start[i];
657 addr = addr << 4;
658 addr = addr | (fromhex (ch) & 0x0f);
660 *addrp = addr;
663 /* builds an image of bin according to byte order of the architecture
664 Useful for register and int image */
665 char* heximage (char *buf, const char *bin, int count)
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;
680 void* C2v(CORE_ADDR addr)
682 return (void*) addr;
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. */
694 remote_escape_output (const gdb_byte *buffer, int len,
695 gdb_byte *out_buf, int *out_len,
696 int out_maxlen)
698 int input_index, output_index;
700 output_index = 0;
701 for (input_index = 0; input_index < len; input_index++) {
702 gdb_byte b = buffer[input_index];
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;
717 *out_len = input_index;
718 return output_index;
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.
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. */
730 static
731 int remote_unescape_input (const gdb_byte *buffer, int len,
732 gdb_byte *out_buf, int out_maxlen)
734 int input_index, output_index;
735 int escaped;
737 output_index = 0;
738 escaped = 0;
739 for (input_index = 0; input_index < len; input_index++) {
740 gdb_byte b = buffer[input_index];
742 if (output_index + 1 > out_maxlen)
743 error ("Received too much data (len %d) from the target.\n", len);
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;
755 if (escaped)
756 error ("Unmatched escape character in target response.\n");
758 return output_index;
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. */
765 static
766 int try_rle (char *buf, int remaining, unsigned char *csum, char **p)
768 int n;
770 /* Always output the character. */
771 *csum += buf[0];
772 *(*p)++ = buf[0];
774 /* Don't go past '~'. */
775 if (remaining > 97)
776 remaining = 97;
778 for (n = 1; n < remaining; n++)
779 if (buf[n] != buf[0])
780 break;
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--;
787 if (n < 3)
788 return 1;
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--;
797 *csum += '*';
798 *(*p)++ = '*';
799 *csum += n + 29;
800 *(*p)++ = n + 29;
802 return n + 1;
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. */
809 int putpkt_binary (char *buf, int cnt)
811 int i;
812 unsigned char csum = 0;
813 char *buf2;
814 char *p;
815 int cc;
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.
822 /* Copy the packet into buffer BUF2, encapsulating it
823 and giving it a checksum. */
825 p = buf2;
826 *p++ = '$';
828 for (i = 0; i < cnt;)
829 i += try_rle (buf + i, cnt - i, &csum, &p);
831 *p++ = '#';
832 *p++ = tohex ((csum >> 4) & 0xf);
833 *p++ = tohex (csum & 0xf);
835 *p = '\0';
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;
844 /* Send it once (noack_mode)
845 or send it over and over until we get a positive ack. */
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;
854 if (VG_(debugLog_getLevel)() >= 3) {
855 char *tracebuf = malloc(4 * (p - buf2) + 1); // worst case
856 char *tr = tracebuf;
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;
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);
876 if (noack_mode)
877 break;
879 cc = readchar (1);
880 if (cc > 0)
881 dlog(3, "[received '%c' (0x%x)]\n", cc, (unsigned)cc);
883 if (cc <= 0) {
884 if (cc == 0)
885 dlog(1, "putpkt(read): Got EOF\n");
886 else
887 warning ("putpkt(read) error\n");
889 free (buf2);
890 return -1;
893 /* Check for an input interrupt while we're here. */
894 if (cc == '\003')
895 dlog(1, "Received 0x03 character (SIGINT)\n");
897 while (cc != '+');
899 free (buf2);
900 return 1; /* Success! */
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. */
907 int putpkt (char *buf)
909 return putpkt_binary (buf, strlen (buf));
912 void monitor_output (char *s)
914 if (remote_connected()) {
915 const int len = strlen(s);
916 char *buf = malloc(1 + 2*len + 1);
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);
927 free (buf);
928 } else {
929 print_to_initial_valgrind_sink (s);
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
939 int readchar (int single)
941 static unsigned char buf[PBUFSIZ];
942 static int bufcnt = 0;
943 static unsigned char *bufp;
944 SysRes ret;
946 if (bufcnt-- > 0)
947 return *bufp++;
949 if (remote_desc == INVALID_DESCRIPTOR)
950 return -1;
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));
962 return -1;
964 if (single)
965 bufcnt = VG_(read) (remote_desc, buf, 1);
966 else
967 bufcnt = VG_(read) (remote_desc, buf, sizeof (buf));
969 if (bufcnt <= 0) {
970 if (bufcnt == 0)
971 dlog (1, "readchar: Got EOF\n");
972 else
973 warning ("readchar read error\n");
975 return -1;
978 shared->seen_by_valgrind += bufcnt;
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");
988 bufp = buf;
989 bufcnt--;
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();
997 return *bufp++;
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. */
1004 int getpkt (char *buf)
1006 char *bp;
1007 unsigned char csum, c1, c2;
1008 int c;
1010 while (1) {
1011 csum = 0;
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;
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;
1032 *bp = 0;
1034 c1 = fromhex (readchar (0));
1035 c2 = fromhex (readchar (0));
1037 if (csum == (c1 << 4) + c2)
1038 break;
1040 dlog (0, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1041 (unsigned)(c1 << 4) + c2, (unsigned)csum, buf);
1042 if (!ensure_write_remote_desc()) {
1043 dlog(1, "getpkt(write nack) no write_remote_desc");
1045 VG_(write) (write_remote_desc, "-", 1);
1048 if (noack_mode)
1049 dlog(3, "getpkt (\"%s\"); [no ack] \n", buf);
1050 else
1051 dlog(3, "getpkt (\"%s\"); [sending ack] \n", buf);
1053 if (!noack_mode) {
1054 if (!ensure_write_remote_desc()) {
1055 dlog(1, "getpkt(write ack) no write_remote_desc");
1057 VG_(write) (write_remote_desc, "+", 1);
1058 dlog(3, "[sent ack]\n");
1061 return bp - buf;
1064 void write_ok (char *buf)
1066 buf[0] = 'O';
1067 buf[1] = 'K';
1068 buf[2] = '\0';
1071 void write_enn (char *buf)
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';
1080 void convert_int_to_ascii (const unsigned char *from, char *to, int n)
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);
1091 *to++ = 0;
1095 void convert_ascii_to_int (const char *from, unsigned char *to, int n)
1097 int nib1, nib2;
1098 while (n--) {
1099 nib1 = fromhex (*from++);
1100 nib2 = fromhex (*from++);
1101 *to++ = (((nib1 & 0x0f) << 4) & 0xf0) | (nib2 & 0x0f);
1105 static
1106 char * outreg (int regno, char *buf)
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++ = ';';
1119 return buf;
1122 void prepare_resume_reply (char *buf, char status, unsigned char sig)
1124 int nib;
1126 *buf++ = status;
1128 nib = ((sig & 0xf0) >> 4);
1129 *buf++ = tohex (nib);
1130 nib = sig & 0x0f;
1131 *buf++ = tohex (nib);
1133 if (status == 'T') {
1134 const char **regp = gdbserver_expedite_regs;
1136 if (valgrind_stopped_by_watchpoint()) {
1137 CORE_ADDR addr;
1138 int i;
1140 strncpy (buf, "watch:", 6);
1141 buf += 6;
1143 addr = valgrind_stopped_data_address ();
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);
1151 *buf++ = ';';
1154 if (valgrind_stopped_by_syscall () >= 0) {
1155 VG_(sprintf) (buf, "%s:%x;",
1156 valgrind_stopped_before_syscall ()
1157 ? "syscall_entry" : "syscall_return",
1158 (UInt)valgrind_stopped_by_syscall ());
1159 buf += strlen (buf);
1162 while (*regp) {
1163 buf = outreg (find_regno (*regp), buf);
1164 regp ++;
1168 unsigned int gdb_id_from_wait;
1170 /* FIXME right place to set this? */
1171 thread_from_wait =
1172 ((struct inferior_list_entry *)current_inferior)->id;
1173 gdb_id_from_wait = thread_to_gdb_id (current_inferior);
1175 dlog(1, "Writing resume reply for %lu\n", thread_from_wait);
1176 /* This if (1) ought to be unnecessary. But remote_wait in GDB
1177 will claim this event belongs to inferior_ptid if we do not
1178 specify a thread, and there's no way for gdbserver to know
1179 what inferior_ptid is. */
1180 if (1 || old_thread_from_wait != thread_from_wait) {
1181 general_thread = thread_from_wait;
1182 VG_(sprintf) (buf, "thread:%x;", gdb_id_from_wait);
1183 buf += strlen (buf);
1184 old_thread_from_wait = thread_from_wait;
1188 /* For W and X, we're done. */
1189 *buf++ = 0;
1192 void decode_m_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr)
1194 int i = 0, j = 0;
1195 char ch;
1196 *mem_addr_ptr = *len_ptr = 0;
1198 while ((ch = from[i++]) != ',') {
1199 *mem_addr_ptr = *mem_addr_ptr << 4;
1200 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1203 for (j = 0; j < 4; j++) {
1204 if ((ch = from[i++]) == 0)
1205 break;
1206 *len_ptr = *len_ptr << 4;
1207 *len_ptr |= fromhex (ch) & 0x0f;
1211 void decode_M_packet (char *from, CORE_ADDR *mem_addr_ptr, unsigned int *len_ptr,
1212 unsigned char *to)
1214 int i = 0;
1215 char ch;
1216 *mem_addr_ptr = *len_ptr = 0;
1218 while ((ch = from[i++]) != ',') {
1219 *mem_addr_ptr = *mem_addr_ptr << 4;
1220 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1223 while ((ch = from[i++]) != ':') {
1224 *len_ptr = *len_ptr << 4;
1225 *len_ptr |= fromhex (ch) & 0x0f;
1228 convert_ascii_to_int (&from[i++], to, *len_ptr);
1231 int decode_X_packet (char *from, int packet_len, CORE_ADDR *mem_addr_ptr,
1232 unsigned int *len_ptr, unsigned char *to)
1234 int i = 0;
1235 char ch;
1236 *mem_addr_ptr = *len_ptr = 0;
1238 while ((ch = from[i++]) != ',') {
1239 *mem_addr_ptr = *mem_addr_ptr << 4;
1240 *mem_addr_ptr |= fromhex (ch) & 0x0f;
1243 while ((ch = from[i++]) != ':') {
1244 *len_ptr = *len_ptr << 4;
1245 *len_ptr |= fromhex (ch) & 0x0f;
1248 if (remote_unescape_input ((const gdb_byte *) &from[i], packet_len - i,
1249 to, *len_ptr) != *len_ptr)
1250 return -1;
1252 return 0;
1256 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
1257 to communicate with valgrind */
1258 HChar *
1259 VG_(vgdb_prefix_default)(void)
1261 static HChar *prefix;
1263 if (prefix == NULL) {
1264 const HChar *tmpdir = VG_(tmpdir)();
1265 prefix = malloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
1266 strcpy(prefix, tmpdir);
1267 strcat(prefix, "/vgdb-pipe");
1269 return prefix;