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-2017 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.
45 #include <netinet/in.h>
47 #include <sys/socket.h>
51 /* vgdb has two usages:
52 1. relay application between gdb and the gdbserver embedded in valgrind.
53 2. standalone to send monitor commands to a running valgrind-ified process
55 It is made of a main program which reads arguments. If no
56 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
59 As relay application, vgdb reads bytes from gdb on stdin and
60 writes these bytes to valgrind. Bytes read from valgrind are
61 written to gdb on stdout. Read/Write from/to valgrind is done
62 using FIFOs. There is one thread reading from stdin, writing to
63 valgrind on a FIFO. There is one thread reading from valgrind on a
64 FIFO, writing to gdb on stdout
66 As a standalone utility, vgdb builds command packets to write to valgrind,
67 sends it and reads the reply. The same two threads are used to write/read.
68 Once all the commands are sent and their replies received, vgdb will exit.
73 static char *vgdb_prefix
= NULL
;
75 /* Will be set to True when any condition indicating we have to shutdown
77 Bool shutting_down
= False
;
79 VgdbShared32
*shared32
;
80 VgdbShared64
*shared64
;
81 #define VS_written_by_vgdb (shared32 != NULL ? \
82 shared32->written_by_vgdb \
83 : shared64->written_by_vgdb)
84 #define VS_seen_by_valgrind (shared32 != NULL ? \
85 shared32->seen_by_valgrind \
86 : shared64->seen_by_valgrind)
88 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
90 void *vmalloc(size_t size
)
92 void * mem
= malloc(size
);
94 XERROR (errno
, "can't allocate memory\n");
98 void *vrealloc(void *ptr
,size_t size
)
100 void * mem
= realloc(ptr
, size
);
102 XERROR (errno
, "can't reallocate memory\n");
106 /* Return the name of a directory for temporary files. */
108 const char *vgdb_tmpdir(void)
112 tmpdir
= getenv("TMPDIR");
113 if (tmpdir
== NULL
|| *tmpdir
== '\0')
115 if (tmpdir
== NULL
|| *tmpdir
== '\0')
116 tmpdir
= "/tmp"; /* fallback */
121 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
122 to communicate with valgrind */
124 char *vgdb_prefix_default(void)
126 static HChar
*prefix
;
128 if (prefix
== NULL
) {
129 const char *tmpdir
= vgdb_tmpdir();
130 prefix
= vmalloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
131 strcpy(prefix
, tmpdir
);
132 strcat(prefix
, "/vgdb-pipe");
137 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
139 void add_written(int nrw
)
141 if (shared32
!= NULL
)
142 shared32
->written_by_vgdb
+= nrw
;
143 else if (shared64
!= NULL
)
144 shared64
->written_by_vgdb
+= nrw
;
149 static int shared_mem_fd
= -1;
151 void map_vgdbshared (char* shared_mem
)
155 shared_mem_fd
= open(shared_mem
, O_RDWR
);
156 /* shared_mem_fd will not be closed till vgdb exits. */
158 if (shared_mem_fd
== -1)
159 XERROR (errno
, "error opening %s shared memory file\n", shared_mem
);
161 if (fstat(shared_mem_fd
, &fdstat
) != 0)
162 XERROR (errno
, "fstat");
164 if (fdstat
.st_size
== sizeof(VgdbShared64
))
165 s
= (void*) &shared64
;
166 else if (fdstat
.st_size
== sizeof(VgdbShared32
))
167 s
= (void*) &shared32
;
169 #if VEX_HOST_WORDSIZE == 8
171 "error size shared memory file %s.\n"
172 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
174 (int) sizeof(VgdbShared64
), (int) sizeof(VgdbShared32
),
175 (long int)fdstat
.st_size
);
176 #elif VEX_HOST_WORDSIZE == 4
178 "error size shared memory file %s.\n"
179 "expecting size %d (32bits) got %ld.\n",
181 (int) sizeof(VgdbShared32
),
184 # error "unexpected wordsize"
187 #if VEX_HOST_WORDSIZE == 4
188 if (shared64
!= NULL
)
189 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
190 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
193 *s
= (void*) mmap (NULL
, fdstat
.st_size
,
194 PROT_READ
|PROT_WRITE
, MAP_SHARED
,
197 if (*s
== (void *) -1)
198 XERROR (errno
, "error mmap shared memory file %s\n", shared_mem
);
202 /* This function loops till shutting_down becomes true. In this loop,
203 it verifies if valgrind process is reading the characters written
204 by vgdb. The verification is done every max_invoke_ms ms. If
205 valgrind is not reading characters, it will use invoker_invoke_gdbserver
206 to ensure that the gdbserver code is called soon by valgrind. */
207 static int max_invoke_ms
= 100;
208 #define NEVER 99999999
209 static int cmd_time_out
= NEVER
;
211 void *invoke_gdbserver_in_valgrind(void *v_pid
)
213 struct timeval cmd_max_end_time
;
214 Bool cmd_started
= False
;
215 struct timeval invoke_time
;
217 int pid
= *(int *)v_pid
;
218 int written_by_vgdb_before_sleep
;
219 int seen_by_valgrind_before_sleep
;
221 int invoked_written
= -1;
224 pthread_cleanup_push(invoker_cleanup_restore_and_detach
, v_pid
);
226 while (!shutting_down
) {
227 written_by_vgdb_before_sleep
= VS_written_by_vgdb
;
228 seen_by_valgrind_before_sleep
= VS_seen_by_valgrind
;
230 "written_by_vgdb_before_sleep %d "
231 "seen_by_valgrind_before_sleep %d\n",
232 written_by_vgdb_before_sleep
,
233 seen_by_valgrind_before_sleep
);
234 if (cmd_time_out
!= NEVER
236 && written_by_vgdb_before_sleep
> seen_by_valgrind_before_sleep
) {
237 /* A command was started. Record the time at which it was started. */
238 DEBUG(1, "IO for command started\n");
239 gettimeofday(&cmd_max_end_time
, NULL
);
240 cmd_max_end_time
.tv_sec
+= cmd_time_out
;
243 if (max_invoke_ms
> 0) {
244 usecs
= 1000 * max_invoke_ms
;
245 gettimeofday(&invoke_time
, NULL
);
246 invoke_time
.tv_sec
+= max_invoke_ms
/ 1000;
247 invoke_time
.tv_usec
+= 1000 * (max_invoke_ms
% 1000);
248 invoke_time
.tv_sec
+= invoke_time
.tv_usec
/ (1000 * 1000);
249 invoke_time
.tv_usec
= invoke_time
.tv_usec
% (1000 * 1000);
254 // 0 usecs here means the thread just has to check gdbserver eats
255 // the characters in <= cmd_time_out seconds.
256 // We will just wait by 1 second max at a time.
257 if (usecs
== 0 || usecs
> 1000 * 1000)
262 /* If nothing happened during our sleep, let's try to wake up valgrind
263 or check for cmd time out. */
264 if (written_by_vgdb_before_sleep
== VS_written_by_vgdb
265 && seen_by_valgrind_before_sleep
== VS_seen_by_valgrind
266 && VS_written_by_vgdb
> VS_seen_by_valgrind
) {
268 gettimeofday(&now
, NULL
);
271 "written_by_vgdb %d "
272 "seen_by_valgrind %d "
273 "invoked_written %d\n",
277 /* if the pid does not exist anymore, we better stop */
278 if (kill(pid
, 0) != 0)
280 "invoke_gdbserver_in_valgrind: "
281 "check for pid %d existence failed\n", pid
);
283 if (timercmp (&now
, &cmd_max_end_time
, >))
285 "pid %d did not handle a command in %d seconds\n",
288 if (max_invoke_ms
> 0 && timercmp (&now
, &invoke_time
, >=)) {
289 /* only need to wake up if the nr written has changed since
291 if (invoked_written
!= written_by_vgdb_before_sleep
) {
292 if (invoker_invoke_gdbserver(pid
)) {
293 /* If invoke successful, no need to invoke again
294 for the same value of written_by_vgdb_before_sleep. */
295 invoked_written
= written_by_vgdb_before_sleep
;
300 // Something happened => restart timer check.
301 if (cmd_time_out
!= NEVER
) {
302 DEBUG(2, "some IO was done => restart command\n");
307 pthread_cleanup_pop(0);
312 int open_fifo (const char* name
, int flags
, const char* desc
)
315 DEBUG(1, "opening %s %s\n", name
, desc
);
316 fd
= open(name
, flags
);
318 XERROR (errno
, "error opening %s %s\n", name
, desc
);
320 DEBUG(1, "opened %s %s fd %d\n", name
, desc
, fd
);
324 /* acquire a lock on the first byte of the given fd. If not successful,
326 This allows to avoid having two vgdb speaking with the same Valgrind
327 gdbserver as this causes serious headaches to the protocol. */
329 void acquire_lock (int fd
, int valgrind_pid
)
333 fl
.l_whence
= SEEK_SET
;
336 if (fcntl(fd
, F_SETLK
, &fl
) < 0) {
337 if (errno
== EAGAIN
|| errno
== EACCES
) {
339 "Cannot acquire lock.\n"
340 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
344 XERROR(errno
, "cannot acquire lock.\n");
348 /* Here, we have the lock. It will be released when fd will be closed. */
349 /* We indicate our pid to Valgrind gdbserver */
350 if (shared32
!= NULL
)
351 shared32
->vgdb_pid
= getpid();
352 else if (shared64
!= NULL
)
353 shared64
->vgdb_pid
= getpid();
358 #define PBUFSIZ 16384 /* keep in sync with server.h */
360 /* read some characters from fd.
361 Returns the nr of characters read, -1 if error.
362 desc is a string used in tracing */
364 int read_buf (int fd
, char* buf
, const char* desc
)
367 DEBUG(2, "reading %s\n", desc
);
368 nrread
= read(fd
, buf
, PBUFSIZ
);
370 ERROR (errno
, "error reading %s\n", desc
);
374 DEBUG(2, "read %s %s\n", desc
, buf
);
378 /* write size bytes from buf to fd.
379 desc is a description of the action for which the write is done.
380 If notify, then add size to the shared cntr indicating to the
381 valgrind process that there is new data.
382 Returns True if write is ok, False if there was a problem. */
384 Bool
write_buf(int fd
, const char* buf
, int size
, const char* desc
, Bool notify
)
388 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc
, size
,
391 while (nrwritten
< size
) {
392 nrw
= write (fd
, buf
+nrwritten
, size
- nrwritten
);
394 ERROR(errno
, "error write %s\n", desc
);
397 nrwritten
= nrwritten
+ nrw
;
408 TO_PID
} ConnectionKind
;
409 static const int NumConnectionKind
= TO_PID
+1;
411 const char *ppConnectionKind (ConnectionKind con
)
414 case FROM_GDB
: return "FROM_GDB";
415 case TO_GDB
: return "TO_GDB";
416 case FROM_PID
: return "FROM_PID";
417 case TO_PID
: return "TO_PID";
418 default: return "invalid connection kind";
422 static char *shared_mem
;
424 static int from_gdb
= 0; /* stdin by default, changed if --port is given. */
425 static char *from_gdb_to_pid
; /* fifo name to write gdb command to pid */
426 /* Returns True in case read/write operations were done properly.
427 Returns False in case of error.
428 to_pid is the file descriptor to write to the process pid. */
430 Bool
read_from_gdb_write_to_pid(int to_pid
)
432 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
435 nrread
= read_buf(from_gdb
, buf
, "from gdb on stdin");
438 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
440 DEBUG(1, "error reading bytes from gdb\n");
442 shutting_down
= True
;
445 return write_buf(to_pid
, buf
, nrread
, "to_pid", /* notify */ True
);
448 static int to_gdb
= 1; /* stdout by default, changed if --port is given. */
449 static char *to_gdb_from_pid
; /* fifo name to read pid replies */
450 /* Returns True in case read/write operations were done properly.
451 Returns False in case of error.
452 from_pid is the file descriptor to read data from the process pid. */
454 Bool
read_from_pid_write_to_gdb(int from_pid
)
456 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
459 nrread
= read_buf(from_pid
, buf
, "from pid");
462 DEBUG(1, "read 0 bytes from pid => assume exit\n");
464 DEBUG(1, "error reading bytes from pid\n");
466 shutting_down
= True
;
469 return write_buf(to_gdb
, buf
, nrread
, "to_gdb", /* notify */ False
);
473 void wait_for_gdb_connect (int in_port
)
475 struct sockaddr_in addr
;
477 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
480 if (-1 == listen_gdb
) {
481 XERROR(errno
, "cannot create socket");
484 memset(&addr
, 0, sizeof(addr
));
486 addr
.sin_family
= AF_INET
;
487 addr
.sin_port
= htons((unsigned short int)in_port
);
488 addr
.sin_addr
.s_addr
= INADDR_ANY
;
490 if (-1 == bind(listen_gdb
,(struct sockaddr
*)&addr
, sizeof(addr
))) {
491 XERROR(errno
, "bind failed");
493 fprintf(stderr
, "listening on port %d ...", in_port
);
495 if (-1 == listen(listen_gdb
, 1)) {
496 XERROR(errno
, "error listen failed");
499 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
500 if (gdb_connect
< 0) {
501 XERROR(errno
, "accept failed");
503 fprintf(stderr
, "connected.\n");
506 from_gdb
= gdb_connect
;
507 to_gdb
= gdb_connect
;
510 /* prepares the FIFOs filenames, map the shared memory. */
512 void prepare_fifos_and_shared_mem(int pid
)
514 const HChar
*user
, *host
;
517 user
= getenv("LOGNAME");
518 if (user
== NULL
) user
= getenv("USER");
519 if (user
== NULL
) user
= "???";
520 if (strchr(user
, '/')) user
= "???";
522 host
= getenv("HOST");
523 if (host
== NULL
) host
= getenv("HOSTNAME");
524 if (host
== NULL
) host
= "???";
525 if (strchr(host
, '/')) host
= "???";
527 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
528 from_gdb_to_pid
= vmalloc (len
);
529 to_gdb_from_pid
= vmalloc (len
);
530 shared_mem
= vmalloc (len
);
531 /* below 3 lines must match the equivalent in remote-utils.c */
532 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
534 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
536 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
538 DEBUG (1, "vgdb: using %s %s %s\n",
539 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
541 map_vgdbshared(shared_mem
);
544 /* Convert hex digit A to a number. */
549 if (a
>= '0' && a
<= '9')
551 else if (a
>= 'a' && a
<= 'f')
554 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
558 /* Returns next char from fd. -1 if error, -2 if EOF.
559 NB: must always call it with the same fd */
563 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
564 static int bufcnt
= 0;
565 static unsigned char *bufp
;
566 // unsigned bufp to e.g. avoid having 255 converted to int -1
571 bufcnt
= read_buf (fd
, buf
, "static buf readchar");
575 fprintf (stderr
, "readchar: Got EOF\n");
578 ERROR (errno
, "readchar\n");
583 bufp
= (unsigned char *)buf
;
588 /* Read a packet from fromfd, with error checking,
590 If checksum incorrect, writes a - on ackfd.
591 Returns length of packet, or -1 if error or -2 if EOF. */
593 getpkt (char *buf
, int fromfd
, int ackfd
)
596 unsigned char csum
, c1
, c2
;
603 c
= readchar (fromfd
);
606 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
613 c
= readchar (fromfd
);
624 repeat
= readchar (fromfd
);
626 for (r
= 0; r
< repeat
- 29; r
++)
635 c1
= fromhex (readchar (fromfd
));
636 c2
= fromhex (readchar (fromfd
));
638 if (csum
== (c1
<< 4) + c2
)
641 fprintf (stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
642 (c1
<< 4) + c2
, csum
, buf
);
643 if (write (ackfd
, "-", 1) != 1)
644 ERROR(0, "error when writing - (nack)\n");
649 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
653 static int sigint
= 0;
654 static int sigterm
= 0;
655 static int sigpipe
= 0;
656 static int sighup
= 0;
657 static int sigusr1
= 0;
658 static int sigalrm
= 0;
659 static int sigusr1_fd
= -1;
660 static pthread_t invoke_gdbserver_in_valgrind_thread
;
663 void received_signal (int signum
)
665 if (signum
== SIGINT
)
667 else if (signum
== SIGUSR1
) {
669 if (sigusr1_fd
>= 0) {
670 char control_c
= '\003';
671 write_buf(sigusr1_fd
, &control_c
, 1,
672 "write \\003 on SIGUSR1", /* notify */ True
);
675 else if (signum
== SIGTERM
) {
676 shutting_down
= True
;
678 } else if (signum
== SIGHUP
) {
679 shutting_down
= True
;
681 } else if (signum
== SIGPIPE
) {
683 } else if (signum
== SIGALRM
) {
685 #if defined(VGPV_arm_linux_android) \
686 || defined(VGPV_x86_linux_android) \
687 || defined(VGPV_mips32_linux_android) \
688 || defined(VGPV_arm64_linux_android)
689 /* Android has no pthread_cancel. As it also does not have
690 an invoker implementation, there is no need for cleanup action.
691 So, we just do nothing. */
692 DEBUG(1, "sigalrm received, no action on android\n");
694 /* Note: we cannot directly invoke restore_and_detach : this must
695 be done by the thread that has attached.
696 We have in this thread pushed a cleanup handler that will
697 cleanup what is needed. */
698 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
699 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
702 ERROR(0, "unexpected signal %d\n", signum
);
706 /* install the signal handlers allowing e.g. vgdb to cleanup in
707 case of termination. */
709 void install_handlers(void)
711 struct sigaction action
, oldaction
;
713 action
.sa_handler
= received_signal
;
714 sigemptyset (&action
.sa_mask
);
717 /* SIGINT: when user types C-c in gdb, this sends
718 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
719 The later is enough to wakeup the valgrind process. */
720 if (sigaction (SIGINT
, &action
, &oldaction
) != 0)
721 XERROR (errno
, "vgdb error sigaction SIGINT\n");
722 /* We might do something more intelligent than just
723 reporting this SIGINT E.g. behave similarly to the gdb: two
724 control-C without feedback from the debugged process would
725 mean to stop debugging it. */
727 /* SIGUSR1: this is used to facilitate automatic testing. When
728 vgdb receives this signal, it will simulate the user typing C-c. */
729 if (sigaction (SIGUSR1
, &action
, &oldaction
) != 0)
730 XERROR (errno
, "vgdb error sigaction SIGUSR1\n");
733 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
734 when detaching or similar. A clean shutdown will be done as both
735 the read and write side will detect an end of file. */
736 if (sigaction (SIGTERM
, &action
, &oldaction
) != 0)
737 XERROR (errno
, "vgdb error sigaction SIGTERM\n");
739 /* SIGPIPE: can receive this signal when gdb detaches or kill the
740 process debugged: gdb will close its pipes to vgdb. vgdb
741 must resist to this signal to allow a clean shutdown. */
742 if (sigaction (SIGPIPE
, &action
, &oldaction
) != 0)
743 XERROR (errno
, "vgdb error sigaction SIGPIPE\n");
745 /* SIGALRM: in case invoke thread is blocked, alarm is used
747 if (sigaction (SIGALRM
, &action
, &oldaction
) != 0)
748 XERROR (errno
, "vgdb error sigaction SIGALRM\n");
750 /* unmask all signals, in case the process that launched vgdb
752 if (sigprocmask (SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
753 XERROR (errno
, "vgdb error sigprocmask");
756 /* close the FIFOs provided connections, terminate the invoker thread. */
758 void close_connection(int to_pid
, int from_pid
)
760 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
761 sigint
, sigterm
, sighup
, sigpipe
);
762 /* Note that we do not forward sigterm to the valgrind process:
763 a sigterm signal is (probably) received from gdb if the user wants to
764 kill the debugged process. The kill instruction has been given to
765 the valgrind process, which should execute a clean exit. */
767 /* We first close the connection to pid. The pid will then
768 terminates its gdbserver work. We keep the from pid
769 fifo opened till the invoker thread is finished.
770 This allows the gdbserver to finish sending its last reply. */
771 if (close(to_pid
) != 0)
772 ERROR(errno
, "close to_pid\n");
774 /* if there is a task that was busy trying to wake up valgrind
775 process, we wait for it to be terminated otherwise threads
776 in the valgrind process can stay stopped if vgdb main
777 exits before the invoke thread had time to detach from
778 all valgrind threads. */
779 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
782 /* It is surprisingly complex to properly shutdown or exit the
783 valgrind process in which gdbserver has been invoked through
784 ptrace. In the normal case (gdb detaches from the process,
785 or process is continued), the valgrind process will reach the
786 breakpoint place. Using ptrace, vgdb will ensure the
787 previous activity of the process is resumed (e.g. restart a
788 blocking system call). The special case is when gdb asks the
789 valgrind process to exit (using either the "kill" command or
790 "monitor exit"). In such a case, the valgrind process will
791 call exit. But a ptraced process will be blocked in exit,
792 waiting for the ptracing process to detach or die. vgdb
793 cannot detach unconditionally as otherwise, in the normal
794 case, the valgrind process would stop abnormally with SIGSTOP
795 (as vgdb would not be there to catch it). vgdb can also not
796 die unconditionally otherwise again, similar problem. So, we
797 assume that most of the time, we arrive here in the normal
798 case, and so, the breakpoint has been encountered by the
799 valgrind process, so the invoker thread will exit and the
800 join will succeed. For the "kill" case, we cause an alarm
801 signal to be sent after a few seconds. This means that in the
802 normal case, the gdbserver code in valgrind process must have
803 returned the control in less than the alarm nr of seconds,
804 otherwise, valgrind will stop abnormally with SIGSTOP. */
807 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
808 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
812 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
814 if (close(from_pid
) != 0)
815 ERROR(errno
, "close from_pid\n");
818 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
819 error is encountered. */
821 void gdb_relay (int pid
)
823 int from_pid
= -1; /* fd to read from pid */
824 int to_pid
= -1; /* fd to write to pid */
826 int shutdown_loop
= 0;
827 fprintf (stderr
, "relaying data between gdb and process %d\n", pid
);
830 if (max_invoke_ms
> 0)
831 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
832 invoke_gdbserver_in_valgrind
, (void *) &pid
);
833 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
834 acquire_lock (shared_mem_fd
, pid
);
836 from_pid
= open_fifo (to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
837 "read mode from pid");
839 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
844 struct pollfd pollfds
[NumConnectionKind
];
846 /* watch data written by gdb, watch POLLERR on both gdb fd */
847 pollfds
[FROM_GDB
].fd
= from_gdb
;
848 pollfds
[FROM_GDB
].events
= POLLIN
;
849 pollfds
[FROM_GDB
].revents
= 0;
850 pollfds
[TO_GDB
].fd
= to_gdb
;
851 pollfds
[TO_GDB
].events
= 0;
852 pollfds
[TO_GDB
].revents
= 0;
854 /* watch data written by pid, watch POLLERR on both pid fd */
855 pollfds
[FROM_PID
].fd
= from_pid
;
856 pollfds
[FROM_PID
].events
= POLLIN
;
857 pollfds
[FROM_PID
].revents
= 0;
858 pollfds
[TO_PID
].fd
= to_pid
;
859 pollfds
[TO_PID
].events
= 0;
860 pollfds
[TO_PID
].revents
= 0;
866 : -1 /* infinite */));
867 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
869 /* check for unexpected error */
870 if (ret
<= 0 && errno
!= EINTR
) {
871 ERROR (errno
, "unexpected poll ret %d\n", ret
);
872 shutting_down
= True
;
876 /* check for data to read */
877 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
878 if (pollfds
[ck
].revents
& POLLIN
) {
881 if (!read_from_gdb_write_to_pid(to_pid
))
882 shutting_down
= True
;
885 if (!read_from_pid_write_to_gdb(from_pid
))
886 shutting_down
= True
;
888 default: XERROR(0, "unexpected POLLIN on %s\n",
889 ppConnectionKind(ck
));
894 /* check for an fd being in error condition */
895 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
896 if (pollfds
[ck
].revents
& POLLERR
) {
897 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
898 ppConnectionKind(ck
), pollfds
[ck
].fd
);
899 invoker_valgrind_dying();
900 shutting_down
= True
;
902 if (pollfds
[ck
].revents
& POLLHUP
) {
903 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
904 ppConnectionKind(ck
), pollfds
[ck
].fd
);
905 invoker_valgrind_dying();
906 shutting_down
= True
;
908 if (pollfds
[ck
].revents
& POLLNVAL
) {
909 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
910 ppConnectionKind(ck
), pollfds
[ck
].fd
);
911 invoker_valgrind_dying();
912 shutting_down
= True
;
917 /* we let some time to the final packets to be transferred */
919 if (shutdown_loop
> 3)
923 close_connection(to_pid
, from_pid
);
926 static int packet_len_for_command(char *cmd
)
928 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
929 return 7+ 2*strlen(cmd
) +3 + 1;
932 /* hyper-minimal protocol implementation that
933 sends the provided commands (using qRcmd packets)
934 and read and display their replies. */
936 void standalone_send_commands(int pid
,
940 int from_pid
= -1; /* fd to read from pid */
941 int to_pid
= -1; /* fd to write to pid */
948 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
953 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
954 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
955 invoke_gdbserver_in_valgrind
, (void *) &pid
);
957 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
958 acquire_lock (shared_mem_fd
, pid
);
960 /* first send a C-c \003 to pid, so that it wakes up the process
961 After that, we can open the fifo from the pid in read mode
962 We then start to wait for packets (normally first a resume reply)
963 At that point, we send our command and expect replies */
966 while (!write_buf(to_pid
, buf
, 1,
967 "write \\003 to wake up", /* notify */ True
)) {
968 /* If write fails, retries up to 10 times every 0.5 seconds
969 This aims at solving the race condition described in
970 remote-utils.c remote_finish function. */
974 XERROR (errno
, "failed to send wake up char after 10 trials\n");
976 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
977 "read cmd result from pid");
979 /* Enable no ack mode. */
980 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
982 buflen
= getpkt(buf
, from_pid
, to_pid
);
983 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
985 ERROR (0, "no ack mode: unexpected buflen %d\n", buflen
);
987 ERROR (0, "no ack mode: unexpected packet %s\n", buf
);
990 for (nc
= 0; nc
<= last_command
; nc
++) {
991 fprintf (stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
994 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
995 hexcommand
= vmalloc (packet_len_for_command(commands
[nc
]));
997 strcat (hexcommand
, "$qRcmd,");
998 for (i
= 0; i
< strlen(commands
[nc
]); i
++) {
999 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][i
]);
1000 // Need to use unsigned char, to avoid sign extension.
1001 strcat (hexcommand
, hex
);
1003 /* checksum (but without the $) */
1005 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1006 cksum
+=hexcommand
[hi
];
1007 strcat(hexcommand
, "#");
1008 sprintf(hex
, "%02x", cksum
);
1009 strcat(hexcommand
, hex
);
1010 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1011 "writing hex command to pid", /* notify */ True
);
1013 /* we exit of the below loop explicitly when the command has
1014 been handled or because a signal handler will set
1016 while (!shutting_down
) {
1017 buflen
= getpkt(buf
, from_pid
, to_pid
);
1019 ERROR (0, "error reading packet\n");
1021 invoker_valgrind_dying();
1024 if (strlen(buf
) == 0) {
1025 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1028 if (strcmp(buf
, "OK") == 0) {
1029 DEBUG(1, "OK packet rcvd\n");
1032 if (buf
[0] == 'E') {
1034 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1038 if (buf
[0] == 'W') {
1039 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1042 if (buf
[0] == 'T') {
1043 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1047 /* must be here an O packet with hex encoded string reply
1048 => decode and print it */
1049 if (buf
[0] != 'O') {
1050 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1054 char buf_print
[buflen
/2 + 1];
1055 for (i
= 1; i
< buflen
; i
= i
+ 2)
1056 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1057 + fromhex(*(buf
+i
+1));
1058 buf_print
[buflen
/2] = 0;
1059 printf("%s", buf_print
);
1065 shutting_down
= True
;
1067 close_connection(to_pid
, from_pid
);
1070 /* report to user the existence of a vgdb-able valgrind process
1072 Note: this function does not use XERROR if an error is encountered
1073 while producing the command line for pid, as this is not critical
1074 and at least on MacOS, reading cmdline is not available. */
1076 void report_pid (int pid
, Bool on_stdout
)
1078 char cmdline_file
[50]; // large enough
1080 FILE *out
= on_stdout
? stdout
: stderr
;
1082 fprintf(out
, "use --pid=%d for ", pid
);
1084 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
1085 fd
= open (cmdline_file
, O_RDONLY
);
1087 DEBUG(1, "error opening cmdline file %s %s\n",
1088 cmdline_file
, strerror(errno
));
1089 fprintf(out
, "(could not open process command line)\n");
1093 while ((sz
= read(fd
, cmdline
, sizeof cmdline
- 1)) != 0) {
1094 for (i
= 0; i
< sz
; i
++)
1095 if (cmdline
[i
] == 0)
1098 fprintf(out
, "%s", cmdline
);
1101 DEBUG(1, "error reading cmdline file %s %s\n",
1102 cmdline_file
, strerror(errno
));
1103 fprintf(out
, "(error reading process command line)");
1115 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1116 "vgdb (valgrind gdb) has two usages\n"
1117 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1118 " The OPTION(s) must be followed by the command to send\n"
1119 " To send more than one command, separate the commands with -c\n"
1120 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1121 " Only OPTION(s) can be given.\n"
1123 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1124 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1125 " [--port=<portnr>\n"
1126 " [--cmd-time-out=<number>] [-l] [-D] [-d]\n"
1128 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1129 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1130 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1131 " between the Valgrind gdbserver and vgdb.\n"
1132 " --wait (default 0) tells vgdb to check during the specified number\n"
1133 " of seconds if a Valgrind gdbserver can be found.\n"
1134 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1135 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1136 " process is blocked in a system call).\n"
1137 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1138 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1139 " gdbserver has not processed a command after number seconds\n"
1140 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1141 " -D arg tells to show shared mem status and then exit.\n"
1142 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1144 " -h --help shows this message\n"
1145 " To get help from the Valgrind gdbserver, use vgdb help\n"
1146 "\n", vgdb_prefix_default()
1148 invoker_restrictions_msg();
1151 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1154 else if arg_pid == -1, waits maximum check_trials seconds to discover
1155 a valgrind pid appearing.
1157 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1158 with gdbserver activated.
1160 Returns the pid to work with
1161 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1164 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
1169 if (arg_pid
== 0 || arg_pid
< -1) {
1170 fprintf (stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
1173 /* search for a matching named fifo.
1174 If we have been given a pid, we will check that the matching FIFO is
1175 there (or wait the nr of check_trials for this to appear).
1176 If no pid has been given, then if we find only one FIFO,
1177 we will use this to build the pid to use.
1178 If we find multiple processes with valid FIFO, we report them and will
1179 exit with an error. */
1181 char *vgdb_dir_name
= vmalloc (strlen (vgdb_prefix
) + 3);
1184 int nr_valid_pid
= 0;
1185 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
1186 char *vgdb_format
= vmalloc (strlen(vgdb_prefix
) + strlen(suffix
) + 1);
1188 strcpy (vgdb_format
, vgdb_prefix
);
1189 strcat (vgdb_format
, suffix
);
1191 if (strchr(vgdb_prefix
, '/') != NULL
) {
1192 strcpy (vgdb_dir_name
, vgdb_prefix
);
1193 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
1194 if (vgdb_dir_name
[is
] == '/') {
1195 vgdb_dir_name
[is
+1] = '\0';
1199 strcpy (vgdb_dir_name
, "");
1202 DEBUG(1, "searching pid in directory %s format %s\n",
1203 vgdb_dir_name
, vgdb_format
);
1205 /* try to find FIFOs with valid pid.
1206 On exit of the loop, pid is set to:
1207 the last pid found if show_list (or -1 if no process was listed)
1208 -1 if no FIFOs matching a running process is found
1209 -2 if multiple FIFOs of running processes are found
1210 otherwise it is set to the (only) pid found that can be debugged
1212 for (i
= 0; i
< check_trials
; i
++) {
1213 DEBUG(1, "check_trial %d \n", i
);
1215 /* wait one second before checking again */
1218 vgdb_dir
= opendir (strlen (vgdb_dir_name
) ? vgdb_dir_name
: "./");
1219 if (vgdb_dir
== NULL
)
1221 "vgdb error: opening directory %s searching vgdb fifo\n",
1224 errno
= 0; /* avoid complain if vgdb_dir is empty */
1225 while ((f
= readdir (vgdb_dir
))) {
1227 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
1231 strcpy (pathname
, vgdb_dir_name
);
1232 strcat (pathname
, f
->d_name
);
1233 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
1234 if (stat (pathname
, &st
) != 0) {
1235 if (debuglevel
>= 3)
1236 ERROR (errno
, "vgdb error: stat %s searching vgdb fifo\n",
1238 } else if (S_ISFIFO (st
.st_mode
)) {
1239 DEBUG(3, "trying FIFO %s\n", pathname
);
1240 if (strncmp (pathname
, vgdb_format
,
1241 strlen (vgdb_format
)) == 0) {
1242 newpid
= strtol(pathname
+ strlen (vgdb_format
),
1244 if (*wrongpid
== '-' && newpid
> 0
1245 && kill (newpid
, 0) == 0) {
1248 report_pid (newpid
, /*on_stdout*/ True
);
1250 } else if (arg_pid
!= -1) {
1251 if (arg_pid
== newpid
) {
1254 } else if (nr_valid_pid
> 1) {
1255 if (nr_valid_pid
== 2) {
1258 "no --pid= arg given"
1259 " and multiple valgrind pids found:\n");
1260 report_pid (pid
, /*on_stdout*/ False
);
1263 report_pid (newpid
, /*on_stdout*/ False
);
1270 errno
= 0; /* avoid complain if at the end of vgdb_dir */
1272 if (f
== NULL
&& errno
!= 0)
1273 XERROR (errno
, "vgdb error: reading directory %s for vgdb fifo\n",
1276 closedir (vgdb_dir
);
1281 free (vgdb_dir_name
);
1287 } else if (pid
== -1) {
1289 fprintf (stderr
, "vgdb error: no FIFO found and no pid given\n");
1291 fprintf (stderr
, "vgdb error: no FIFO found matching pid %d\n",
1295 else if (pid
== -2) {
1296 /* no arg_pid given, multiple FIFOs found */
1304 /* return true if the numeric value of an option of the
1305 form --xxxxxxxxx=<number> could properly be extracted
1306 from arg. If True is returned, *value contains the
1309 Bool
numeric_val(char* arg
, int *value
)
1311 const char *eq_pos
= strchr(arg
, '=');
1313 long long int long_value
;
1318 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
1319 if (long_value
< 0 || long_value
> INT_MAX
)
1324 *value
= (int) long_value
;
1328 /* true if arg matches the provided option */
1330 Bool
is_opt(char* arg
, const char *option
)
1332 int option_len
= strlen(option
);
1333 if (option
[option_len
-1] == '=')
1334 return (0 == strncmp(option
, arg
, option_len
));
1336 return (0 == strcmp(option
, arg
));
1339 /* Parse command lines options. If error(s), exits.
1340 Otherwise returns the options in *p_... args.
1341 commands must be big enough for the commands extracted from argv.
1342 On return, *p_last_command gives the position in commands where
1343 the last command has been allocated (using vmalloc). */
1345 void parse_options(int argc
, char** argv
,
1346 Bool
*p_show_shared_mem
,
1349 int *p_check_trials
,
1351 int *p_last_command
,
1354 Bool show_shared_mem
= False
;
1355 Bool show_list
= False
;
1357 int check_trials
= 1;
1358 int last_command
= -1;
1364 for (i
= 1; i
< argc
; i
++) {
1365 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
1368 } else if (is_opt(argv
[i
], "-d")) {
1370 } else if (is_opt(argv
[i
], "-D")) {
1371 show_shared_mem
= True
;
1372 } else if (is_opt(argv
[i
], "-l")) {
1374 } else if (is_opt(argv
[i
], "--pid=")) {
1376 if (!numeric_val(argv
[i
], &newpid
)) {
1377 fprintf (stderr
, "invalid --pid argument %s\n", argv
[i
]);
1379 } else if (arg_pid
!= -1) {
1380 fprintf (stderr
, "multiple --pid arguments given\n");
1385 } else if (is_opt(argv
[i
], "--wait=")) {
1386 if (!numeric_val(argv
[i
], &check_trials
)) {
1387 fprintf (stderr
, "invalid --wait argument %s\n", argv
[i
]);
1390 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
1391 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
1392 fprintf (stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
1395 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
1396 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
1397 fprintf (stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
1400 } else if (is_opt(argv
[i
], "--port=")) {
1401 if (!numeric_val(argv
[i
], &int_port
)) {
1402 fprintf (stderr
, "invalid --port argument %s\n", argv
[i
]);
1405 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
1406 vgdb_prefix
= argv
[i
] + 14;
1407 } else if (is_opt(argv
[i
], "-c")) {
1409 commands
[last_command
] = vmalloc (1);
1410 commands
[last_command
][0] = '\0';
1411 } else if (0 == strncmp(argv
[i
], "-", 1)) {
1412 fprintf (stderr
, "unknown or invalid argument %s\n", argv
[i
]);
1416 if (last_command
== -1) {
1417 /* only one command, no -c command indicator */
1419 commands
[last_command
] = vmalloc (1);
1420 commands
[last_command
][0] = '\0';
1422 len
= strlen(commands
[last_command
]);
1423 commands
[last_command
] = vrealloc (commands
[last_command
],
1424 len
+ 1 + strlen(argv
[i
]) + 1);
1426 strcat (commands
[last_command
], " ");
1427 strcat (commands
[last_command
], argv
[i
]);
1428 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
1429 fprintf (stderr
, "command %s too long\n", commands
[last_command
]);
1436 if (vgdb_prefix
== NULL
)
1437 vgdb_prefix
= vgdb_prefix_default();
1443 && last_command
== -1) {
1446 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1449 if (show_shared_mem
&& show_list
) {
1452 "Can't use both -D and -l options\n");
1455 if (max_invoke_ms
> 0
1456 && cmd_time_out
!= NEVER
1457 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
1460 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1463 if (show_list
&& arg_pid
!= -1) {
1466 "Can't use both --pid and -l options\n");
1469 if (int_port
> 0 && last_command
!= -1) {
1472 "Can't use --port to send commands\n");
1475 if (arg_errors
> 0) {
1476 fprintf (stderr
, "args error. Try `vgdb --help` for more information\n");
1480 *p_show_shared_mem
= show_shared_mem
;
1481 *p_show_list
= show_list
;
1482 *p_arg_pid
= arg_pid
;
1483 *p_check_trials
= check_trials
;
1485 *p_last_command
= last_command
;
1488 int main(int argc
, char** argv
)
1493 Bool show_shared_mem
;
1499 char *commands
[argc
]; // we will never have more commands than args.
1501 parse_options(argc
, argv
,
1510 /* when we are working as a relay for gdb, handle some signals by
1511 only reporting them (according to debug level). Also handle these
1512 when ptrace will be used: vgdb must clean up the ptrace effect before
1514 if (max_invoke_ms
> 0 || last_command
== -1)
1517 pid
= search_arg_pid (arg_pid
, check_trials
, show_list
);
1519 prepare_fifos_and_shared_mem(pid
);
1522 wait_for_gdb_connect(in_port
);
1524 if (show_shared_mem
) {
1527 "written_by_vgdb %d "
1528 "seen_by_valgrind %d\n"
1532 VS_seen_by_valgrind
,
1537 if (last_command
>= 0) {
1538 standalone_send_commands(pid
, last_command
, commands
);
1544 free (from_gdb_to_pid
);
1545 free (to_gdb_from_pid
);
1548 for (i
= 0; i
<= last_command
; i
++)