1 /*--------------------------------------------------------------------*/
2 /*--- Relay between gdb and gdbserver embedded in valgrind vgdb.c ---*/
3 /*--------------------------------------------------------------------*/
6 This file is part of Valgrind, a dynamic binary instrumentation
9 Copyright (C) 2011 Philippe Waroquiers
11 This program is free software; you can redistribute it and/or
12 modify it under the terms of the GNU General Public License as
13 published by the Free Software Foundation; either version 2 of the
14 License, or (at your option) any later version.
16 This program is distributed in the hope that it will be useful, but
17 WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26 The GNU General Public License is contained in the file COPYING.
28 #include "pub_core_basics.h"
29 #include "pub_core_vki.h"
30 #include "pub_core_libcsetjmp.h"
31 #include "pub_core_threadstate.h"
32 #include "pub_core_gdbserver.h"
47 #include <sys/ptrace.h>
52 # if defined(VGO_linux)
53 #include <sys/prctl.h>
54 #include <linux/ptrace.h>
57 /* vgdb has two usages:
58 1. relay application between gdb and the gdbserver embedded in valgrind.
59 2. standalone to send monitor commands to a running valgrind-ified process
61 It is made of a main program which reads arguments. If no
62 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
65 As relay application, vgdb reads bytes from gdb on stdin and
66 writes these bytes to valgrind. Bytes read from valgrind are
67 written to gdb on stdout. Read/Write from/to valgrind is done
68 using FIFOs. There is one thread reading from stdin, writing to
69 valgrind on a FIFO. There is one thread reading from valgrind on a
70 FIFO, writing to gdb on stdout
72 As a standalone utility, vgdb builds command packets to write to valgrind,
73 sends it and reads the reply. The same two threads are used to write/read.
74 Once all the commands are sent and their replies received, vgdb will exit.
78 /* define PTRACEINVOKER to compile the ptrace related code
79 which ensures a valgrind process blocked in a system call
80 can be "waken up". PTRACEINVOKER implies some architecture
81 specific code and/or some OS specific code. */
82 #if defined(VGA_arm) || defined(VGA_x86) || defined(VGA_amd64) \
83 || defined(VGA_ppc32) || defined(VGA_ppc64) || defined(VGA_s390x)
86 I_die_here : (PTRACEINVOKER) architecture missing in vgdb.c
89 /* Some darwin specific stuff is needed as ptrace is not
90 fully supported on MacOS. Till we find someone courageous
91 having access to Darwin, there is no PTRACEINVOKER. */
92 #if defined(VGO_darwin)
96 static int debuglevel;
97 static struct timeval dbgtv;
98 /* if level <= debuglevel, print timestamp, then print provided by debug info */
99 #define DEBUG(level, ...) (level <= debuglevel ? \
100 gettimeofday(&dbgtv, NULL), \
101 fprintf(stderr, "%ld.%6.6ld ", \
102 (long int)dbgtv.tv_sec, \
103 (long int)dbgtv.tv_usec), \
104 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
107 /* same as DEBUG but does not print time stamp info */
108 #define PDEBUG(level, ...) (level <= debuglevel ? \
109 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
113 report the errno and fprintf the ... varargs on stderr. */
114 #define ERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
115 fprintf(stderr, __VA_ARGS__), \
117 /* same as ERROR, but also exits with status 1 */
118 #define XERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
119 fprintf(stderr, __VA_ARGS__), \
123 static char *vgdb_prefix = "/tmp/vgdb-pipe";
125 /* Will be set to True when any condition indicating we have to shutdown
127 static Bool shutting_down = False;
129 static VgdbShared32 *shared32;
130 static VgdbShared64 *shared64;
131 #define VS_written_by_vgdb (shared32 != NULL ? \
132 shared32->written_by_vgdb \
133 : shared64->written_by_vgdb)
134 #define VS_seen_by_valgrind (shared32 != NULL ? \
135 shared32->seen_by_valgrind \
136 : shared64->seen_by_valgrind)
138 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
140 /* Calls malloc (size). Exits if memory can't be allocated. */
142 void *vmalloc(size_t size)
144 void * mem = malloc(size);
146 XERROR (errno, "can't allocate memory\n");
150 /* Calls realloc (size). Exits if memory can't be allocated. */
152 void *vrealloc(void *ptr,size_t size)
154 void * mem = realloc(ptr, size);
156 XERROR (errno, "can't reallocate memory\n");
160 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
162 void add_written(int nrw)
164 if (shared32 != NULL)
165 shared32->written_by_vgdb += nrw;
166 else if (shared64 != NULL)
167 shared64->written_by_vgdb += nrw;
172 static int shared_mem_fd = -1;
174 void map_vgdbshared (char* shared_mem)
178 shared_mem_fd = open(shared_mem, O_RDWR);
179 /* shared_mem_fd will not be closed till vgdb exits. */
181 if (shared_mem_fd == -1)
182 XERROR (errno, "error opening %s shared memory file\n", shared_mem);
184 if (fstat(shared_mem_fd, &fdstat) != 0)
185 XERROR (errno, "fstat");
187 if (fdstat.st_size == sizeof(VgdbShared64))
188 s = (void*) &shared64;
189 else if (fdstat.st_size == sizeof(VgdbShared32))
190 s = (void*) &shared32;
192 #if VEX_HOST_WORDSIZE == 8
194 "error size shared memory file %s.\n"
195 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
197 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
198 (long int)fdstat.st_size);
199 #elif VEX_HOST_WORDSIZE == 4
201 "error size shared memory file %s.\n"
202 "expecting size %d (32bits) got %ld.\n",
204 (int) sizeof(VgdbShared32),
207 # error "unexpected wordsize"
210 #if VEX_HOST_WORDSIZE == 4
211 if (shared64 != NULL)
212 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
213 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
216 *s = (void*) mmap (NULL, fdstat.st_size,
217 PROT_READ|PROT_WRITE, MAP_SHARED,
220 if (*s == (void *) -1)
221 XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
225 #if VEX_HOST_WORDSIZE == 8
226 typedef Addr64 CORE_ADDR;
227 typedef Addr64 PTRACE_XFER_TYPE;
228 typedef void* PTRACE_ARG3_TYPE;
229 #elif VEX_HOST_WORDSIZE == 4
230 typedef Addr32 CORE_ADDR;
231 typedef Addr32 PTRACE_XFER_TYPE;
232 typedef void* PTRACE_ARG3_TYPE;
234 # error "unexpected wordsize"
237 static Bool pid_of_save_regs_continued = False;
238 // True if we have continued pid_of_save_regs after PTRACE_ATTACH
240 static Bool dying = False;
241 // Set to True when loss of connection indicating that the Valgrind
244 /* To be called when connection with valgrind is lost. In case we
245 have lost the connection, it means that Valgrind has closed the
246 connection and is busy exiting. We can't and don't have to stop it in
249 void valgrind_dying(void)
251 pid_of_save_regs_continued = False;
257 /* ptrace_(read|write)_memory are modified extracts of linux-low.c
258 from gdb 6.6. Copyrighted FSF */
259 /* Copy LEN bytes from inferior's memory starting at MEMADDR
260 to debugger memory starting at MYADDR. */
263 int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
264 unsigned char *myaddr, int len)
267 /* Round starting address down to longword boundary. */
268 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
269 /* Round ending address up; get number of longwords that makes. */
271 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
272 / sizeof (PTRACE_XFER_TYPE);
273 /* Allocate buffer of that many longwords. */
274 register PTRACE_XFER_TYPE *buffer
275 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
277 /* Read all the longwords */
278 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
280 buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
281 (PTRACE_ARG3_TYPE) addr, 0);
286 /* Copy appropriate bytes out of the buffer. */
288 (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
293 /* Copy LEN bytes of data from debugger memory at MYADDR
294 to inferior's memory at MEMADDR.
295 On failure (cannot write the inferior)
296 returns the value of errno. */
299 int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr,
300 const unsigned char *myaddr, int len)
303 /* Round starting address down to longword boundary. */
304 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
305 /* Round ending address up; get number of longwords that makes. */
307 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
308 / sizeof (PTRACE_XFER_TYPE);
309 /* Allocate buffer of that many longwords. */
310 register PTRACE_XFER_TYPE *buffer
311 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
313 if (debuglevel >= 1) {
314 DEBUG (1, "Writing ");
315 for (i = 0; i < len; i++)
316 PDEBUG (1, "%02x", (unsigned)myaddr[i]);
317 PDEBUG(1, " to %p\n", (void *) memaddr);
320 /* Fill start and end extra bytes of buffer with existing memory data. */
322 buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
323 (PTRACE_ARG3_TYPE) addr, 0);
327 = ptrace (PTRACE_PEEKTEXT, inferior_pid,
328 (PTRACE_ARG3_TYPE) (addr + (count - 1)
329 * sizeof (PTRACE_XFER_TYPE)),
333 /* Copy data to be written over corresponding part of buffer */
335 memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
338 /* Write the entire buffer. */
340 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
342 ptrace (PTRACE_POKETEXT, inferior_pid,
343 (PTRACE_ARG3_TYPE) addr, buffer[i]);
351 /* subset of VG_(threads) needed for vgdb ptrace.
352 This is initialized when process is attached. */
358 static VgdbThreadState vgdb_threads[VG_N_THREADS];
361 HChar* name_of_ThreadStatus ( ThreadStatus status )
364 case VgTs_Empty: return "VgTs_Empty";
365 case VgTs_Init: return "VgTs_Init";
366 case VgTs_Runnable: return "VgTs_Runnable";
367 case VgTs_WaitSys: return "VgTs_WaitSys";
368 case VgTs_Yielding: return "VgTs_Yielding";
369 case VgTs_Zombie: return "VgTs_Zombie";
370 default: return "VgTs_???";
375 char *status_image (int status)
377 static char result[256];
379 #define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
383 if (WIFEXITED(status))
384 APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
386 if (WIFSIGNALED(status)) {
387 APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
388 if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
391 if (WIFSTOPPED(status))
392 APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
394 if (WIFCONTINUED(status))
395 APPEND ("WIFCONTINUED ");
401 /* Wait till the process pid is reported as stopped with signal_expected.
402 If other signal(s) than signal_expected are received, waitstopped
403 will pass them to pid, waiting for signal_expected to stop pid.
404 Returns True when process is in stopped state with signal_expected.
405 Returns False if a problem was encountered while waiting for pid
408 If pid is reported as being dead/exited, waitstopped will return False.
411 Bool waitstopped (int pid, int signal_expected, char *msg)
419 DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
420 msg, signal_expected);
421 p = waitpid(pid, &status, __WALL);
422 DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p,
423 status, status_image (status));
425 ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n",
426 msg, pid, p, status, status_image (status));
430 if (WIFEXITED(status)) {
431 shutting_down = True;
435 assert (WIFSTOPPED(status));
436 signal_received = WSTOPSIG(status);
437 if (signal_received == signal_expected)
440 /* pid received a signal which is not the signal we are waiting for.
441 We continue pid, transmitting this signal. */
442 DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
443 res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
445 ERROR(errno, "waitstopped PTRACE_CONT\n");
453 /* Stops the given pid, wait for the process to be stopped.
454 Returns True if succesful, False otherwise.
455 msg is used in tracing and error reporting. */
457 Bool stop (int pid, char *msg)
461 DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
462 res = kill (pid, SIGSTOP);
464 ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
468 return waitstopped (pid, SIGSTOP, msg);
472 /* Attaches to given pid, wait for the process to be stopped.
473 Returns True if succesful, False otherwise.
474 msg is used in tracing and error reporting. */
476 Bool attach (int pid, char *msg)
480 DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
481 res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
483 ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
487 return waitstopped(pid, SIGSTOP, msg);
490 /* once we are attached to the pid, get the list of threads and stop
492 Returns True if all threads properly suspended, False otherwise. */
494 Bool acquire_and_suspend_threads(int pid)
498 Bool pid_found = False;
503 int nr_live_threads = 0;
505 if (shared32 != NULL) {
506 vgt = shared32->threads;
507 sz_tst = shared32->sizeof_ThreadState;
508 off_status = shared32->offset_status;
509 off_lwpid = shared32->offset_lwpid;
511 else if (shared64 != NULL) {
512 vgt = shared64->threads;
513 sz_tst = shared64->sizeof_ThreadState;
514 off_status = shared64->offset_status;
515 off_lwpid = shared64->offset_lwpid;
520 /* note: the entry 0 is unused */
521 for (i = 1; i < VG_N_THREADS; i++) {
523 rw = ptrace_read_memory(pid, vgt+off_status,
524 (unsigned char *)&(vgdb_threads[i].status),
525 sizeof(ThreadStatus));
527 ERROR(rw, "status ptrace_read_memory\n");
531 rw = ptrace_read_memory(pid, vgt+off_lwpid,
532 (unsigned char *)&(vgdb_threads[i].lwpid),
535 ERROR(rw, "lwpid ptrace_read_memory\n");
539 if (vgdb_threads[i].status != VgTs_Empty) {
540 DEBUG(1, "found tid %d status %s lwpid %d\n",
541 i, name_of_ThreadStatus(vgdb_threads[i].status),
542 vgdb_threads[i].lwpid);
544 if (vgdb_threads[i].lwpid <= 1) {
545 if (vgdb_threads[i].lwpid == 0
546 && vgdb_threads[i].status == VgTs_Init) {
547 DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
548 i, name_of_ThreadStatus(vgdb_threads[i].status),
549 vgdb_threads[i].lwpid);
551 ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
552 i, name_of_ThreadStatus(vgdb_threads[i].status),
553 vgdb_threads[i].lwpid);
555 /* in case we have a VtTs_Init thread with lwpid not yet set,
556 we try again later. */
559 if (vgdb_threads[i].lwpid == pid) {
564 if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
565 ERROR(0, "ERROR attach pid %d tid %d\n",
566 vgdb_threads[i].lwpid, i);
572 /* If we found no thread, it means the process is stopping, and
573 we better do not force anything to happen during that. */
574 if (nr_live_threads > 0)
581 void detach_from_all_threads(int pid)
585 Bool pid_found = False;
587 /* detach from all the threads */
588 for (i = 1; i < VG_N_THREADS; i++) {
589 if (vgdb_threads[i].status != VgTs_Empty) {
590 if (vgdb_threads[i].status == VgTs_Init
591 && vgdb_threads[i].lwpid == 0) {
592 DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
593 vgdb_threads[i].lwpid, i,
594 name_of_ThreadStatus (vgdb_threads[i].status));
596 if (vgdb_threads[i].lwpid == pid) {
600 DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
601 vgdb_threads[i].lwpid, i,
602 name_of_ThreadStatus (vgdb_threads[i].status));
603 res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
605 ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n",
606 vgdb_threads[i].lwpid, i,
607 name_of_ThreadStatus (vgdb_threads[i].status),
614 if (!pid_found && pid) {
615 /* No threads are live. Process is busy stopping.
616 We need to detach from pid explicitely. */
617 DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
618 res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
620 ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
624 // if > 0, pid for which registers have to be restored.
625 static int pid_of_save_regs = 0;
626 static struct user user_save;
628 // The below indicates if ptrace_getregs (and ptrace_setregs) can be used.
629 // Note that some linux versions are defining PTRACE_GETREGS but using
630 // it gives back EIO.
631 // has_working_ptrace_getregs can take the following values:
632 // -1 : PTRACE_GETREGS is defined
633 // runtime check not yet done.
634 // 0 : PTRACE_GETREGS runtime check has failed.
635 // 1 : PTRACE_GETREGS defined and runtime check ok.
636 #ifdef PTRACE_GETREGS
637 static int has_working_ptrace_getregs = -1;
640 /* Get the registers from pid into regs.
641 regs_bsz value gives the length of *regs.
642 Returns True if all ok, otherwise False. */
644 Bool getregs (int pid, void *regs, long regs_bsz)
646 DEBUG(1, "getregs regs_bsz %ld\n", regs_bsz);
647 # ifdef PTRACE_GETREGS
648 if (has_working_ptrace_getregs) {
649 // Platforms having GETREGS
651 DEBUG(1, "getregs PTRACE_GETREGS\n");
652 res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
654 if (has_working_ptrace_getregs == -1) {
655 // First call to PTRACE_GETREGS succesful =>
656 has_working_ptrace_getregs = 1;
657 DEBUG(1, "detected a working PTRACE_GETREGS\n");
659 assert (has_working_ptrace_getregs == 1);
662 else if (has_working_ptrace_getregs == 1) {
663 // We had a working call, but now it fails.
664 // This is unexpected.
665 ERROR(errno, "PTRACE_GETREGS %ld\n", res);
668 // Check this is the first call:
669 assert (has_working_ptrace_getregs == -1);
671 DEBUG(1, "detected a broken PTRACE_GETREGS with EIO\n");
672 has_working_ptrace_getregs = 0;
673 // Fall over to the PTRACE_PEEKUSER case.
675 ERROR(errno, "broken PTRACE_GETREGS unexpected errno %ld\n", res);
682 // We assume PTRACE_PEEKUSER is defined everywhere.
685 long peek_bsz = PT_ENDREGS;
686 assert (peek_bsz <= regs_bsz);
688 long peek_bsz = regs_bsz-1;
690 char *pregs = (char *) regs;
693 DEBUG(1, "getregs PTRACE_PEEKUSER(s) peek_bsz %ld\n", peek_bsz);
694 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
695 *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
697 ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
704 // If neither PTRACE_GETREGS not PTRACE_PEEKUSER have returned,
705 // then we are in serious trouble.
709 /* Set the registers of pid to regs.
710 regs_bsz value gives the length of *regs.
711 Returns True if all ok, otherwise False. */
713 Bool setregs (int pid, void *regs, long regs_bsz)
715 DEBUG(1, "setregs regs_bsz %ld\n", regs_bsz);
716 // Note : the below is checking for GETREGS, not SETREGS
717 // as if one is defined and working, the other one should also work.
718 # ifdef PTRACE_GETREGS
719 if (has_working_ptrace_getregs) {
720 // Platforms having SETREGS
722 // setregs can never be called before getregs has done a runtime check.
723 assert (has_working_ptrace_getregs == 1);
724 DEBUG(1, "setregs PTRACE_SETREGS\n");
725 res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
727 ERROR(errno, "PTRACE_SETREGS %ld\n", res);
735 char *pregs = (char *) regs;
739 long peek_bsz = PT_ENDREGS;
740 assert (peek_bsz <= regs_bsz);
742 long peek_bsz = regs_bsz-1;
745 DEBUG(1, "setregs PTRACE_POKEUSER(s) %ld\n", peek_bsz);
746 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
747 res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
749 ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
756 // If neither PTRACE_SETREGS not PTRACE_POKEUSER have returned,
757 // then we are in serious trouble.
761 /* Restore the registers to the saved value, then detaches from all threads */
763 void restore_and_detach(int pid)
765 if (pid_of_save_regs) {
766 /* In case the 'main pid' has been continued, we need to stop it
767 before resetting the registers. */
768 if (pid_of_save_regs_continued) {
769 pid_of_save_regs_continued = False;
770 if (!stop(pid_of_save_regs, "sigstop before reset regs"))
771 DEBUG(0, "Could not sigstop before reset");
774 DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
775 if (!setregs(pid_of_save_regs, &user_save.regs, sizeof(user_save.regs))) {
776 ERROR(errno, "setregs restore registers pid %d after cont\n",
779 pid_of_save_regs = 0;
781 DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
783 detach_from_all_threads(pid);
786 /* Ensures that the gdbserver code is invoked by pid.
787 If an error occurs, resets to the valgrind process
788 to the state it has before being ptrace-d.
789 Returns True if invoke successful, False otherwise.
792 Bool invoke_gdbserver (int pid)
796 struct user user_mod;
798 /* A specific int value is passed to invoke_gdbserver, to check
799 everything goes according to the plan. */
800 const int check = 0x8BADF00D; // ate bad food.
802 const Addr bad_return = 0;
803 // A bad return address will be pushed on the stack.
804 // The function invoke_gdbserver cannot return. If ever it returns, a NULL
805 // address pushed on the stack should ensure this is detected.
807 /* Not yet attached. If problem, vgdb can abort,
810 On Ubuntu>= 10.10, a /proc setting can disable ptrace.
811 So, Valgrind has to SET_PTRACER this vgdb. Once this
812 is done, this vgdb can ptrace the valgrind process. */
814 DEBUG(1, "attach to 'main' pid %d\n", pid);
815 if (!attach(pid, "attach main pid")) {
816 ERROR(0, "error attach main pid %d\n", pid);
820 /* Now, we are attached. If problem, detach and return. */
822 if (!acquire_and_suspend_threads(pid)) {
823 detach_from_all_threads(pid);
824 /* if the pid does not exist anymore, we better stop */
825 if (kill(pid, 0) != 0)
826 XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
831 if (!getregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
832 detach_from_all_threads(pid);
835 user_save = user_mod;
838 sp = user_mod.regs.esp;
839 #elif defined(VGA_amd64)
840 sp = user_mod.regs.rsp;
841 if (shared32 != NULL) {
842 /* 64bit vgdb speaking with a 32bit executable.
843 To have system call restart properly, we need to sign extend rax.
845 web search '[patch] Fix syscall restarts for amd64->i386 biarch'
846 e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
847 *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
848 DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
849 user_mod.regs.rax, user_save.regs.rax);
851 #elif defined(VGA_arm)
852 sp = user_mod.regs.uregs[13];
853 #elif defined(VGA_ppc32)
854 sp = user_mod.regs.gpr[1];
855 #elif defined(VGA_ppc64)
856 sp = user_mod.regs.gpr[1];
857 #elif defined(VGA_s390x)
858 sp = user_mod.regs.gprs[15];
860 I_die_here : (sp) architecture missing in vgdb.c
864 // the magic below is derived from spying what gdb sends to
865 // the (classical) gdbserver when invoking a C function.
866 if (shared32 != NULL) {
867 // vgdb speaking with a 32bit executable.
868 #if defined(VGA_x86) || defined(VGA_amd64)
869 const int regsize = 4;
871 /* push check arg on the stack */
873 DEBUG(1, "push check arg ptrace_write_memory\n");
874 assert(regsize == sizeof(check));
875 rw = ptrace_write_memory(pid, sp,
876 (unsigned char *) &check,
879 ERROR(rw, "push check arg ptrace_write_memory");
880 detach_from_all_threads(pid);
885 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
886 // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
888 rw = ptrace_write_memory(pid, sp,
889 (unsigned char *) &bad_return,
892 ERROR(rw, "push bad_return return address ptrace_write_memory");
893 detach_from_all_threads(pid);
897 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
898 // compiled in 32bits, speaking with a 32bits exe
899 user_mod.regs.ebp = sp; // bp set to sp
900 user_mod.regs.esp = sp;
901 user_mod.regs.eip = shared32->invoke_gdbserver;
902 user_mod.regs.orig_eax = -1L;
903 #elif defined(VGA_amd64)
904 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
905 // compiled in 64bits, speaking with a 32bits exe
906 user_mod.regs.rbp = sp; // bp set to sp
907 user_mod.regs.rsp = sp;
908 user_mod.regs.rip = shared32->invoke_gdbserver;
909 user_mod.regs.orig_rax = -1L;
911 I_die_here : not x86 or amd64 in x86/amd64 section/
914 #elif defined(VGA_ppc32) || defined(VGA_ppc64)
915 user_mod.regs.nip = shared32->invoke_gdbserver;
916 user_mod.regs.trap = -1L;
917 /* put check arg in register 3 */
918 user_mod.regs.gpr[3] = check;
919 /* put NULL return address in Link Register */
920 user_mod.regs.link = bad_return;
922 #elif defined(VGA_arm)
923 /* put check arg in register 0 */
924 user_mod.regs.uregs[0] = check;
925 /* put NULL return address in Link Register */
926 user_mod.regs.uregs[14] = bad_return;
927 user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
929 #elif defined(VGA_s390x)
930 XERROR(0, "(fn32) s390x has no 32bits implementation");
932 I_die_here : architecture missing in vgdb.c
936 else if (shared64 != NULL) {
938 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
939 #elif defined(VGA_amd64)
940 // vgdb speaking with a 64 bit executable.
941 const int regsize = 8;
944 /* give check arg in rdi */
945 user_mod.regs.rdi = check;
947 /* push return address on stack : return to breakaddr */
949 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
950 rw = ptrace_write_memory(pid, sp,
951 (unsigned char *) &bad_return,
954 ERROR(rw, "push bad_return return address ptrace_write_memory");
955 detach_from_all_threads(pid);
959 /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
960 user_mod.regs.rbp = sp; // bp set to sp
961 user_mod.regs.rsp = sp;
962 user_mod.regs.rip = shared64->invoke_gdbserver;
963 user_mod.regs.orig_rax = -1L;
965 #elif defined(VGA_arm)
966 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
967 #elif defined(VGA_ppc32)
968 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
969 #elif defined(VGA_ppc64)
973 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
974 (unsigned char *)&func_addr,
977 ERROR(rw, "ppc64 read func_addr\n");
978 detach_from_all_threads(pid);
981 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
982 (unsigned char *)&toc_addr,
985 ERROR(rw, "ppc64 read toc_addr\n");
986 detach_from_all_threads(pid);
989 // We are not pushing anything on the stack, so it is not
990 // very clear why the sp has to be decreased, but it seems
991 // needed. The ppc64 ABI might give some lights on this ?
992 user_mod.regs.gpr[1] = sp - 220;
993 user_mod.regs.gpr[2] = toc_addr;
994 user_mod.regs.nip = func_addr;
995 user_mod.regs.trap = -1L;
996 /* put check arg in register 3 */
997 user_mod.regs.gpr[3] = check;
998 /* put bad_return return address in Link Register */
999 user_mod.regs.link = bad_return;
1000 #elif defined(VGA_s390x)
1001 /* put check arg in register r2 */
1002 user_mod.regs.gprs[2] = check;
1003 /* bad_return Return address is in r14 */
1004 user_mod.regs.gprs[14] = bad_return;
1005 /* minimum stack frame */
1007 user_mod.regs.gprs[15] = sp;
1008 /* set program counter */
1009 user_mod.regs.psw.addr = shared64->invoke_gdbserver;
1011 I_die_here: architecture missing in vgdb.c
1018 if (!setregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
1019 detach_from_all_threads(pid);
1022 /* Now that we have modified the registers, we set
1023 pid_of_save_regs to indicate that restore_and_detach
1024 must restore the registers in case of cleanup. */
1025 pid_of_save_regs = pid;
1026 pid_of_save_regs_continued = False;
1029 /* We PTRACE_CONT-inue pid.
1030 Either gdbserver will be invoked directly (if all
1031 threads are interruptible) or gdbserver will be
1032 called soon by the scheduler. In the first case,
1033 pid will stop on the break inserted above when
1034 gdbserver returns. In the 2nd case, the break will
1035 be encountered directly. */
1036 DEBUG(1, "PTRACE_CONT to invoke\n");
1037 res = ptrace (PTRACE_CONT, pid, NULL, NULL);
1039 ERROR(errno, "PTRACE_CONT\n");
1040 restore_and_detach(pid);
1043 pid_of_save_regs_continued = True;
1045 stopped = waitstopped (pid, SIGTRAP,
1046 "waitpid status after PTRACE_CONT to invoke");
1048 /* Here pid has properly stopped on the break. */
1049 pid_of_save_regs_continued = False;
1050 restore_and_detach(pid);
1053 /* Whatever kind of problem happened. We shutdown */
1054 shutting_down = True;
1061 void cleanup_restore_and_detach(void *v_pid)
1063 DEBUG(1, "cleanup_restore_and_detach dying: %d\n", dying);
1064 #ifdef PTRACEINVOKER
1066 restore_and_detach(*(int*)v_pid);
1070 /* This function loops till shutting_down becomes true. In this loop,
1071 it verifies if valgrind process is reading the characters written
1072 by vgdb. The verification is done every max_invoke_ms ms. If
1073 valgrind is not reading characters, it will use invoke_gdbserver
1074 (if PTRACE_INVOKER is defined) to ensure that the gdbserver code is
1075 called soon by valgrind. */
1076 static int max_invoke_ms = 100;
1078 void *invoke_gdbserver_in_valgrind(void *v_pid)
1080 int pid = *(int *)v_pid;
1081 int written_by_vgdb_before_sleep;
1082 int seen_by_valgrind_before_sleep;
1084 int invoked_written = -1;
1086 pthread_cleanup_push(cleanup_restore_and_detach, v_pid);
1088 while (!shutting_down) {
1089 written_by_vgdb_before_sleep = VS_written_by_vgdb;
1090 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
1092 "written_by_vgdb_before_sleep %d "
1093 "seen_by_valgrind_before_sleep %d\n",
1094 written_by_vgdb_before_sleep,
1095 seen_by_valgrind_before_sleep);
1096 if (usleep(1000 * max_invoke_ms) != 0) {
1099 XERROR (errno, "error usleep\n");
1101 /* if nothing happened during our sleep, let's try to wake up valgrind */
1102 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
1103 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
1104 && VS_written_by_vgdb > VS_seen_by_valgrind) {
1107 "written_by_vgdb %d "
1108 "seen_by_valgrind %d "
1109 "invoked_written %d\n",
1111 VS_seen_by_valgrind,
1113 /* if the pid does not exist anymore, we better stop */
1114 if (kill(pid, 0) != 0)
1116 "invoke_gdbserver_in_valgrind: "
1117 "check for pid %d existence failed\n", pid);
1119 #if defined(PTRACEINVOKER)
1120 /* only need to wake up if the nr written has changed since
1122 if (invoked_written != written_by_vgdb_before_sleep) {
1123 if (invoke_gdbserver(pid)) {
1124 /* If invoke succesful, no need to invoke again
1125 for the same value of written_by_vgdb_before_sleep. */
1126 invoked_written = written_by_vgdb_before_sleep;
1130 DEBUG(2, "invoke_gdbserver via ptrace not (yet) implemented\n");
1134 pthread_cleanup_pop(0);
1139 int open_fifo (char* name, int flags, char* desc)
1142 DEBUG(1, "opening %s %s\n", name, desc);
1143 fd = open(name, flags);
1145 XERROR (errno, "error opening %s %s\n", name, desc);
1147 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
1151 /* acquire a lock on the first byte of the given fd. If not successful,
1153 This allows to avoid having two vgdb speaking with the same Valgrind
1154 gdbserver as this causes serious headaches to the protocol. */
1156 void acquire_lock (int fd, int valgrind_pid)
1158 if (lockf(fd, F_TLOCK, 1) < 0) {
1159 if (errno == EAGAIN || errno == EACCES) {
1161 "Cannot acquire lock.\n"
1162 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
1166 XERROR(errno, "cannot acquire lock.\n");
1170 /* Here, we have the lock. It will be released when fd will be closed. */
1171 /* We indicate our pid to Valgrind gdbserver */
1172 if (shared32 != NULL)
1173 shared32->vgdb_pid = getpid();
1174 else if (shared64 != NULL)
1175 shared64->vgdb_pid = getpid();
1180 #define PBUFSIZ 16384 /* keep in sync with server.h */
1182 /* read some characters from fd.
1183 Returns the nr of characters read, -1 if error.
1184 desc is a string used in tracing */
1186 int read_buf (int fd, char* buf, char* desc)
1189 DEBUG(2, "reading %s\n", desc);
1190 nrread = read(fd, buf, PBUFSIZ);
1192 ERROR (errno, "error reading %s\n", desc);
1196 DEBUG(2, "read %s %s\n", desc, buf);
1200 /* write size bytes from buf to fd.
1201 desc is a description of the action for which the write is done.
1202 If notify, then add size to the shared cntr indicating to the
1203 valgrind process that there is new data.
1204 Returns True if write is ok, False if there was a problem. */
1206 Bool write_buf(int fd, char* buf, int size, char* desc, Bool notify)
1210 DEBUG(2, "writing %s len %d %s notify: %d\n", desc, size, buf, notify);
1212 while (nrwritten < size) {
1213 nrw = write (fd, buf+nrwritten, size - nrwritten);
1215 ERROR(errno, "error write %s\n", desc);
1218 nrwritten = nrwritten + nrw;
1229 TO_PID } ConnectionKind;
1230 static const int NumConnectionKind = TO_PID+1;
1232 char *ppConnectionKind (ConnectionKind con)
1235 case FROM_GDB: return "FROM_GDB";
1236 case TO_GDB: return "TO_GDB";
1237 case FROM_PID: return "FROM_PID";
1238 case TO_PID: return "TO_PID";
1239 default: return "invalid connection kind";
1243 static char *shared_mem;
1245 static const int from_gdb = 0;
1246 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
1247 /* Returns True in case read/write operations were done properly.
1248 Returns False in case of error.
1249 to_pid is the file descriptor to write to the process pid. */
1251 Bool read_from_gdb_write_to_pid(int to_pid)
1256 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
1259 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
1261 DEBUG(1, "error reading bytes from gdb\n");
1263 shutting_down = True;
1266 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
1269 static const int to_gdb = 1;
1270 static char *to_gdb_from_pid; /* fifo name to read pid replies */
1271 /* Returns True in case read/write operations were done properly.
1272 Returns False in case of error.
1273 from_pid is the file descriptor to read data from the process pid. */
1275 Bool read_from_pid_write_to_gdb(int from_pid)
1280 nrread = read_buf(from_pid, buf, "from pid");
1283 DEBUG(1, "read 0 bytes from pid => assume exit\n");
1285 DEBUG(1, "error reading bytes from pid\n");
1287 shutting_down = True;
1290 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
1293 /* prepares the FIFOs filenames, map the shared memory. */
1295 void prepare_fifos_and_shared_mem(int pid)
1297 from_gdb_to_pid = vmalloc (strlen(vgdb_prefix) + 30);
1298 to_gdb_from_pid = vmalloc (strlen(vgdb_prefix) + 30);
1299 shared_mem = vmalloc (strlen(vgdb_prefix) + 30);
1300 /* below 3 lines must match the equivalent in remote-utils.c */
1301 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d", vgdb_prefix, pid);
1302 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d", vgdb_prefix, pid);
1303 sprintf(shared_mem, "%s-shared-mem-vgdb-%d", vgdb_prefix, pid);
1304 DEBUG (1, "vgdb: using %s %s %s\n",
1305 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
1307 map_vgdbshared(shared_mem);
1310 /* Convert hex digit A to a number. */
1315 if (a >= '0' && a <= '9')
1317 else if (a >= 'a' && a <= 'f')
1318 return a - 'a' + 10;
1320 XERROR(0, "Reply contains invalid hex digit %c\n", a);
1324 /* Returns next char from fd. -1 if error, -2 if EOF.
1325 NB: must always call it with the same fd */
1329 static unsigned char buf[PBUFSIZ];
1330 static int bufcnt = 0;
1331 static unsigned char *bufp;
1336 bufcnt = read (fd, buf, sizeof (buf));
1340 fprintf (stderr, "readchar: Got EOF\n");
1343 ERROR (errno, "readchar\n");
1353 /* Read a packet from fromfd, with error checking,
1354 and store it in BUF.
1355 Returns length of packet, or -1 if error or -2 if EOF.
1356 Writes ack on ackfd */
1359 getpkt (char *buf, int fromfd, int ackfd)
1362 unsigned char csum, c1, c2;
1369 c = readchar (fromfd);
1372 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
1379 c = readchar (fromfd);
1390 repeat = readchar (fromfd);
1392 for (r = 0; r < repeat - 29; r ++)
1401 c1 = fromhex (readchar (fromfd));
1402 c2 = fromhex (readchar (fromfd));
1404 if (csum == (c1 << 4) + c2)
1407 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1408 (c1 << 4) + c2, csum, buf);
1409 if (write (ackfd, "-", 1) != 1)
1410 ERROR(0, "error when writing - (nack)\n");
1415 DEBUG(2, "getpkt (\"%s\"); [sending ack] \n", buf);
1416 if (write (ackfd, "+", 1) != 1)
1417 ERROR(0, "error when writing + (ack)\n");
1423 static int sigint = 0;
1424 static int sigterm = 0;
1425 static int sigpipe = 0;
1426 static int sighup = 0;
1427 static int sigusr1 = 0;
1428 static int sigalrm = 0;
1429 static int sigusr1_fd = -1;
1430 static pthread_t invoke_gdbserver_in_valgrind_thread;
1433 void received_signal (int signum)
1435 if (signum == SIGINT)
1437 else if (signum == SIGUSR1) {
1439 if (sigusr1_fd >= 0) {
1440 char control_c = '\003';
1441 write_buf(sigusr1_fd, &control_c, 1,
1442 "write \\003 on SIGUSR1", /* notify */ True);
1445 else if (signum == SIGTERM) {
1446 shutting_down = True;
1448 } else if (signum == SIGHUP) {
1449 shutting_down = True;
1451 } else if (signum == SIGPIPE) {
1453 } else if (signum == SIGALRM) {
1455 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
1456 /* Note: we cannot directly invoke restore_and_detach : this must
1457 be done by the thread that has attached.
1458 We have in this thread pushed a cleanup handler that will
1459 cleanup what is needed. */
1460 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
1462 ERROR(0, "unexpected signal %d\n", signum);
1466 /* install the signal handlers allowing e.g. vgdb to cleanup in
1467 case of termination. */
1469 void install_handlers(void)
1471 struct sigaction action, oldaction;
1473 action.sa_handler = received_signal;
1474 sigemptyset (&action.sa_mask);
1475 action.sa_flags = 0;
1477 /* SIGINT: when user types C-c in gdb, this sends
1478 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
1479 The later is enough to wakeup the valgrind process. */
1480 if (sigaction (SIGINT, &action, &oldaction) != 0)
1481 XERROR (errno, "vgdb error sigaction SIGINT\n");
1482 /* We might do something more intelligent than just
1483 reporting this SIGINT E.g. behave similarly to the gdb: two
1484 control-C without feedback from the debugged process would
1485 mean to stop debugging it. */
1487 /* SIGUSR1: this is used to facilitate automatic testing. When
1488 vgdb receives this signal, it will simulate the user typing C-c. */
1489 if (sigaction (SIGUSR1, &action, &oldaction) != 0)
1490 XERROR (errno, "vgdb error sigaction SIGUSR1\n");
1493 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
1494 when detaching or similar. A clean shutdown will be done as both
1495 the read and write side will detect an end of file. */
1496 if (sigaction (SIGTERM, &action, &oldaction) != 0)
1497 XERROR (errno, "vgdb error sigaction SIGTERM\n");
1499 /* SIGPIPE: can receive this signal when gdb detaches or kill the
1500 process debugged: gdb will close its pipes to vgdb. vgdb
1501 must resist to this signal to allow a clean shutdown. */
1502 if (sigaction (SIGPIPE, &action, &oldaction) != 0)
1503 XERROR (errno, "vgdb error sigaction SIGPIPE\n");
1505 /* SIGALRM: in case invoke thread is blocked, alarm is used
1507 if (sigaction (SIGALRM, &action, &oldaction) != 0)
1508 XERROR (errno, "vgdb error sigaction SIGALRM\n");
1511 /* close the FIFOs provided connections, terminate the invoker thread. */
1513 void close_connection(int to_pid, int from_pid)
1515 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
1516 sigint, sigterm, sighup, sigpipe);
1517 /* Note that we do not forward sigterm to the valgrind process:
1518 a sigterm signal is (probably) received from gdb if the user wants to
1519 kill the debugged process. The kill instruction has been given to
1520 the valgrind process, which should execute a clean exit. */
1522 /* We first close the connection to pid. The pid will then
1523 terminates its gdbserver work. We keep the from pid
1524 fifo opened till the invoker thread is finished.
1525 This allows the gdbserver to finish sending its last reply. */
1526 if (close(to_pid) != 0)
1527 ERROR(errno, "close to_pid\n");
1529 /* if there is a task that was busy trying to wake up valgrind
1530 process, we wait for it to be terminated otherwise threads
1531 in the valgrind process can stay stopped if vgdb main
1532 exits before the invoke thread had time to detach from
1533 all valgrind threads. */
1534 if (max_invoke_ms > 0) {
1537 /* It is surprisingly complex to properly shutdown or exit the
1538 valgrind process in which gdbserver has been invoked through
1539 ptrace. In the normal case (gdb detaches from the process,
1540 or process is continued), the valgrind process will reach the
1541 breakpoint place. Using ptrace, vgdb will ensure the
1542 previous activity of the process is resumed (e.g. restart a
1543 blocking system call). The special case is when gdb asks the
1544 valgrind process to exit (using either the "kill" command or
1545 "monitor exit"). In such a case, the valgrind process will
1546 call exit. But a ptraced process will be blocked in exit,
1547 waiting for the ptracing process to detach or die. vgdb
1548 cannot detach unconditionally as otherwise, in the normal
1549 case, the valgrind process would die abnormally with SIGTRAP
1550 (as vgdb would not be there to catch it). vgdb can also not
1551 die unconditionally otherwise again, similar problem. So, we
1552 assume that most of the time, we arrive here in the normal
1553 case, and so, the breakpoint has been encountered by the
1554 valgrind process, so the invoker thread will exit and the
1555 join will succeed. For the "kill" case, we cause an alarm
1556 signal to be sent after a few seconds. This means that in the
1557 normal case, the gdbserver code in valgrind process must have
1558 returned the control in less than the alarm nr of seconds,
1559 otherwise, valgrind will die abnormally with SIGTRAP. */
1562 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
1563 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
1567 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
1569 if (close(from_pid) != 0)
1570 ERROR(errno, "close from_pid\n");
1573 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
1574 error is encountered. */
1576 void gdb_relay (int pid)
1578 int from_pid = -1; /* fd to read from pid */
1579 int to_pid = -1; /* fd to write to pid */
1581 int shutdown_loop = 0;
1582 fprintf (stderr, "relaying data between gdb and process %d\n", pid);
1585 if (max_invoke_ms > 0)
1586 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1587 invoke_gdbserver_in_valgrind, (void *) &pid);
1588 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1589 acquire_lock (shared_mem_fd, pid);
1591 from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
1592 "read mode from pid");
1594 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1599 struct pollfd pollfds[NumConnectionKind];
1601 /* watch data written by gdb, watch POLLERR on both gdb fd */
1602 pollfds[FROM_GDB].fd = from_gdb;
1603 pollfds[FROM_GDB].events = POLLIN;
1604 pollfds[FROM_GDB].revents = 0;
1605 pollfds[TO_GDB].fd = to_gdb;
1606 pollfds[TO_GDB].events = 0;
1607 pollfds[TO_GDB].revents = 0;
1609 /* watch data written by pid, watch POLLERR on both pid fd */
1610 pollfds[FROM_PID].fd = from_pid;
1611 pollfds[FROM_PID].events = POLLIN;
1612 pollfds[FROM_PID].revents = 0;
1613 pollfds[TO_PID].fd = to_pid;
1614 pollfds[TO_PID].events = 0;
1615 pollfds[TO_PID].revents = 0;
1621 : -1 /* infinite */));
1622 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1624 /* check for unexpected error */
1625 if (ret <= 0 && errno != EINTR) {
1626 ERROR (errno, "unexpected poll ret %d\n", ret);
1627 shutting_down = True;
1631 /* check for data to read */
1632 for (ck = 0; ck < NumConnectionKind; ck ++) {
1633 if (pollfds[ck].revents & POLLIN) {
1636 if (!read_from_gdb_write_to_pid(to_pid))
1637 shutting_down = True;
1640 if (!read_from_pid_write_to_gdb(from_pid))
1641 shutting_down = True;
1643 default: XERROR(0, "unexpected POLLIN on %s\n",
1644 ppConnectionKind(ck));
1649 /* check for an fd being in error condition */
1650 for (ck = 0; ck < NumConnectionKind; ck ++) {
1651 if (pollfds[ck].revents & POLLERR) {
1652 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1653 ppConnectionKind(ck), pollfds[ck].fd);
1655 shutting_down = True;
1657 if (pollfds[ck].revents & POLLHUP) {
1658 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1659 ppConnectionKind(ck), pollfds[ck].fd);
1661 shutting_down = True;
1663 if (pollfds[ck].revents & POLLNVAL) {
1664 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1665 ppConnectionKind(ck), pollfds[ck].fd);
1667 shutting_down = True;
1671 if (shutting_down) {
1672 /* we let some time to the final packets to be transferred */
1674 if (shutdown_loop > 3)
1678 close_connection(to_pid, from_pid);
1681 static int packet_len_for_command(char *cmd)
1683 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1684 return 7+ 2*strlen(cmd) +3 + 1;
1687 /* hyper-minimal protocol implementation that
1688 sends the provided commands (using qRcmd packets)
1689 and read and display their replies. */
1691 void standalone_send_commands(int pid,
1695 int from_pid = -1; /* fd to read from pid */
1696 int to_pid = -1; /* fd to write to pid */
1700 unsigned char hex[3];
1701 unsigned char cksum;
1702 unsigned char *hexcommand;
1703 unsigned char buf[PBUFSIZ];
1708 if (max_invoke_ms > 0)
1709 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1710 invoke_gdbserver_in_valgrind, (void *) &pid);
1712 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1713 acquire_lock (shared_mem_fd, pid);
1715 /* first send a C-c \003 to pid, so that it wakes up the process
1716 After that, we can open the fifo from the pid in read mode
1717 We then start to wait for packets (normally first a resume reply)
1718 At that point, we send our command and expect replies */
1720 write_buf(to_pid, buf, 1, "write \\003 to wake up", /* notify */ True);
1721 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1722 "read cmd result from pid");
1724 for (nc = 0; nc <= last_command; nc++) {
1725 fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
1728 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1729 hexcommand = vmalloc (packet_len_for_command(commands[nc]));
1731 strcat (hexcommand, "$qRcmd,");
1732 for (i = 0; i < strlen(commands[nc]); i++) {
1733 sprintf(hex, "%02x", commands[nc][i]);
1734 strcat (hexcommand, hex);
1736 /* checksum (but without the $) */
1738 for (hi = 1; hi < strlen(hexcommand); hi++)
1739 cksum+=hexcommand[hi];
1740 strcat(hexcommand, "#");
1741 sprintf(hex, "%02x", cksum);
1742 strcat(hexcommand, hex);
1743 write_buf(to_pid, hexcommand, strlen(hexcommand),
1744 "writing hex command to pid", /* notify */ True);
1746 /* we exit of the below loop explicitely when the command has
1747 been handled or because a signal handler will set
1749 while (!shutting_down) {
1750 buflen = getpkt(buf, from_pid, to_pid);
1752 ERROR (0, "error reading packet\n");
1757 if (strlen(buf) == 0) {
1758 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1761 if (strcmp(buf, "OK") == 0) {
1762 DEBUG(1, "OK packet rcvd\n");
1765 if (buf[0] == 'E') {
1767 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1771 if (buf[0] == 'W') {
1772 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1775 if (buf[0] == 'T') {
1776 DEBUG(1, "T resume reply packet received: %s\n", buf);
1780 /* must be here an O packet with hex encoded string reply
1781 => decode and print it */
1782 if (buf[0] != 'O') {
1783 DEBUG(0, "expecting O packet, received: %s\n", buf);
1787 char buf_print[buflen/2 + 1];
1788 for (i = 1; i < buflen; i = i + 2)
1789 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1790 + fromhex(*(buf+i+1));
1791 buf_print[buflen/2] = 0;
1792 printf("%s", buf_print);
1798 shutting_down = True;
1800 close_connection(to_pid, from_pid);
1803 /* report to user the existence of a vgdb-able valgrind process
1806 void report_pid (int pid)
1808 char cmdline_file[100];
1813 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1814 fd = open (cmdline_file, O_RDONLY);
1816 DEBUG(1, "error opening cmdline file %s %s\n",
1817 cmdline_file, strerror(errno));
1818 sprintf(cmdline, "(could not obtain process command line)");
1820 sz = read(fd, cmdline, 1000);
1821 for (i = 0; i < sz; i++)
1822 if (cmdline[i] == 0)
1827 fprintf(stderr, "use --pid=%d for %s\n", pid, cmdline);
1831 /* Eventually produces additional usage information documenting the
1832 ptrace restrictions. */
1834 void ptrace_restrictions(void)
1836 # ifdef PR_SET_PTRACER
1837 char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
1839 char ptrace_scope = 'X';
1840 fd = open (ptrace_scope_setting_file, O_RDONLY, 0);
1841 if (fd >= 0 && (read (fd, &ptrace_scope, 1) == 1) && (ptrace_scope != '0')) {
1843 "Note: your kernel restricts ptrace invoker using %s\n"
1844 "vgdb will only be able to attach to a Valgrind process\n"
1845 "blocked in a system call *after* an initial successful attach\n",
1846 ptrace_scope_setting_file);
1847 } else if (ptrace_scope == 'X') {
1849 "PR_SET_PTRACER defined"
1850 " but could not determine ptrace scope from %s\n",
1851 ptrace_scope_setting_file);
1857 # ifndef PTRACEINVOKER
1859 "Note: ptrace invoker not implemented\n"
1860 "For more info: read user manual section"
1861 " 'Limitations of the Valgrind gdbserver'\n");
1869 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1870 "vgdb (valgrind gdb) has two usages\n"
1871 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1872 " The OPTION(s) must be followed by the command to send\n"
1873 " To send more than one command, separate the commands with -c\n"
1874 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1875 " Only OPTION(s) can be given.\n"
1877 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1878 " [--max-invoke-ms=<number>] [--wait=<number>] [-d] [-D] [-l]\n"
1879 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1880 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1881 " if you want to change the default prefix for the FIFOs communication\n"
1882 " between the Valgrind gdbserver and vgdb.\n"
1883 " --wait arg tells vgdb to check during the specified number\n"
1884 " of seconds if a Valgrind gdbserver can be found.\n"
1885 " --max-invoke-ms gives the nr of milli-seconds after which vgdb will force\n"
1886 " the invocation of the Valgrind gdbserver (if the Valgrind process\n"
1887 " is blocked in a system call).\n"
1888 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1889 " -D arg tells to show shared mem status and then exit.\n"
1890 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1892 " -h --help shows this message\n"
1893 " To get help from the Valgrind gdbserver, use vgdb help\n"
1896 ptrace_restrictions();
1899 /* If show_list, shows the list of Valgrind processes with gdbserver activated.
1902 else if arg_pid == -1, waits maximum check_trials seconds to discover
1903 a valgrind pid appearing.
1905 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1906 with gdbserver activated.
1908 Returns the pid to work with
1909 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1912 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1917 if (arg_pid == 0 || arg_pid < -1) {
1918 fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1921 /* search for a matching named fifo.
1922 If we have been given a pid, we will check that the matching FIFO is
1923 there (or wait the nr of check_trials for this to appear).
1924 If no pid has been given, then if we find only one FIFO,
1925 we will use this to build the pid to use.
1926 If we find multiple processes with valid FIFO, we report them and will
1927 exit with an error. */
1929 char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
1932 int nr_valid_pid = 0;
1933 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1934 char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
1936 strcpy (vgdb_format, vgdb_prefix);
1937 strcat (vgdb_format, suffix);
1939 strcpy (vgdb_dir_name, vgdb_prefix);
1941 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1942 if (vgdb_dir_name[is] == '/') {
1943 vgdb_dir_name[is+1] = '\0';
1946 if (strlen(vgdb_dir_name) == 0)
1947 strcpy (vgdb_dir_name, "./");
1949 DEBUG(1, "searching pid in directory %s format %s\n",
1950 vgdb_dir_name, vgdb_format);
1952 /* try to find FIFOs with valid pid.
1953 On exit of the loop, pid is set to:
1954 the last pid found if show_list (or -1 if no process was listed)
1955 -1 if no FIFOs matching a running process is found
1956 -2 if multiple FIFOs of running processes are found
1957 otherwise it is set to the (only) pid found that can be debugged
1959 for (i = 0; i < check_trials; i++) {
1960 DEBUG(1, "check_trial %d \n", i);
1962 /* wait one second before checking again */
1965 vgdb_dir = opendir (vgdb_dir_name);
1966 if (vgdb_dir == NULL)
1968 "vgdb error: opening directory %s searching vgdb fifo\n",
1971 errno = 0; /* avoid complain if vgdb_dir is empty */
1972 while ((f = readdir (vgdb_dir))) {
1974 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name)];
1978 strcpy (pathname, vgdb_dir_name);
1979 strcat (pathname, f->d_name);
1980 DEBUG(3, "trying %s\n", pathname);
1981 if (stat (pathname, &st) != 0) {
1982 if (debuglevel >= 3)
1983 ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n",
1985 } else if (S_ISFIFO (st.st_mode)) {
1986 DEBUG(3, "trying %s\n", pathname);
1987 if (strncmp (pathname, vgdb_format,
1988 strlen (vgdb_format)) == 0) {
1989 newpid = strtol(pathname + strlen (vgdb_format),
1991 if (*wrongpid == '\0' && newpid > 0
1992 && kill (newpid, 0) == 0) {
1995 report_pid (newpid);
1997 } else if (arg_pid != -1) {
1998 if (arg_pid == newpid) {
2001 } else if (nr_valid_pid > 1) {
2002 if (nr_valid_pid == 2) {
2005 "no --pid= arg given"
2006 " and multiple valgrind pids found:\n");
2010 report_pid (newpid);
2017 errno = 0; /* avoid complain if at the end of vgdb_dir */
2019 if (f == NULL && errno != 0)
2020 XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n",
2023 closedir (vgdb_dir);
2028 free (vgdb_dir_name);
2034 } else if (pid == -1) {
2036 fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
2038 fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n",
2042 else if (pid == -2) {
2043 /* no arg_pid given, multiple FIFOs found */
2051 /* return true if the numeric value of an option of the
2052 form --xxxxxxxxx=<number> could properly be extracted
2053 from arg. If True is returned, *value contains the
2056 Bool numeric_val(char* arg, int *value)
2058 const char *eq_pos = strchr(arg, '=');
2064 *value = strtol(eq_pos+1, &wrong, 10);
2071 /* true if arg matches the provided option */
2073 Bool is_opt(char* arg, char *option)
2075 int option_len = strlen(option);
2076 if (option[option_len-1] == '=')
2077 return (0 == strncmp(option, arg, option_len));
2079 return (0 == strcmp(option, arg));
2082 /* Parse command lines options. If error(s), exits.
2083 Otherwise returns the options in *p_... args.
2084 commands must be big enough for the commands extracted from argv.
2085 On return, *p_last_command gives the position in commands where
2086 the last command has been allocated (using vmalloc). */
2088 void parse_options(int argc, char** argv,
2089 Bool *p_show_shared_mem,
2092 int *p_check_trials,
2093 int *p_last_command,
2096 Bool show_shared_mem = False;
2097 Bool show_list = False;
2099 int check_trials = 1;
2100 int last_command = -1;
2105 for (i = 1; i < argc; i++) {
2106 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2109 } else if (is_opt(argv[i], "-d")) {
2111 } else if (is_opt(argv[i], "-D")) {
2112 show_shared_mem = True;
2113 } else if (is_opt(argv[i], "-l")) {
2115 } else if (is_opt(argv[i], "--pid=")) {
2117 if (!numeric_val(argv[i], &newpid)) {
2118 fprintf (stderr, "invalid pid argument %s\n", argv[i]);
2120 } else if (arg_pid != -1) {
2121 fprintf (stderr, "multiple pid arguments given\n");
2126 } else if (is_opt(argv[i], "--wait=")) {
2127 if (!numeric_val(argv[i], &check_trials)) {
2128 fprintf (stderr, "invalid wait argument %s\n", argv[i]);
2131 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2132 if (!numeric_val(argv[i], &max_invoke_ms)) {
2133 fprintf (stderr, "invalid max-invoke-ms argument %s\n", argv[i]);
2136 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2137 vgdb_prefix = argv[i] + 14;
2138 } else if (is_opt(argv[i], "-c")) {
2140 commands[last_command] = vmalloc (1);
2141 commands[last_command][0] = '\0';
2142 } else if (0 == strncmp(argv[i], "-", 1)) {
2143 fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
2147 if (last_command == -1) {
2148 /* only one command, no -c command indicator */
2150 commands[last_command] = vmalloc (1);
2151 commands[last_command][0] = '\0';
2153 len = strlen(commands[last_command]);
2154 commands[last_command] = vrealloc (commands[last_command],
2155 len + 1 + strlen(argv[i]) + 1);
2157 strcat (commands[last_command], " ");
2158 strcat (commands[last_command], argv[i]);
2159 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2160 fprintf (stderr, "command %s too long\n", commands[last_command]);
2170 && last_command == -1) {
2173 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2176 if (show_shared_mem && show_list) {
2179 "Can't use both -D and -l options\n");
2182 if (show_list && arg_pid != -1) {
2185 "Can't use both --pid and -l options\n");
2188 if (arg_errors > 0) {
2189 fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
2193 *p_show_shared_mem = show_shared_mem;
2194 *p_show_list = show_list;
2195 *p_arg_pid = arg_pid;
2196 *p_check_trials = check_trials;
2197 *p_last_command = last_command;
2200 int main(int argc, char** argv)
2205 Bool show_shared_mem;
2210 char *commands[argc]; // we will never have more commands than args.
2212 parse_options(argc, argv,
2220 /* when we are working as a relay for gdb, handle some signals by
2221 only reporting them (according to debug level). Also handle these
2222 when ptrace will be used: vgdb must clean up the ptrace effect before
2224 if (max_invoke_ms > 0 || last_command == -1)
2227 pid = search_arg_pid (arg_pid, check_trials, show_list);
2229 prepare_fifos_and_shared_mem(pid);
2231 if (show_shared_mem) {
2234 "written_by_vgdb %d "
2235 "seen_by_valgrind %d\n"
2239 VS_seen_by_valgrind,
2244 if (last_command >= 0) {
2245 standalone_send_commands(pid, last_command, commands);
2251 free (from_gdb_to_pid);
2252 free (to_gdb_from_pid);
2255 for (i = 0; i <= last_command; i++)
2259 /*--------------------------------------------------------------------*/
2260 /*--- Relay between gdb and gdbserver embedded in valgrind vgdb.c ---*/
2261 /*--------------------------------------------------------------------*/
2264 This file is part of Valgrind, a dynamic binary instrumentation
2267 Copyright (C) 2011 Philippe Waroquiers
2269 This program is free software; you can redistribute it and/or
2270 modify it under the terms of the GNU General Public License as
2271 published by the Free Software Foundation; either version 2 of the
2272 License, or (at your option) any later version.
2274 This program is distributed in the hope that it will be useful, but
2275 WITHOUT ANY WARRANTY; without even the implied warranty of
2276 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
2277 General Public License for more details.
2279 You should have received a copy of the GNU General Public License
2280 along with this program; if not, write to the Free Software
2281 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
2284 The GNU General Public License is contained in the file COPYING.
2286 #include "pub_core_basics.h"
2287 #include "pub_core_vki.h"
2288 #include "pub_core_libcsetjmp.h"
2289 #include "pub_core_threadstate.h"
2290 #include "pub_core_gdbserver.h"
2295 #include <pthread.h>
2300 #include <sys/stat.h>
2301 #include <sys/time.h>
2304 #include <sys/mman.h>
2305 #include <sys/ptrace.h>
2306 #include <sys/wait.h>
2308 #include <sys/user.h>
2310 # if defined(VGO_linux)
2311 #include <sys/prctl.h>
2314 /* vgdb has two usages:
2315 1. relay application between gdb and the gdbserver embedded in valgrind.
2316 2. standalone to send monitor commands to a running valgrind-ified process
2318 It is made of a main program which reads arguments. If no
2319 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
2322 As relay application, vgdb reads bytes from gdb on stdin and
2323 writes these bytes to valgrind. Bytes read from valgrind are
2324 written to gdb on stdout. Read/Write from/to valgrind is done
2325 using FIFOs. There is one thread reading from stdin, writing to
2326 valgrind on a FIFO. There is one thread reading from valgrind on a
2327 FIFO, writing to gdb on stdout
2329 As a standalone utility, vgdb builds command packets to write to valgrind,
2330 sends it and reads the reply. The same two threads are used to write/read.
2331 Once all the commands are sent and their replies received, vgdb will exit.
2335 /* define PTRACEINVOKER to compile the ptrace related code
2336 which ensures a valgrind process blocked in a system call
2337 can be "waken up". PTRACEINVOKER implies some architecture
2338 specific code and/or some OS specific code. */
2339 #if defined(VGA_arm) || defined(VGA_x86) || defined(VGA_amd64) \
2340 || defined(VGA_ppc32) || defined(VGA_ppc64) || defined(VGA_s390x)
2341 #define PTRACEINVOKER
2343 I_die_here : (PTRACEINVOKER) architecture missing in vgdb.c
2346 /* Some darwin specific stuff is needed as ptrace is not
2347 fully supported on MacOS. Till we find someone courageous
2348 having access to Darwin, there is no PTRACEINVOKER. */
2349 #if defined(VGO_darwin)
2350 #undef PTRACEINVOKER
2353 static int debuglevel;
2354 static struct timeval dbgtv;
2355 /* if level <= debuglevel, print timestamp, then print provided by debug info */
2356 #define DEBUG(level, ...) (level <= debuglevel ? \
2357 gettimeofday(&dbgtv, NULL), \
2358 fprintf(stderr, "%ld.%6.6ld ", \
2359 (long int)dbgtv.tv_sec, \
2360 (long int)dbgtv.tv_usec), \
2361 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
2364 /* same as DEBUG but does not print time stamp info */
2365 #define PDEBUG(level, ...) (level <= debuglevel ? \
2366 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
2370 report the errno and fprintf the ... varargs on stderr. */
2371 #define ERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
2372 fprintf(stderr, __VA_ARGS__), \
2374 /* same as ERROR, but also exits with status 1 */
2375 #define XERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
2376 fprintf(stderr, __VA_ARGS__), \
2380 static char *vgdb_prefix = "/tmp/vgdb-pipe";
2382 /* Will be set to True when any condition indicating we have to shutdown
2384 static Bool shutting_down = False;
2386 static VgdbShared32 *shared32;
2387 static VgdbShared64 *shared64;
2388 #define VS_written_by_vgdb (shared32 != NULL ? \
2389 shared32->written_by_vgdb \
2390 : shared64->written_by_vgdb)
2391 #define VS_seen_by_valgrind (shared32 != NULL ? \
2392 shared32->seen_by_valgrind \
2393 : shared64->seen_by_valgrind)
2395 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
2397 /* Calls malloc (size). Exits if memory can't be allocated. */
2399 void *vmalloc(size_t size)
2401 void * mem = malloc(size);
2403 XERROR (errno, "can't allocate memory\n");
2407 /* Calls realloc (size). Exits if memory can't be allocated. */
2409 void *vrealloc(void *ptr,size_t size)
2411 void * mem = realloc(ptr, size);
2413 XERROR (errno, "can't reallocate memory\n");
2417 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
2419 void add_written(int nrw)
2421 if (shared32 != NULL)
2422 shared32->written_by_vgdb += nrw;
2423 else if (shared64 != NULL)
2424 shared64->written_by_vgdb += nrw;
2429 static int shared_mem_fd = -1;
2431 void map_vgdbshared (char* shared_mem)
2435 shared_mem_fd = open(shared_mem, O_RDWR);
2436 /* shared_mem_fd will not be closed till vgdb exits. */
2438 if (shared_mem_fd == -1)
2439 XERROR (errno, "error opening %s shared memory file\n", shared_mem);
2441 if (fstat(shared_mem_fd, &fdstat) != 0)
2442 XERROR (errno, "fstat");
2444 if (fdstat.st_size == sizeof(VgdbShared64))
2445 s = (void*) &shared64;
2446 else if (fdstat.st_size == sizeof(VgdbShared32))
2447 s = (void*) &shared32;
2449 #if VEX_HOST_WORDSIZE == 8
2451 "error size shared memory file %s.\n"
2452 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
2454 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
2455 (long int)fdstat.st_size);
2456 #elif VEX_HOST_WORDSIZE == 4
2458 "error size shared memory file %s.\n"
2459 "expecting size %d (32bits) got %ld.\n",
2461 (int) sizeof(VgdbShared32),
2464 # error "unexpected wordsize"
2467 #if VEX_HOST_WORDSIZE == 4
2468 if (shared64 != NULL)
2469 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
2470 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
2473 *s = (void*) mmap (NULL, fdstat.st_size,
2474 PROT_READ|PROT_WRITE, MAP_SHARED,
2477 if (*s == (void *) -1)
2478 XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
2482 #if VEX_HOST_WORDSIZE == 8
2483 typedef Addr64 CORE_ADDR;
2484 typedef Addr64 PTRACE_XFER_TYPE;
2485 typedef void* PTRACE_ARG3_TYPE;
2486 #elif VEX_HOST_WORDSIZE == 4
2487 typedef Addr32 CORE_ADDR;
2488 typedef Addr32 PTRACE_XFER_TYPE;
2489 typedef void* PTRACE_ARG3_TYPE;
2491 # error "unexpected wordsize"
2494 static Bool pid_of_save_regs_continued = False;
2495 // True if we have continued pid_of_save_regs after PTRACE_ATTACH
2497 static Bool dying = False;
2498 // Set to True when loss of connection indicating that the Valgrind
2499 // process is dying.
2501 /* To be called when connection with valgrind is lost. In case we
2502 have lost the connection, it means that Valgrind has closed the
2503 connection and is busy exiting. We can't and don't have to stop it in
2506 void valgrind_dying(void)
2508 pid_of_save_regs_continued = False;
2513 #ifdef PTRACEINVOKER
2514 /* ptrace_(read|write)_memory are modified extracts of linux-low.c
2515 from gdb 6.6. Copyrighted FSF */
2516 /* Copy LEN bytes from inferior's memory starting at MEMADDR
2517 to debugger memory starting at MYADDR. */
2520 int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
2521 unsigned char *myaddr, int len)
2524 /* Round starting address down to longword boundary. */
2525 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2526 /* Round ending address up; get number of longwords that makes. */
2528 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
2529 / sizeof (PTRACE_XFER_TYPE);
2530 /* Allocate buffer of that many longwords. */
2531 register PTRACE_XFER_TYPE *buffer
2532 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2534 /* Read all the longwords */
2535 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
2537 buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
2538 (PTRACE_ARG3_TYPE) addr, 0);
2543 /* Copy appropriate bytes out of the buffer. */
2545 (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
2550 /* Copy LEN bytes of data from debugger memory at MYADDR
2551 to inferior's memory at MEMADDR.
2552 On failure (cannot write the inferior)
2553 returns the value of errno. */
2556 int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr,
2557 const unsigned char *myaddr, int len)
2560 /* Round starting address down to longword boundary. */
2561 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2562 /* Round ending address up; get number of longwords that makes. */
2564 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
2565 / sizeof (PTRACE_XFER_TYPE);
2566 /* Allocate buffer of that many longwords. */
2567 register PTRACE_XFER_TYPE *buffer
2568 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2570 if (debuglevel >= 1) {
2571 DEBUG (1, "Writing ");
2572 for (i = 0; i < len; i++)
2573 PDEBUG (1, "%02x", (unsigned)myaddr[i]);
2574 PDEBUG(1, " to %p\n", (void *) memaddr);
2577 /* Fill start and end extra bytes of buffer with existing memory data. */
2579 buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
2580 (PTRACE_ARG3_TYPE) addr, 0);
2584 = ptrace (PTRACE_PEEKTEXT, inferior_pid,
2585 (PTRACE_ARG3_TYPE) (addr + (count - 1)
2586 * sizeof (PTRACE_XFER_TYPE)),
2590 /* Copy data to be written over corresponding part of buffer */
2592 memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
2595 /* Write the entire buffer. */
2597 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
2599 ptrace (PTRACE_POKETEXT, inferior_pid,
2600 (PTRACE_ARG3_TYPE) addr, buffer[i]);
2608 /* subset of VG_(threads) needed for vgdb ptrace.
2609 This is initialized when process is attached. */
2611 ThreadStatus status;
2615 static VgdbThreadState vgdb_threads[VG_N_THREADS];
2618 HChar* name_of_ThreadStatus ( ThreadStatus status )
2621 case VgTs_Empty: return "VgTs_Empty";
2622 case VgTs_Init: return "VgTs_Init";
2623 case VgTs_Runnable: return "VgTs_Runnable";
2624 case VgTs_WaitSys: return "VgTs_WaitSys";
2625 case VgTs_Yielding: return "VgTs_Yielding";
2626 case VgTs_Zombie: return "VgTs_Zombie";
2627 default: return "VgTs_???";
2632 char *status_image (int status)
2634 static char result[256];
2636 #define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
2640 if (WIFEXITED(status))
2641 APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
2643 if (WIFSIGNALED(status)) {
2644 APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
2645 if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
2648 if (WIFSTOPPED(status))
2649 APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
2651 if (WIFCONTINUED(status))
2652 APPEND ("WIFCONTINUED ");
2658 /* Wait till the process pid is reported as stopped with signal_expected.
2659 If other signal(s) than signal_expected are received, waitstopped
2660 will pass them to pid, waiting for signal_expected to stop pid.
2661 Returns True when process is in stopped state with signal_expected.
2662 Returns False if a problem was encountered while waiting for pid
2665 If pid is reported as being dead/exited, waitstopped will return False.
2668 Bool waitstopped (int pid, int signal_expected, char *msg)
2672 int signal_received;
2676 DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
2677 msg, signal_expected);
2678 p = waitpid(pid, &status, __WALL);
2679 DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p,
2680 status, status_image (status));
2682 ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n",
2683 msg, pid, p, status, status_image (status));
2687 if (WIFEXITED(status)) {
2688 shutting_down = True;
2692 assert (WIFSTOPPED(status));
2693 signal_received = WSTOPSIG(status);
2694 if (signal_received == signal_expected)
2697 /* pid received a signal which is not the signal we are waiting for.
2698 We continue pid, transmitting this signal. */
2699 DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
2700 res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
2702 ERROR(errno, "waitstopped PTRACE_CONT\n");
2710 /* Stops the given pid, wait for the process to be stopped.
2711 Returns True if succesful, False otherwise.
2712 msg is used in tracing and error reporting. */
2714 Bool stop (int pid, char *msg)
2718 DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
2719 res = kill (pid, SIGSTOP);
2721 ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
2725 return waitstopped (pid, SIGSTOP, msg);
2729 /* Attaches to given pid, wait for the process to be stopped.
2730 Returns True if succesful, False otherwise.
2731 msg is used in tracing and error reporting. */
2733 Bool attach (int pid, char *msg)
2737 DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
2738 res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
2740 ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
2744 return waitstopped(pid, SIGSTOP, msg);
2747 /* once we are attached to the pid, get the list of threads and stop
2749 Returns True if all threads properly suspended, False otherwise. */
2751 Bool acquire_and_suspend_threads(int pid)
2755 Bool pid_found = False;
2760 int nr_live_threads = 0;
2762 if (shared32 != NULL) {
2763 vgt = shared32->threads;
2764 sz_tst = shared32->sizeof_ThreadState;
2765 off_status = shared32->offset_status;
2766 off_lwpid = shared32->offset_lwpid;
2768 else if (shared64 != NULL) {
2769 vgt = shared64->threads;
2770 sz_tst = shared64->sizeof_ThreadState;
2771 off_status = shared64->offset_status;
2772 off_lwpid = shared64->offset_lwpid;
2777 /* note: the entry 0 is unused */
2778 for (i = 1; i < VG_N_THREADS; i++) {
2780 rw = ptrace_read_memory(pid, vgt+off_status,
2781 (unsigned char *)&(vgdb_threads[i].status),
2782 sizeof(ThreadStatus));
2784 ERROR(rw, "status ptrace_read_memory\n");
2788 rw = ptrace_read_memory(pid, vgt+off_lwpid,
2789 (unsigned char *)&(vgdb_threads[i].lwpid),
2792 ERROR(rw, "lwpid ptrace_read_memory\n");
2796 if (vgdb_threads[i].status != VgTs_Empty) {
2797 DEBUG(1, "found tid %d status %s lwpid %d\n",
2798 i, name_of_ThreadStatus(vgdb_threads[i].status),
2799 vgdb_threads[i].lwpid);
2801 if (vgdb_threads[i].lwpid <= 1) {
2802 if (vgdb_threads[i].lwpid == 0
2803 && vgdb_threads[i].status == VgTs_Init) {
2804 DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
2805 i, name_of_ThreadStatus(vgdb_threads[i].status),
2806 vgdb_threads[i].lwpid);
2808 ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
2809 i, name_of_ThreadStatus(vgdb_threads[i].status),
2810 vgdb_threads[i].lwpid);
2812 /* in case we have a VtTs_Init thread with lwpid not yet set,
2813 we try again later. */
2816 if (vgdb_threads[i].lwpid == pid) {
2817 assert (!pid_found);
2821 if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
2822 ERROR(0, "ERROR attach pid %d tid %d\n",
2823 vgdb_threads[i].lwpid, i);
2829 /* If we found no thread, it means the process is stopping, and
2830 we better do not force anything to happen during that. */
2831 if (nr_live_threads > 0)
2838 void detach_from_all_threads(int pid)
2842 Bool pid_found = False;
2844 /* detach from all the threads */
2845 for (i = 1; i < VG_N_THREADS; i++) {
2846 if (vgdb_threads[i].status != VgTs_Empty) {
2847 if (vgdb_threads[i].status == VgTs_Init
2848 && vgdb_threads[i].lwpid == 0) {
2849 DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
2850 vgdb_threads[i].lwpid, i,
2851 name_of_ThreadStatus (vgdb_threads[i].status));
2853 if (vgdb_threads[i].lwpid == pid) {
2854 assert (!pid_found);
2857 DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
2858 vgdb_threads[i].lwpid, i,
2859 name_of_ThreadStatus (vgdb_threads[i].status));
2860 res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
2862 ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n",
2863 vgdb_threads[i].lwpid, i,
2864 name_of_ThreadStatus (vgdb_threads[i].status),
2871 if (!pid_found && pid) {
2872 /* No threads are live. Process is busy stopping.
2873 We need to detach from pid explicitely. */
2874 DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
2875 res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
2877 ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
2881 // if > 0, pid for which registers have to be restored.
2882 static int pid_of_save_regs = 0;
2883 static struct user user_save;
2885 /* Get the registers from pid into regs.
2886 Returns True if all ok, otherwise False. */
2888 Bool getregs (int pid, void *regs)
2891 char *pregs = (char *) regs;
2894 DEBUG(1, "getregs PTRACE_PEEKUSER(s)\n");
2895 for (offset = 0; offset < PT_ENDREGS; offset = offset + sizeof(long)) {
2896 *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
2898 ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
2904 // Platforms having GETREGS
2906 DEBUG(1, "getregs PTRACE_GETREGS\n");
2907 res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
2909 ERROR(errno, "PTRACE_GETREGS %ld\n", res);
2916 /* Set the registers of pid to regs.
2917 Returns True if all ok, otherwise False. */
2919 Bool setregs (int pid, void *regs)
2922 char *pregs = (char *) regs;
2926 DEBUG(1, "setregs PTRACE_POKEUSER(s)\n");
2927 for (offset = 0; offset < PT_ENDREGS; offset = offset + sizeof(long)) {
2928 res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
2930 ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
2936 // Platforms having SETREGS
2938 DEBUG(1, "setregs PTRACE_SETREGS\n");
2939 res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
2941 ERROR(errno, "PTRACE_SETREGS %ld\n", res);
2948 /* Restore the registers to the saved value, then detaches from all threads */
2950 void restore_and_detach(int pid)
2952 if (pid_of_save_regs) {
2953 /* In case the 'main pid' has been continued, we need to stop it
2954 before resetting the registers. */
2955 if (pid_of_save_regs_continued) {
2956 pid_of_save_regs_continued = False;
2957 if (!stop(pid_of_save_regs, "sigstop before reset regs"))
2958 DEBUG(0, "Could not sigstop before reset");
2961 DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
2962 if (!setregs(pid_of_save_regs, &user_save.regs)) {
2963 ERROR(errno, "setregs restore registers pid %d after cont\n",
2966 pid_of_save_regs = 0;
2968 DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
2970 detach_from_all_threads(pid);
2973 /* Ensures that the gdbserver code is invoked by pid.
2974 If an error occurs, resets to the valgrind process
2975 to the state it has before being ptrace-d.
2976 Returns True if invoke successful, False otherwise.
2979 Bool invoke_gdbserver (int pid)
2983 struct user user_mod;
2985 /* A specific int value is passed to invoke_gdbserver, to check
2986 everything goes according to the plan. */
2987 const int check = 0x8BADF00D; // ate bad food.
2989 const Addr bad_return = 0;
2990 // A bad return address will be pushed on the stack.
2991 // The function invoke_gdbserver cannot return. If ever it returns, a NULL
2992 // address pushed on the stack should ensure this is detected.
2994 /* Not yet attached. If problem, vgdb can abort,
2997 On Ubuntu>= 10.10, a /proc setting can disable ptrace.
2998 So, Valgrind has to SET_PTRACER this vgdb. Once this
2999 is done, this vgdb can ptrace the valgrind process. */
3001 DEBUG(1, "attach to 'main' pid %d\n", pid);
3002 if (!attach(pid, "attach main pid")) {
3003 ERROR(0, "error attach main pid %d\n", pid);
3007 /* Now, we are attached. If problem, detach and return. */
3009 if (!acquire_and_suspend_threads(pid)) {
3010 detach_from_all_threads(pid);
3011 /* if the pid does not exist anymore, we better stop */
3012 if (kill(pid, 0) != 0)
3013 XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
3018 if (!getregs(pid, &user_mod.regs)) {
3019 detach_from_all_threads(pid);
3022 user_save = user_mod;
3024 #if defined(VGA_x86)
3025 sp = user_mod.regs.esp;
3026 #elif defined(VGA_amd64)
3027 sp = user_mod.regs.rsp;
3028 if (shared32 != NULL) {
3029 /* 64bit vgdb speaking with a 32bit executable.
3030 To have system call restart properly, we need to sign extend rax.
3032 web search '[patch] Fix syscall restarts for amd64->i386 biarch'
3033 e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
3034 *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
3035 DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
3036 user_mod.regs.rax, user_save.regs.rax);
3038 #elif defined(VGA_arm)
3039 sp = user_mod.regs.uregs[13];
3040 #elif defined(VGA_ppc32)
3041 sp = user_mod.regs.gpr[1];
3042 #elif defined(VGA_ppc64)
3043 sp = user_mod.regs.gpr[1];
3044 #elif defined(VGA_s390x)
3045 sp = user_mod.regs.gprs[15];
3047 I_die_here : (sp) architecture missing in vgdb.c
3051 // the magic below is derived from spying what gdb sends to
3052 // the (classical) gdbserver when invoking a C function.
3053 if (shared32 != NULL) {
3054 // vgdb speaking with a 32bit executable.
3055 #if defined(VGA_x86) || defined(VGA_amd64)
3056 const int regsize = 4;
3058 /* push check arg on the stack */
3060 DEBUG(1, "push check arg ptrace_write_memory\n");
3061 assert(regsize == sizeof(check));
3062 rw = ptrace_write_memory(pid, sp,
3063 (unsigned char *) &check,
3066 ERROR(rw, "push check arg ptrace_write_memory");
3067 detach_from_all_threads(pid);
3072 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
3073 // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
3075 rw = ptrace_write_memory(pid, sp,
3076 (unsigned char *) &bad_return,
3079 ERROR(rw, "push bad_return return address ptrace_write_memory");
3080 detach_from_all_threads(pid);
3083 #if defined(VGA_x86)
3084 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
3085 // compiled in 32bits, speaking with a 32bits exe
3086 user_mod.regs.ebp = sp; // bp set to sp
3087 user_mod.regs.esp = sp;
3088 user_mod.regs.eip = shared32->invoke_gdbserver;
3089 user_mod.regs.orig_eax = -1L;
3090 #elif defined(VGA_amd64)
3091 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
3092 // compiled in 64bits, speaking with a 32bits exe
3093 user_mod.regs.rbp = sp; // bp set to sp
3094 user_mod.regs.rsp = sp;
3095 user_mod.regs.rip = shared32->invoke_gdbserver;
3096 user_mod.regs.orig_rax = -1L;
3098 I_die_here : not x86 or amd64 in x86/amd64 section/
3101 #elif defined(VGA_ppc32) || defined(VGA_ppc64)
3102 user_mod.regs.nip = shared32->invoke_gdbserver;
3103 user_mod.regs.trap = -1L;
3104 /* put check arg in register 3 */
3105 user_mod.regs.gpr[3] = check;
3106 /* put NULL return address in Link Register */
3107 user_mod.regs.link = bad_return;
3109 #elif defined(VGA_arm)
3110 /* put check arg in register 0 */
3111 user_mod.regs.uregs[0] = check;
3112 /* put NULL return address in Link Register */
3113 user_mod.regs.uregs[14] = bad_return;
3114 user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
3116 #elif defined(VGA_s390x)
3117 XERROR(0, "(fn32) s390x has no 32bits implementation");
3119 I_die_here : architecture missing in vgdb.c
3123 else if (shared64 != NULL) {
3124 #if defined(VGA_x86)
3125 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3126 #elif defined(VGA_amd64)
3127 // vgdb speaking with a 64 bit executable.
3128 const int regsize = 8;
3131 /* give check arg in rdi */
3132 user_mod.regs.rdi = check;
3134 /* push return address on stack : return to breakaddr */
3136 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
3137 rw = ptrace_write_memory(pid, sp,
3138 (unsigned char *) &bad_return,
3139 sizeof(bad_return));
3141 ERROR(rw, "push bad_return return address ptrace_write_memory");
3142 detach_from_all_threads(pid);
3146 /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
3147 user_mod.regs.rbp = sp; // bp set to sp
3148 user_mod.regs.rsp = sp;
3149 user_mod.regs.rip = shared64->invoke_gdbserver;
3150 user_mod.regs.orig_rax = -1L;
3152 #elif defined(VGA_arm)
3153 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3154 #elif defined(VGA_ppc32)
3155 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3156 #elif defined(VGA_ppc64)
3160 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
3161 (unsigned char *)&func_addr,
3164 ERROR(rw, "ppc64 read func_addr\n");
3165 detach_from_all_threads(pid);
3168 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
3169 (unsigned char *)&toc_addr,
3172 ERROR(rw, "ppc64 read toc_addr\n");
3173 detach_from_all_threads(pid);
3176 // We are not pushing anything on the stack, so it is not
3177 // very clear why the sp has to be decreased, but it seems
3178 // needed. The ppc64 ABI might give some lights on this ?
3179 user_mod.regs.gpr[1] = sp - 220;
3180 user_mod.regs.gpr[2] = toc_addr;
3181 user_mod.regs.nip = func_addr;
3182 user_mod.regs.trap = -1L;
3183 /* put check arg in register 3 */
3184 user_mod.regs.gpr[3] = check;
3185 /* put bad_return return address in Link Register */
3186 user_mod.regs.link = bad_return;
3187 #elif defined(VGA_s390x)
3188 /* put check arg in register r2 */
3189 user_mod.regs.gprs[2] = check;
3190 /* bad_return Return address is in r14 */
3191 user_mod.regs.gprs[14] = bad_return;
3192 /* minimum stack frame */
3194 user_mod.regs.gprs[15] = sp;
3195 /* set program counter */
3196 user_mod.regs.psw.addr = shared64->invoke_gdbserver;
3198 I_die_here: architecture missing in vgdb.c
3205 if (!setregs(pid, &user_mod.regs)) {
3206 detach_from_all_threads(pid);
3209 /* Now that we have modified the registers, we set
3210 pid_of_save_regs to indicate that restore_and_detach
3211 must restore the registers in case of cleanup. */
3212 pid_of_save_regs = pid;
3213 pid_of_save_regs_continued = False;
3216 /* We PTRACE_CONT-inue pid.
3217 Either gdbserver will be invoked directly (if all
3218 threads are interruptible) or gdbserver will be
3219 called soon by the scheduler. In the first case,
3220 pid will stop on the break inserted above when
3221 gdbserver returns. In the 2nd case, the break will
3222 be encountered directly. */
3223 DEBUG(1, "PTRACE_CONT to invoke\n");
3224 res = ptrace (PTRACE_CONT, pid, NULL, NULL);
3226 ERROR(errno, "PTRACE_CONT\n");
3227 restore_and_detach(pid);
3230 pid_of_save_regs_continued = True;
3232 stopped = waitstopped (pid, SIGTRAP,
3233 "waitpid status after PTRACE_CONT to invoke");
3235 /* Here pid has properly stopped on the break. */
3236 pid_of_save_regs_continued = False;
3237 restore_and_detach(pid);
3240 /* Whatever kind of problem happened. We shutdown */
3241 shutting_down = True;
3248 void cleanup_restore_and_detach(void *v_pid)
3250 DEBUG(1, "cleanup_restore_and_detach dying: %d\n", dying);
3251 #ifdef PTRACEINVOKER
3253 restore_and_detach(*(int*)v_pid);
3257 /* This function loops till shutting_down becomes true. In this loop,
3258 it verifies if valgrind process is reading the characters written
3259 by vgdb. The verification is done every max_invoke_ms ms. If
3260 valgrind is not reading characters, it will use invoke_gdbserver
3261 (if PTRACE_INVOKER is defined) to ensure that the gdbserver code is
3262 called soon by valgrind. */
3263 static int max_invoke_ms = 100;
3265 void *invoke_gdbserver_in_valgrind(void *v_pid)
3267 int pid = *(int *)v_pid;
3268 int written_by_vgdb_before_sleep;
3269 int seen_by_valgrind_before_sleep;
3271 int invoked_written = -1;
3273 pthread_cleanup_push(cleanup_restore_and_detach, v_pid);
3275 while (!shutting_down) {
3276 written_by_vgdb_before_sleep = VS_written_by_vgdb;
3277 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
3279 "written_by_vgdb_before_sleep %d "
3280 "seen_by_valgrind_before_sleep %d\n",
3281 written_by_vgdb_before_sleep,
3282 seen_by_valgrind_before_sleep);
3283 if (usleep(1000 * max_invoke_ms) != 0) {
3286 XERROR (errno, "error usleep\n");
3288 /* if nothing happened during our sleep, let's try to wake up valgrind */
3289 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
3290 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
3291 && VS_written_by_vgdb > VS_seen_by_valgrind) {
3294 "written_by_vgdb %d "
3295 "seen_by_valgrind %d "
3296 "invoked_written %d\n",
3298 VS_seen_by_valgrind,
3300 /* if the pid does not exist anymore, we better stop */
3301 if (kill(pid, 0) != 0)
3303 "invoke_gdbserver_in_valgrind: "
3304 "check for pid %d existence failed\n", pid);
3306 #if defined(PTRACEINVOKER)
3307 /* only need to wake up if the nr written has changed since
3309 if (invoked_written != written_by_vgdb_before_sleep) {
3310 if (invoke_gdbserver(pid)) {
3311 /* If invoke succesful, no need to invoke again
3312 for the same value of written_by_vgdb_before_sleep. */
3313 invoked_written = written_by_vgdb_before_sleep;
3317 DEBUG(2, "invoke_gdbserver via ptrace not (yet) implemented\n");
3321 pthread_cleanup_pop(0);
3326 int open_fifo (char* name, int flags, char* desc)
3329 DEBUG(1, "opening %s %s\n", name, desc);
3330 fd = open(name, flags);
3332 XERROR (errno, "error opening %s %s\n", name, desc);
3334 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
3338 /* acquire a lock on the first byte of the given fd. If not successful,
3340 This allows to avoid having two vgdb speaking with the same Valgrind
3341 gdbserver as this causes serious headaches to the protocol. */
3343 void acquire_lock (int fd, int valgrind_pid)
3345 if (lockf(fd, F_TLOCK, 1) < 0) {
3346 if (errno == EAGAIN || errno == EACCES) {
3348 "Cannot acquire lock.\n"
3349 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
3353 XERROR(errno, "cannot acquire lock.\n");
3357 /* Here, we have the lock. It will be released when fd will be closed. */
3358 /* We indicate our pid to Valgrind gdbserver */
3359 if (shared32 != NULL)
3360 shared32->vgdb_pid = getpid();
3361 else if (shared64 != NULL)
3362 shared64->vgdb_pid = getpid();
3367 #define PBUFSIZ 16384 /* keep in sync with server.h */
3369 /* read some characters from fd.
3370 Returns the nr of characters read, -1 if error.
3371 desc is a string used in tracing */
3373 int read_buf (int fd, char* buf, char* desc)
3376 DEBUG(2, "reading %s\n", desc);
3377 nrread = read(fd, buf, PBUFSIZ);
3379 ERROR (errno, "error reading %s\n", desc);
3383 DEBUG(2, "read %s %s\n", desc, buf);
3387 /* write size bytes from buf to fd.
3388 desc is a description of the action for which the write is done.
3389 If notify, then add size to the shared cntr indicating to the
3390 valgrind process that there is new data.
3391 Returns True if write is ok, False if there was a problem. */
3393 Bool write_buf(int fd, char* buf, int size, char* desc, Bool notify)
3397 DEBUG(2, "writing %s len %d %s notify: %d\n", desc, size, buf, notify);
3399 while (nrwritten < size) {
3400 nrw = write (fd, buf+nrwritten, size - nrwritten);
3402 ERROR(errno, "error write %s\n", desc);
3405 nrwritten = nrwritten + nrw;
3416 TO_PID } ConnectionKind;
3417 static const int NumConnectionKind = TO_PID+1;
3419 char *ppConnectionKind (ConnectionKind con)
3422 case FROM_GDB: return "FROM_GDB";
3423 case TO_GDB: return "TO_GDB";
3424 case FROM_PID: return "FROM_PID";
3425 case TO_PID: return "TO_PID";
3426 default: return "invalid connection kind";
3430 static char *shared_mem;
3432 static const int from_gdb = 0;
3433 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
3434 /* Returns True in case read/write operations were done properly.
3435 Returns False in case of error.
3436 to_pid is the file descriptor to write to the process pid. */
3438 Bool read_from_gdb_write_to_pid(int to_pid)
3443 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
3446 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
3448 DEBUG(1, "error reading bytes from gdb\n");
3450 shutting_down = True;
3453 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
3456 static const int to_gdb = 1;
3457 static char *to_gdb_from_pid; /* fifo name to read pid replies */
3458 /* Returns True in case read/write operations were done properly.
3459 Returns False in case of error.
3460 from_pid is the file descriptor to read data from the process pid. */
3462 Bool read_from_pid_write_to_gdb(int from_pid)
3467 nrread = read_buf(from_pid, buf, "from pid");
3470 DEBUG(1, "read 0 bytes from pid => assume exit\n");
3472 DEBUG(1, "error reading bytes from pid\n");
3474 shutting_down = True;
3477 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
3480 /* prepares the FIFOs filenames, map the shared memory. */
3482 void prepare_fifos_and_shared_mem(int pid)
3484 from_gdb_to_pid = vmalloc (strlen(vgdb_prefix) + 30);
3485 to_gdb_from_pid = vmalloc (strlen(vgdb_prefix) + 30);
3486 shared_mem = vmalloc (strlen(vgdb_prefix) + 30);
3487 /* below 3 lines must match the equivalent in remote-utils.c */
3488 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d", vgdb_prefix, pid);
3489 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d", vgdb_prefix, pid);
3490 sprintf(shared_mem, "%s-shared-mem-vgdb-%d", vgdb_prefix, pid);
3491 DEBUG (1, "vgdb: using %s %s %s\n",
3492 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
3494 map_vgdbshared(shared_mem);
3497 /* Convert hex digit A to a number. */
3502 if (a >= '0' && a <= '9')
3504 else if (a >= 'a' && a <= 'f')
3505 return a - 'a' + 10;
3507 XERROR(0, "Reply contains invalid hex digit %c\n", a);
3511 /* Returns next char from fd. -1 if error, -2 if EOF.
3512 NB: must always call it with the same fd */
3516 static unsigned char buf[PBUFSIZ];
3517 static int bufcnt = 0;
3518 static unsigned char *bufp;
3523 bufcnt = read (fd, buf, sizeof (buf));
3527 fprintf (stderr, "readchar: Got EOF\n");
3530 ERROR (errno, "readchar\n");
3540 /* Read a packet from fromfd, with error checking,
3541 and store it in BUF.
3542 Returns length of packet, or -1 if error or -2 if EOF.
3543 Writes ack on ackfd */
3546 getpkt (char *buf, int fromfd, int ackfd)
3549 unsigned char csum, c1, c2;
3556 c = readchar (fromfd);
3559 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
3566 c = readchar (fromfd);
3577 repeat = readchar (fromfd);
3579 for (r = 0; r < repeat - 29; r ++)
3588 c1 = fromhex (readchar (fromfd));
3589 c2 = fromhex (readchar (fromfd));
3591 if (csum == (c1 << 4) + c2)
3594 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
3595 (c1 << 4) + c2, csum, buf);
3596 if (write (ackfd, "-", 1) != 1)
3597 ERROR(0, "error when writing - (nack)\n");
3602 DEBUG(2, "getpkt (\"%s\"); [sending ack] \n", buf);
3603 if (write (ackfd, "+", 1) != 1)
3604 ERROR(0, "error when writing + (ack)\n");
3610 static int sigint = 0;
3611 static int sigterm = 0;
3612 static int sigpipe = 0;
3613 static int sighup = 0;
3614 static int sigusr1 = 0;
3615 static int sigalrm = 0;
3616 static int sigusr1_fd = -1;
3617 static pthread_t invoke_gdbserver_in_valgrind_thread;
3620 void received_signal (int signum)
3622 if (signum == SIGINT)
3624 else if (signum == SIGUSR1) {
3626 if (sigusr1_fd >= 0) {
3627 char control_c = '\003';
3628 write_buf(sigusr1_fd, &control_c, 1,
3629 "write \\003 on SIGUSR1", /* notify */ True);
3632 else if (signum == SIGTERM) {
3633 shutting_down = True;
3635 } else if (signum == SIGHUP) {
3636 shutting_down = True;
3638 } else if (signum == SIGPIPE) {
3640 } else if (signum == SIGALRM) {
3642 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
3643 /* Note: we cannot directly invoke restore_and_detach : this must
3644 be done by the thread that has attached.
3645 We have in this thread pushed a cleanup handler that will
3646 cleanup what is needed. */
3647 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
3649 ERROR(0, "unexpected signal %d\n", signum);
3653 /* install the signal handlers allowing e.g. vgdb to cleanup in
3654 case of termination. */
3656 void install_handlers(void)
3658 struct sigaction action, oldaction;
3660 action.sa_handler = received_signal;
3661 sigemptyset (&action.sa_mask);
3662 action.sa_flags = 0;
3664 /* SIGINT: when user types C-c in gdb, this sends
3665 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
3666 The later is enough to wakeup the valgrind process. */
3667 if (sigaction (SIGINT, &action, &oldaction) != 0)
3668 XERROR (errno, "vgdb error sigaction SIGINT\n");
3669 /* We might do something more intelligent than just
3670 reporting this SIGINT E.g. behave similarly to the gdb: two
3671 control-C without feedback from the debugged process would
3672 mean to stop debugging it. */
3674 /* SIGUSR1: this is used to facilitate automatic testing. When
3675 vgdb receives this signal, it will simulate the user typing C-c. */
3676 if (sigaction (SIGUSR1, &action, &oldaction) != 0)
3677 XERROR (errno, "vgdb error sigaction SIGUSR1\n");
3680 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
3681 when detaching or similar. A clean shutdown will be done as both
3682 the read and write side will detect an end of file. */
3683 if (sigaction (SIGTERM, &action, &oldaction) != 0)
3684 XERROR (errno, "vgdb error sigaction SIGTERM\n");
3686 /* SIGPIPE: can receive this signal when gdb detaches or kill the
3687 process debugged: gdb will close its pipes to vgdb. vgdb
3688 must resist to this signal to allow a clean shutdown. */
3689 if (sigaction (SIGPIPE, &action, &oldaction) != 0)
3690 XERROR (errno, "vgdb error sigaction SIGPIPE\n");
3692 /* SIGALRM: in case invoke thread is blocked, alarm is used
3694 if (sigaction (SIGALRM, &action, &oldaction) != 0)
3695 XERROR (errno, "vgdb error sigaction SIGALRM\n");
3698 /* close the FIFOs provided connections, terminate the invoker thread. */
3700 void close_connection(int to_pid, int from_pid)
3702 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
3703 sigint, sigterm, sighup, sigpipe);
3704 /* Note that we do not forward sigterm to the valgrind process:
3705 a sigterm signal is (probably) received from gdb if the user wants to
3706 kill the debugged process. The kill instruction has been given to
3707 the valgrind process, which should execute a clean exit. */
3709 /* We first close the connection to pid. The pid will then
3710 terminates its gdbserver work. We keep the from pid
3711 fifo opened till the invoker thread is finished.
3712 This allows the gdbserver to finish sending its last reply. */
3713 if (close(to_pid) != 0)
3714 ERROR(errno, "close to_pid\n");
3716 /* if there is a task that was busy trying to wake up valgrind
3717 process, we wait for it to be terminated otherwise threads
3718 in the valgrind process can stay stopped if vgdb main
3719 exits before the invoke thread had time to detach from
3720 all valgrind threads. */
3721 if (max_invoke_ms > 0) {
3724 /* It is surprisingly complex to properly shutdown or exit the
3725 valgrind process in which gdbserver has been invoked through
3726 ptrace. In the normal case (gdb detaches from the process,
3727 or process is continued), the valgrind process will reach the
3728 breakpoint place. Using ptrace, vgdb will ensure the
3729 previous activity of the process is resumed (e.g. restart a
3730 blocking system call). The special case is when gdb asks the
3731 valgrind process to exit (using either the "kill" command or
3732 "monitor exit"). In such a case, the valgrind process will
3733 call exit. But a ptraced process will be blocked in exit,
3734 waiting for the ptracing process to detach or die. vgdb
3735 cannot detach unconditionally as otherwise, in the normal
3736 case, the valgrind process would die abnormally with SIGTRAP
3737 (as vgdb would not be there to catch it). vgdb can also not
3738 die unconditionally otherwise again, similar problem. So, we
3739 assume that most of the time, we arrive here in the normal
3740 case, and so, the breakpoint has been encountered by the
3741 valgrind process, so the invoker thread will exit and the
3742 join will succeed. For the "kill" case, we cause an alarm
3743 signal to be sent after a few seconds. This means that in the
3744 normal case, the gdbserver code in valgrind process must have
3745 returned the control in less than the alarm nr of seconds,
3746 otherwise, valgrind will die abnormally with SIGTRAP. */
3749 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
3750 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
3754 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
3756 if (close(from_pid) != 0)
3757 ERROR(errno, "close from_pid\n");
3760 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
3761 error is encountered. */
3763 void gdb_relay (int pid)
3765 int from_pid = -1; /* fd to read from pid */
3766 int to_pid = -1; /* fd to write to pid */
3768 int shutdown_loop = 0;
3769 fprintf (stderr, "relaying data between gdb and process %d\n", pid);
3772 if (max_invoke_ms > 0)
3773 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
3774 invoke_gdbserver_in_valgrind, (void *) &pid);
3775 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
3776 acquire_lock (shared_mem_fd, pid);
3778 from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
3779 "read mode from pid");
3781 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
3786 struct pollfd pollfds[NumConnectionKind];
3788 /* watch data written by gdb, watch POLLERR on both gdb fd */
3789 pollfds[FROM_GDB].fd = from_gdb;
3790 pollfds[FROM_GDB].events = POLLIN;
3791 pollfds[FROM_GDB].revents = 0;
3792 pollfds[TO_GDB].fd = to_gdb;
3793 pollfds[TO_GDB].events = 0;
3794 pollfds[TO_GDB].revents = 0;
3796 /* watch data written by pid, watch POLLERR on both pid fd */
3797 pollfds[FROM_PID].fd = from_pid;
3798 pollfds[FROM_PID].events = POLLIN;
3799 pollfds[FROM_PID].revents = 0;
3800 pollfds[TO_PID].fd = to_pid;
3801 pollfds[TO_PID].events = 0;
3802 pollfds[TO_PID].revents = 0;
3808 : -1 /* infinite */));
3809 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
3811 /* check for unexpected error */
3812 if (ret <= 0 && errno != EINTR) {
3813 ERROR (errno, "unexpected poll ret %d\n", ret);
3814 shutting_down = True;
3818 /* check for data to read */
3819 for (ck = 0; ck < NumConnectionKind; ck ++) {
3820 if (pollfds[ck].revents & POLLIN) {
3823 if (!read_from_gdb_write_to_pid(to_pid))
3824 shutting_down = True;
3827 if (!read_from_pid_write_to_gdb(from_pid))
3828 shutting_down = True;
3830 default: XERROR(0, "unexpected POLLIN on %s\n",
3831 ppConnectionKind(ck));
3836 /* check for an fd being in error condition */
3837 for (ck = 0; ck < NumConnectionKind; ck ++) {
3838 if (pollfds[ck].revents & POLLERR) {
3839 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
3840 ppConnectionKind(ck), pollfds[ck].fd);
3842 shutting_down = True;
3844 if (pollfds[ck].revents & POLLHUP) {
3845 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
3846 ppConnectionKind(ck), pollfds[ck].fd);
3848 shutting_down = True;
3850 if (pollfds[ck].revents & POLLNVAL) {
3851 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
3852 ppConnectionKind(ck), pollfds[ck].fd);
3854 shutting_down = True;
3858 if (shutting_down) {
3859 /* we let some time to the final packets to be transferred */
3861 if (shutdown_loop > 3)
3865 close_connection(to_pid, from_pid);
3868 static int packet_len_for_command(char *cmd)
3870 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
3871 return 7+ 2*strlen(cmd) +3 + 1;
3874 /* hyper-minimal protocol implementation that
3875 sends the provided commands (using qRcmd packets)
3876 and read and display their replies. */
3878 void standalone_send_commands(int pid,
3882 int from_pid = -1; /* fd to read from pid */
3883 int to_pid = -1; /* fd to write to pid */
3887 unsigned char hex[3];
3888 unsigned char cksum;
3889 unsigned char *hexcommand;
3890 unsigned char buf[PBUFSIZ];
3895 if (max_invoke_ms > 0)
3896 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
3897 invoke_gdbserver_in_valgrind, (void *) &pid);
3899 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
3900 acquire_lock (shared_mem_fd, pid);
3902 /* first send a C-c \003 to pid, so that it wakes up the process
3903 After that, we can open the fifo from the pid in read mode
3904 We then start to wait for packets (normally first a resume reply)
3905 At that point, we send our command and expect replies */
3907 write_buf(to_pid, buf, 1, "write \\003 to wake up", /* notify */ True);
3908 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
3909 "read cmd result from pid");
3911 for (nc = 0; nc <= last_command; nc++) {
3912 fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
3915 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
3916 hexcommand = vmalloc (packet_len_for_command(commands[nc]));
3918 strcat (hexcommand, "$qRcmd,");
3919 for (i = 0; i < strlen(commands[nc]); i++) {
3920 sprintf(hex, "%02x", commands[nc][i]);
3921 strcat (hexcommand, hex);
3923 /* checksum (but without the $) */
3925 for (hi = 1; hi < strlen(hexcommand); hi++)
3926 cksum+=hexcommand[hi];
3927 strcat(hexcommand, "#");
3928 sprintf(hex, "%02x", cksum);
3929 strcat(hexcommand, hex);
3930 write_buf(to_pid, hexcommand, strlen(hexcommand),
3931 "writing hex command to pid", /* notify */ True);
3933 /* we exit of the below loop explicitely when the command has
3934 been handled or because a signal handler will set
3936 while (!shutting_down) {
3937 buflen = getpkt(buf, from_pid, to_pid);
3939 ERROR (0, "error reading packet\n");
3944 if (strlen(buf) == 0) {
3945 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
3948 if (strcmp(buf, "OK") == 0) {
3949 DEBUG(1, "OK packet rcvd\n");
3952 if (buf[0] == 'E') {
3954 "E NN error packet rcvd: %s (unknown monitor command?)\n",
3958 if (buf[0] == 'W') {
3959 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
3962 if (buf[0] == 'T') {
3963 DEBUG(1, "T resume reply packet received: %s\n", buf);
3967 /* must be here an O packet with hex encoded string reply
3968 => decode and print it */
3969 if (buf[0] != 'O') {
3970 DEBUG(0, "expecting O packet, received: %s\n", buf);
3974 char buf_print[buflen/2 + 1];
3975 for (i = 1; i < buflen; i = i + 2)
3976 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
3977 + fromhex(*(buf+i+1));
3978 buf_print[buflen/2] = 0;
3979 printf("%s", buf_print);
3985 shutting_down = True;
3987 close_connection(to_pid, from_pid);
3990 /* report to user the existence of a vgdb-able valgrind process
3993 void report_pid (int pid)
3995 char cmdline_file[100];
4000 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
4001 fd = open (cmdline_file, O_RDONLY);
4003 DEBUG(1, "error opening cmdline file %s %s\n",
4004 cmdline_file, strerror(errno));
4005 sprintf(cmdline, "(could not obtain process command line)");
4007 sz = read(fd, cmdline, 1000);
4008 for (i = 0; i < sz; i++)
4009 if (cmdline[i] == 0)
4013 fprintf(stderr, "use --pid=%d for %s\n", pid, cmdline);
4017 /* Eventually produces additional usage information documenting the
4018 ptrace restrictions. */
4020 void ptrace_restrictions(void)
4022 # ifdef PR_SET_PTRACER
4023 char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
4025 char ptrace_scope = 'X';
4026 fd = open (ptrace_scope_setting_file, O_RDONLY, 0);
4027 if (fd >= 0 && (read (fd, &ptrace_scope, 1) == 1) && (ptrace_scope != '0')) {
4029 "Note: your kernel restricts ptrace invoker using %s\n"
4030 "vgdb will only be able to attach to a Valgrind process\n"
4031 "blocked in a system call *after* an initial successful attach\n",
4032 ptrace_scope_setting_file);
4033 } else if (ptrace_scope == 'X') {
4034 fprintf(stderr, "Could not determine ptrace scope from %s\n",
4035 ptrace_scope_setting_file);
4041 # ifndef PTRACEINVOKER
4043 "Note: ptrace invoker not implemented\n"
4044 "For more info: read user manual section"
4045 " 'Limitations of the Valgrind gdbserver'\n");
4053 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
4054 "vgdb (valgrind gdb) has two usages\n"
4055 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
4056 " The OPTION(s) must be followed by the command to send\n"
4057 " To send more than one command, separate the commands with -c\n"
4058 " 2. relay application between gdb and a Valgrind gdbserver.\n"
4059 " Only OPTION(s) can be given.\n"
4061 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
4062 " [--max-invoke-ms=<number>] [--wait=<number>] [-d] -D]\n"
4063 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
4064 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
4065 " if you want to change the default prefix for the FIFOs communication\n"
4066 " between the Valgrind gdbserver and vgdb.\n"
4067 " --wait arg tells vgdb to check during the specified number\n"
4068 " of seconds if a Valgrind gdbserver can be found.\n"
4069 " --max-invoke-ms gives the nr of milli-seconds after which vgdb will force\n"
4070 " the invocation of the Valgrind gdbserver (if the Valgrind process\n"
4071 " is blocked in a system call).\n"
4072 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
4073 " -D arg tells to show shared mem status and then exit.\n"
4076 ptrace_restrictions();
4079 /* If arg_pid == -1, waits maximum check_trials seconds to discover
4080 a valgrind pid appearing.
4081 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
4082 with gdbserver activated.
4084 Returns the pid to work with
4085 or exits in case of error (e.g. no pid found corresponding to arg_pid */
4088 int search_arg_pid(int arg_pid, int check_trials)
4093 if (arg_pid == 0 || arg_pid < -1) {
4094 fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
4097 /* search for a matching named fifo.
4098 If we have been given a pid, we will check that the matching FIFO is
4099 there (or wait the nr of check_trials for this to appear).
4100 If no pid has been given, then if we find only one FIFO,
4101 we will use this to build the pid to use.
4102 If we find multiple processes with valid FIFO, we report them and will
4103 exit with an error. */
4105 char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
4108 int nr_valid_pid = 0;
4109 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
4110 char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
4112 strcpy (vgdb_format, vgdb_prefix);
4113 strcat (vgdb_format, suffix);
4115 strcpy (vgdb_dir_name, vgdb_prefix);
4117 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
4118 if (vgdb_dir_name[is] == '/') {
4119 vgdb_dir_name[is+1] = '\0';
4122 if (strlen(vgdb_dir_name) == 0)
4123 strcpy (vgdb_dir_name, "./");
4125 DEBUG(1, "searching pid in directory %s format %s\n",
4126 vgdb_dir_name, vgdb_format);
4128 /* try to find FIFOs with valid pid.
4129 On exit of the loop, pid is set to:
4130 -1 if no FIFOs matching a running process is found
4131 -2 if multiple FIFOs of running processes are found
4132 otherwise it is set to the (only) pid found that can be debugged
4134 for (i = 0; i < check_trials; i++) {
4135 DEBUG(1, "check_trial %d \n", i);
4137 /* wait one second before checking again */
4140 vgdb_dir = opendir (vgdb_dir_name);
4141 if (vgdb_dir == NULL)
4143 "vgdb error: opening directory %s searching vgdb fifo\n",
4146 errno = 0; /* avoid complain if vgdb_dir is empty */
4147 while ((f = readdir (vgdb_dir))) {
4149 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name)];
4153 strcpy (pathname, vgdb_dir_name);
4154 strcat (pathname, f->d_name);
4155 DEBUG(3, "trying %s\n", pathname);
4156 if (stat (pathname, &st) != 0) {
4157 if (debuglevel >= 3)
4158 ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n",
4160 } else if (S_ISFIFO (st.st_mode)) {
4161 DEBUG(3, "trying %s\n", pathname);
4162 if (strncmp (pathname, vgdb_format,
4163 strlen (vgdb_format)) == 0) {
4164 newpid = strtol(pathname + strlen (vgdb_format),
4166 if (*wrongpid == '\0' && newpid > 0
4167 && kill (newpid, 0) == 0) {
4169 if (arg_pid != -1) {
4170 if (arg_pid == newpid) {
4173 } else if (nr_valid_pid > 1) {
4174 if (nr_valid_pid == 2) {
4177 "no --pid= arg given"
4178 " and multiple valgrind pids found:\n");
4182 report_pid (newpid);
4189 errno = 0; /* avoid complain if at the end of vgdb_dir */
4191 if (f == NULL && errno != 0)
4192 XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n",
4195 closedir (vgdb_dir);
4200 free (vgdb_dir_name);
4206 fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
4208 fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n",
4212 else if (pid == -2) {
4213 /* no arg_pid given, multiple FIFOs found */
4221 /* return true if the numeric value of an option of the
4222 form --xxxxxxxxx=<number> could properly be extracted
4223 from arg. If True is returned, *value contains the
4226 Bool numeric_val(char* arg, int *value)
4228 const char *eq_pos = strchr(arg, '=');
4234 *value = strtol(eq_pos+1, &wrong, 10);
4241 /* true if arg matches the provided option */
4243 Bool is_opt(char* arg, char *option)
4245 int option_len = strlen(option);
4246 if (option[option_len-1] == '=')
4247 return (0 == strncmp(option, arg, option_len));
4249 return (0 == strcmp(option, arg));
4252 /* Parse command lines options. If error(s), exits.
4253 Otherwise returns the options in *p_... args.
4254 commands must be big enough for the commands extracted from argv.
4255 On return, *p_last_command gives the position in commands where
4256 the last command has been allocated (using vmalloc). */
4258 void parse_options(int argc, char** argv,
4259 Bool *p_show_shared_mem,
4261 int *p_check_trials,
4262 int *p_last_command,
4265 Bool show_shared_mem = False;
4267 int check_trials = 1;
4268 int last_command = -1;
4273 for (i = 1; i < argc; i++) {
4274 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
4277 } else if (is_opt(argv[i], "-d")) {
4279 } else if (is_opt(argv[i], "-D")) {
4280 show_shared_mem = True;
4281 } else if (is_opt(argv[i], "--pid=")) {
4283 if (!numeric_val(argv[i], &newpid)) {
4284 fprintf (stderr, "invalid pid argument %s\n", argv[i]);
4286 } else if (arg_pid != -1) {
4287 fprintf (stderr, "multiple pid arguments given\n");
4292 } else if (is_opt(argv[i], "--wait=")) {
4293 if (!numeric_val(argv[i], &check_trials)) {
4294 fprintf (stderr, "invalid wait argument %s\n", argv[i]);
4297 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
4298 if (!numeric_val(argv[i], &max_invoke_ms)) {
4299 fprintf (stderr, "invalid max-invoke-ms argument %s\n", argv[i]);
4302 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
4303 vgdb_prefix = argv[i] + 14;
4304 } else if (is_opt(argv[i], "-c")) {
4306 commands[last_command] = vmalloc (1);
4307 commands[last_command][0] = '\0';
4308 } else if (0 == strncmp(argv[i], "-", 1)) {
4309 fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
4313 if (last_command == -1) {
4314 /* only one command, no -c command indicator */
4316 commands[last_command] = vmalloc (1);
4317 commands[last_command][0] = '\0';
4319 len = strlen(commands[last_command]);
4320 commands[last_command] = vrealloc (commands[last_command],
4321 len + 1 + strlen(argv[i]) + 1);
4323 strcat (commands[last_command], " ");
4324 strcat (commands[last_command], argv[i]);
4325 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
4326 fprintf (stderr, "command %s too long\n", commands[last_command]);
4332 if (arg_errors > 0) {
4333 fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
4337 *p_show_shared_mem = show_shared_mem;
4338 *p_arg_pid = arg_pid;
4339 *p_check_trials = check_trials;
4340 *p_last_command = last_command;
4343 int main(int argc, char** argv)
4348 Bool show_shared_mem;
4352 char *commands[argc]; // we will never have more commands than args.
4354 parse_options(argc, argv,
4361 /* when we are working as a relay for gdb, handle some signals by
4362 only reporting them (according to debug level). Also handle these
4363 when ptrace will be used: vgdb must clean up the ptrace effect before
4365 if (max_invoke_ms > 0 || last_command == -1)
4368 pid = search_arg_pid (arg_pid, check_trials);
4370 prepare_fifos_and_shared_mem(pid);
4372 if (show_shared_mem) {
4375 "written_by_vgdb %d "
4376 "seen_by_valgrind %d\n"
4380 VS_seen_by_valgrind,
4385 if (last_command >= 0) {
4386 standalone_send_commands(pid, last_command, commands);
4392 free (from_gdb_to_pid);
4393 free (to_gdb_from_pid);
4396 for (i = 0; i <= last_command; i++)