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, see <http://www.gnu.org/licenses/>.
24 The GNU General Public License is contained in the file COPYING.
43 #include <netinet/in.h>
45 #include <sys/socket.h>
49 /* vgdb has two usages:
50 1. relay application between gdb and the gdbserver embedded in valgrind.
51 2. standalone to send monitor commands to a running valgrind-ified process
53 It is made of a main program which reads arguments. If no
54 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
57 As relay application, vgdb reads bytes from gdb on stdin and
58 writes these bytes to valgrind. Bytes read from valgrind are
59 written to gdb on stdout. Read/Write from/to valgrind is done
60 using FIFOs. There is one thread reading from stdin, writing to
61 valgrind on a FIFO. There is one thread reading from valgrind on a
62 FIFO, writing to gdb on stdout
64 As a standalone utility, vgdb builds command packets to write to valgrind,
65 sends it and reads the reply. The same two threads are used to write/read.
66 Once all the commands are sent and their replies received, vgdb will exit.
70 Bool timestamp
= False
;
71 char timestamp_out
[20];
72 static char *vgdb_prefix
= NULL
;
74 char *timestamp_str (Bool produce
)
82 gettimeofday(&dbgtv
, NULL
);
83 ts_tm
= localtime(&dbgtv
.tv_sec
);
84 ptr
= out
+ strftime(out
, sizeof(out
), "%H:%M:%S", ts_tm
);
85 sprintf(ptr
, ".%6.6ld ", dbgtv
.tv_usec
);
92 /* Will be set to True when any condition indicating we have to shutdown
94 Bool shutting_down
= False
;
96 VgdbShared32
*shared32
;
97 VgdbShared64
*shared64
;
98 #define VS_written_by_vgdb (shared32 != NULL ? \
99 shared32->written_by_vgdb \
100 : shared64->written_by_vgdb)
101 #define VS_seen_by_valgrind (shared32 != NULL ? \
102 shared32->seen_by_valgrind \
103 : shared64->seen_by_valgrind)
105 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
107 void *vmalloc(size_t size
)
109 void * mem
= malloc(size
);
111 XERROR(errno
, "can't allocate memory\n");
115 void *vrealloc(void *ptr
,size_t size
)
117 void * mem
= realloc(ptr
, size
);
119 XERROR(errno
, "can't reallocate memory\n");
123 /* Return the name of a directory for temporary files. */
125 const char *vgdb_tmpdir(void)
129 tmpdir
= getenv("TMPDIR");
130 if (tmpdir
== NULL
|| *tmpdir
== '\0')
132 if (tmpdir
== NULL
|| *tmpdir
== '\0')
133 tmpdir
= "/tmp"; /* fallback */
138 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
139 to communicate with valgrind */
141 char *vgdb_prefix_default(void)
143 static HChar
*prefix
;
145 if (prefix
== NULL
) {
146 const char *tmpdir
= vgdb_tmpdir();
147 prefix
= vmalloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
148 strcpy(prefix
, tmpdir
);
149 strcat(prefix
, "/vgdb-pipe");
154 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
156 void add_written(int nrw
)
158 if (shared32
!= NULL
)
159 shared32
->written_by_vgdb
+= nrw
;
160 else if (shared64
!= NULL
)
161 shared64
->written_by_vgdb
+= nrw
;
166 static int shared_mem_fd
= -1;
168 void map_vgdbshared(char* shared_mem
)
172 shared_mem_fd
= open(shared_mem
, O_RDWR
);
173 /* shared_mem_fd will not be closed till vgdb exits. */
175 if (shared_mem_fd
== -1)
176 XERROR(errno
, "error opening %s shared memory file\n", shared_mem
);
178 if (fstat(shared_mem_fd
, &fdstat
) != 0)
179 XERROR(errno
, "fstat\n");
181 if (fdstat
.st_size
== sizeof(VgdbShared64
))
182 s
= (void*) &shared64
;
183 else if (fdstat
.st_size
== sizeof(VgdbShared32
))
184 s
= (void*) &shared32
;
186 #if VEX_HOST_WORDSIZE == 8
188 "error size shared memory file %s.\n"
189 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
191 (int) sizeof(VgdbShared64
), (int) sizeof(VgdbShared32
),
192 (long int)fdstat
.st_size
);
193 #elif VEX_HOST_WORDSIZE == 4
195 "error size shared memory file %s.\n"
196 "expecting size %d (32bits) got %ld.\n",
198 (int) sizeof(VgdbShared32
),
201 # error "unexpected wordsize"
204 #if VEX_HOST_WORDSIZE == 4
205 if (shared64
!= NULL
)
206 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
207 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
210 *s
= (void*) mmap(NULL
, fdstat
.st_size
,
211 PROT_READ
|PROT_WRITE
, MAP_SHARED
,
214 if (*s
== (void *) -1)
215 XERROR(errno
, "error mmap shared memory file %s\n", shared_mem
);
219 /* This function loops till shutting_down becomes true. In this loop,
220 it verifies if valgrind process is reading the characters written
221 by vgdb. The verification is done every max_invoke_ms ms. If
222 valgrind is not reading characters, it will use invoker_invoke_gdbserver
223 to ensure that the gdbserver code is called soon by valgrind. */
224 static int max_invoke_ms
= 100;
225 #define NEVER 99999999
226 static int cmd_time_out
= NEVER
;
228 void *invoke_gdbserver_in_valgrind(void *v_pid
)
230 struct timeval cmd_max_end_time
;
231 Bool cmd_started
= False
;
232 struct timeval invoke_time
;
234 int pid
= *(int *)v_pid
;
235 int written_by_vgdb_before_sleep
;
236 int seen_by_valgrind_before_sleep
;
238 int invoked_written
= -1;
241 pthread_cleanup_push(invoker_cleanup_restore_and_detach
, v_pid
);
243 while (!shutting_down
) {
244 written_by_vgdb_before_sleep
= VS_written_by_vgdb
;
245 seen_by_valgrind_before_sleep
= VS_seen_by_valgrind
;
247 "written_by_vgdb_before_sleep %d "
248 "seen_by_valgrind_before_sleep %d\n",
249 written_by_vgdb_before_sleep
,
250 seen_by_valgrind_before_sleep
);
251 if (cmd_time_out
!= NEVER
253 && written_by_vgdb_before_sleep
> seen_by_valgrind_before_sleep
) {
254 /* A command was started. Record the time at which it was started. */
255 DEBUG(1, "IO for command started\n");
256 gettimeofday(&cmd_max_end_time
, NULL
);
257 cmd_max_end_time
.tv_sec
+= cmd_time_out
;
260 if (max_invoke_ms
> 0) {
261 usecs
= 1000 * max_invoke_ms
;
262 gettimeofday(&invoke_time
, NULL
);
263 invoke_time
.tv_sec
+= max_invoke_ms
/ 1000;
264 invoke_time
.tv_usec
+= 1000 * (max_invoke_ms
% 1000);
265 invoke_time
.tv_sec
+= invoke_time
.tv_usec
/ (1000 * 1000);
266 invoke_time
.tv_usec
= invoke_time
.tv_usec
% (1000 * 1000);
271 // 0 usecs here means the thread just has to check gdbserver eats
272 // the characters in <= cmd_time_out seconds.
273 // We will just wait by 1 second max at a time.
274 if (usecs
== 0 || usecs
> 1000 * 1000)
279 /* If nothing happened during our sleep, let's try to wake up valgrind
280 or check for cmd time out. */
281 if (written_by_vgdb_before_sleep
== VS_written_by_vgdb
282 && seen_by_valgrind_before_sleep
== VS_seen_by_valgrind
283 && VS_written_by_vgdb
> VS_seen_by_valgrind
) {
285 gettimeofday(&now
, NULL
);
288 "written_by_vgdb %d "
289 "seen_by_valgrind %d "
290 "invoked_written %d\n",
294 /* if the pid does not exist anymore, we better stop */
295 if (kill(pid
, 0) != 0)
297 "invoke_gdbserver_in_valgrind: "
298 "check for pid %d existence failed\n", pid
);
300 if (timercmp(&now
, &cmd_max_end_time
, >))
302 "pid %d did not handle a command in %d seconds\n",
305 if (max_invoke_ms
> 0 && timercmp (&now
, &invoke_time
, >=)) {
306 /* only need to wake up if the nr written has changed since
308 if (invoked_written
!= written_by_vgdb_before_sleep
) {
309 if (invoker_invoke_gdbserver(pid
)) {
310 /* If invoke successful, no need to invoke again
311 for the same value of written_by_vgdb_before_sleep. */
312 invoked_written
= written_by_vgdb_before_sleep
;
317 // Something happened => restart timer check.
318 if (cmd_time_out
!= NEVER
) {
319 DEBUG(2, "some IO was done => restart command\n");
324 pthread_cleanup_pop(0);
329 int open_fifo(const char* name
, int flags
, const char* desc
)
332 DEBUG(1, "opening %s %s\n", name
, desc
);
333 fd
= open(name
, flags
);
335 XERROR(errno
, "error opening %s %s\n", name
, desc
);
337 DEBUG(1, "opened %s %s fd %d\n", name
, desc
, fd
);
341 /* acquire a lock on the first byte of the given fd. If not successful,
343 This allows to avoid having two vgdb speaking with the same Valgrind
344 gdbserver as this causes serious headaches to the protocol. */
346 void acquire_lock(int fd
, int valgrind_pid
)
350 fl
.l_whence
= SEEK_SET
;
353 if (fcntl(fd
, F_SETLK
, &fl
) < 0) {
354 if (errno
== EAGAIN
|| errno
== EACCES
) {
356 "Cannot acquire lock.\n"
357 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
361 XERROR(errno
, "cannot acquire lock.\n");
365 /* Here, we have the lock. It will be released when fd will be closed. */
366 /* We indicate our pid to Valgrind gdbserver */
367 if (shared32
!= NULL
)
368 shared32
->vgdb_pid
= getpid();
369 else if (shared64
!= NULL
)
370 shared64
->vgdb_pid
= getpid();
375 #define PBUFSIZ 16384 /* keep in sync with server.h */
377 /* read some characters from fd.
378 Returns the nr of characters read, -1 if error.
379 desc is a string used in tracing */
381 int read_buf(int fd
, char* buf
, const char* desc
)
384 DEBUG(2, "reading %s\n", desc
);
385 nrread
= read(fd
, buf
, PBUFSIZ
);
387 ERROR(errno
, "error reading %s\n", desc
);
391 DEBUG(2, "read %s %s\n", desc
, buf
);
395 /* write size bytes from buf to fd.
396 desc is a description of the action for which the write is done.
397 If notify, then add size to the shared cntr indicating to the
398 valgrind process that there is new data.
399 Returns True if write is ok, False if there was a problem. */
401 Bool
write_buf(int fd
, const char* buf
, int size
, const char* desc
, Bool notify
)
405 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc
, size
,
408 while (nrwritten
< size
) {
409 nrw
= write(fd
, buf
+nrwritten
, size
- nrwritten
);
411 ERROR(errno
, "error write %s\n", desc
);
414 nrwritten
= nrwritten
+ nrw
;
425 TO_PID
} ConnectionKind
;
426 static const int NumConnectionKind
= TO_PID
+1;
428 const char *ppConnectionKind(ConnectionKind con
)
431 case FROM_GDB
: return "FROM_GDB";
432 case TO_GDB
: return "TO_GDB";
433 case FROM_PID
: return "FROM_PID";
434 case TO_PID
: return "TO_PID";
435 default: return "invalid connection kind";
439 static char *shared_mem
;
441 static int from_gdb
= 0; /* stdin by default, changed if --port is given. */
442 static char *from_gdb_to_pid
; /* fifo name to write gdb command to pid */
443 /* Returns True in case read/write operations were done properly.
444 Returns False in case of error.
445 to_pid is the file descriptor to write to the process pid. */
447 Bool
read_from_gdb_write_to_pid(int to_pid
)
449 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
452 nrread
= read_buf(from_gdb
, buf
, "from gdb on stdin");
455 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
457 DEBUG(1, "error reading bytes from gdb\n");
459 shutting_down
= True
;
462 return write_buf(to_pid
, buf
, nrread
, "to_pid", /* notify */ True
);
465 static int to_gdb
= 1; /* stdout by default, changed if --port is given. */
466 static char *to_gdb_from_pid
; /* fifo name to read pid replies */
467 /* Returns True in case read/write operations were done properly.
468 Returns False in case of error.
469 from_pid is the file descriptor to read data from the process pid. */
471 Bool
read_from_pid_write_to_gdb(int from_pid
)
473 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
476 nrread
= read_buf(from_pid
, buf
, "from pid");
479 DEBUG(1, "read 0 bytes from pid => assume exit\n");
481 DEBUG(1, "error reading bytes from pid\n");
483 shutting_down
= True
;
486 return write_buf(to_gdb
, buf
, nrread
, "to_gdb", /* notify */ False
);
490 void wait_for_gdb_connect(int in_port
)
492 struct sockaddr_in addr
;
494 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
497 if (-1 == listen_gdb
) {
498 XERROR(errno
, "cannot create socket\n");
501 /* allow address reuse to avoid "address already in use" errors */
504 if (setsockopt(listen_gdb
, SOL_SOCKET
, SO_REUSEADDR
,
505 &one
, sizeof(one
)) < 0) {
506 XERROR(errno
, "cannot enable address reuse\n");
509 memset(&addr
, 0, sizeof(addr
));
511 addr
.sin_family
= AF_INET
;
512 addr
.sin_port
= htons((unsigned short int)in_port
);
513 addr
.sin_addr
.s_addr
= INADDR_ANY
;
515 if (-1 == bind(listen_gdb
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
516 XERROR(errno
, "bind failed\n");
518 TSFPRINTF(stderr
, "listening on port %d ...", in_port
);
519 if (-1 == listen(listen_gdb
, 1)) {
520 XERROR(errno
, "error listen failed\n");
523 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
524 if (gdb_connect
< 0) {
525 XERROR(errno
, "accept failed\n");
527 fprintf(stderr
, "connected.\n");
530 from_gdb
= gdb_connect
;
531 to_gdb
= gdb_connect
;
534 /* prepares the FIFOs filenames, map the shared memory. */
536 void prepare_fifos_and_shared_mem(int pid
)
538 const HChar
*user
, *host
;
541 user
= getenv("LOGNAME");
542 if (user
== NULL
) user
= getenv("USER");
543 if (user
== NULL
) user
= "???";
544 if (strchr(user
, '/')) user
= "???";
546 host
= getenv("HOST");
547 if (host
== NULL
) host
= getenv("HOSTNAME");
548 if (host
== NULL
) host
= "???";
549 if (strchr(host
, '/')) host
= "???";
551 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
552 from_gdb_to_pid
= vmalloc(len
);
553 to_gdb_from_pid
= vmalloc(len
);
554 shared_mem
= vmalloc(len
);
555 /* below 3 lines must match the equivalent in remote-utils.c */
556 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
558 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
560 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
562 DEBUG(1, "vgdb: using %s %s %s\n",
563 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
565 map_vgdbshared(shared_mem
);
568 /* Convert hex digit A to a number. */
573 if (a
>= '0' && a
<= '9')
575 else if (a
>= 'a' && a
<= 'f')
578 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
582 /* Returns next char from fd. -1 if error, -2 if EOF.
583 NB: must always call it with the same fd */
587 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
588 static int bufcnt
= 0;
589 static unsigned char *bufp
;
590 // unsigned bufp to e.g. avoid having 255 converted to int -1
595 bufcnt
= read_buf(fd
, buf
, "static buf readchar");
599 TSFPRINTF(stderr
, "readchar: Got EOF\n");
602 ERROR(errno
, "readchar\n");
607 bufp
= (unsigned char *)buf
;
612 /* Read a packet from fromfd, with error checking,
614 If checksum incorrect, writes a - on ackfd.
615 Returns length of packet, or -1 if error or -2 if EOF. */
617 getpkt(char *buf
, int fromfd
, int ackfd
)
620 unsigned char csum
, c1
, c2
;
627 c
= readchar(fromfd
);
630 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
637 c
= readchar(fromfd
);
648 repeat
= readchar(fromfd
);
650 for (r
= 0; r
< repeat
- 29; r
++)
659 c1
= fromhex(readchar (fromfd
));
660 c2
= fromhex(readchar (fromfd
));
662 if (csum
== (c1
<< 4) + c2
)
665 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
666 (c1
<< 4) + c2
, csum
, buf
);
667 if (write(ackfd
, "-", 1) != 1)
668 ERROR(0, "error when writing - (nack)\n");
673 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
677 static int sigint
= 0;
678 static int sigterm
= 0;
679 static int sigpipe
= 0;
680 static int sighup
= 0;
681 static int sigusr1
= 0;
682 static int sigalrm
= 0;
683 static int sigusr1_fd
= -1;
684 static pthread_t invoke_gdbserver_in_valgrind_thread
;
687 void received_signal(int signum
)
689 if (signum
== SIGINT
)
691 else if (signum
== SIGUSR1
) {
693 if (sigusr1_fd
>= 0) {
694 char control_c
= '\003';
695 write_buf(sigusr1_fd
, &control_c
, 1,
696 "write \\003 on SIGUSR1", /* notify */ True
);
699 else if (signum
== SIGTERM
) {
700 shutting_down
= True
;
702 } else if (signum
== SIGHUP
) {
703 shutting_down
= True
;
705 } else if (signum
== SIGPIPE
) {
707 } else if (signum
== SIGALRM
) {
709 #if defined(VGPV_arm_linux_android) \
710 || defined(VGPV_x86_linux_android) \
711 || defined(VGPV_mips32_linux_android) \
712 || defined(VGPV_arm64_linux_android)
713 /* Android has no pthread_cancel. As it also does not have
714 an invoker implementation, there is no need for cleanup action.
715 So, we just do nothing. */
716 DEBUG(1, "sigalrm received, no action on android\n");
718 /* Note: we cannot directly invoke restore_and_detach : this must
719 be done by the thread that has attached.
720 We have in this thread pushed a cleanup handler that will
721 cleanup what is needed. */
722 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
723 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
726 ERROR(0, "unexpected signal %d\n", signum
);
730 /* install the signal handlers allowing e.g. vgdb to cleanup in
731 case of termination. */
733 void install_handlers(void)
735 struct sigaction action
, oldaction
;
737 action
.sa_handler
= received_signal
;
738 sigemptyset(&action
.sa_mask
);
741 /* SIGINT: when user types C-c in gdb, this sends
742 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
743 The later is enough to wakeup the valgrind process. */
744 if (sigaction(SIGINT
, &action
, &oldaction
) != 0)
745 XERROR(errno
, "vgdb error sigaction SIGINT\n");
746 /* We might do something more intelligent than just
747 reporting this SIGINT E.g. behave similarly to the gdb: two
748 control-C without feedback from the debugged process would
749 mean to stop debugging it. */
751 /* SIGUSR1: this is used to facilitate automatic testing. When
752 vgdb receives this signal, it will simulate the user typing C-c. */
753 if (sigaction(SIGUSR1
, &action
, &oldaction
) != 0)
754 XERROR(errno
, "vgdb error sigaction SIGUSR1\n");
757 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
758 when detaching or similar. A clean shutdown will be done as both
759 the read and write side will detect an end of file. */
760 if (sigaction(SIGTERM
, &action
, &oldaction
) != 0)
761 XERROR(errno
, "vgdb error sigaction SIGTERM\n");
763 /* SIGPIPE: can receive this signal when gdb detaches or kill the
764 process debugged: gdb will close its pipes to vgdb. vgdb
765 must resist to this signal to allow a clean shutdown. */
766 if (sigaction(SIGPIPE
, &action
, &oldaction
) != 0)
767 XERROR(errno
, "vgdb error sigaction SIGPIPE\n");
769 /* SIGALRM: in case invoke thread is blocked, alarm is used
771 if (sigaction(SIGALRM
, &action
, &oldaction
) != 0)
772 XERROR(errno
, "vgdb error sigaction SIGALRM\n");
774 /* unmask all signals, in case the process that launched vgdb
776 if (sigprocmask(SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
777 XERROR(errno
, "vgdb error sigprocmask\n");
780 /* close the FIFOs provided connections, terminate the invoker thread. */
782 void close_connection(int to_pid
, int from_pid
)
784 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
785 sigint
, sigterm
, sighup
, sigpipe
);
786 /* Note that we do not forward sigterm to the valgrind process:
787 a sigterm signal is (probably) received from gdb if the user wants to
788 kill the debugged process. The kill instruction has been given to
789 the valgrind process, which should execute a clean exit. */
791 /* We first close the connection to pid. The pid will then
792 terminates its gdbserver work. We keep the from pid
793 fifo opened till the invoker thread is finished.
794 This allows the gdbserver to finish sending its last reply. */
795 if (close(to_pid
) != 0)
796 ERROR(errno
, "close to_pid\n");
798 /* if there is a task that was busy trying to wake up valgrind
799 process, we wait for it to be terminated otherwise threads
800 in the valgrind process can stay stopped if vgdb main
801 exits before the invoke thread had time to detach from
802 all valgrind threads. */
803 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
806 /* It is surprisingly complex to properly shutdown or exit the
807 valgrind process in which gdbserver has been invoked through
808 ptrace. In the normal case (gdb detaches from the process,
809 or process is continued), the valgrind process will reach the
810 breakpoint place. Using ptrace, vgdb will ensure the
811 previous activity of the process is resumed (e.g. restart a
812 blocking system call). The special case is when gdb asks the
813 valgrind process to exit (using either the "kill" command or
814 "monitor exit"). In such a case, the valgrind process will
815 call exit. But a ptraced process will be blocked in exit,
816 waiting for the ptracing process to detach or die. vgdb
817 cannot detach unconditionally as otherwise, in the normal
818 case, the valgrind process would stop abnormally with SIGSTOP
819 (as vgdb would not be there to catch it). vgdb can also not
820 die unconditionally otherwise again, similar problem. So, we
821 assume that most of the time, we arrive here in the normal
822 case, and so, the breakpoint has been encountered by the
823 valgrind process, so the invoker thread will exit and the
824 join will succeed. For the "kill" case, we cause an alarm
825 signal to be sent after a few seconds. This means that in the
826 normal case, the gdbserver code in valgrind process must have
827 returned the control in less than the alarm nr of seconds,
828 otherwise, valgrind will stop abnormally with SIGSTOP. */
831 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
832 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
836 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
838 #if !defined(VGO_freebsd)
839 if (close(from_pid
) != 0)
840 ERROR(errno
, "close from_pid\n");
844 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
845 error is encountered. */
847 void gdb_relay(int pid
)
849 int from_pid
= -1; /* fd to read from pid */
850 int to_pid
= -1; /* fd to write to pid */
852 int shutdown_loop
= 0;
853 TSFPRINTF(stderr
, "relaying data between gdb and process %d\n", pid
);
855 if (max_invoke_ms
> 0)
856 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
857 invoke_gdbserver_in_valgrind
, (void *) &pid
);
858 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
859 acquire_lock(shared_mem_fd
, pid
);
861 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
862 "read mode from pid");
864 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
869 struct pollfd pollfds
[NumConnectionKind
];
871 /* watch data written by gdb, watch POLLERR on both gdb fd */
872 pollfds
[FROM_GDB
].fd
= from_gdb
;
873 pollfds
[FROM_GDB
].events
= POLLIN
;
874 pollfds
[FROM_GDB
].revents
= 0;
875 pollfds
[TO_GDB
].fd
= to_gdb
;
876 pollfds
[TO_GDB
].events
= 0;
877 pollfds
[TO_GDB
].revents
= 0;
879 /* watch data written by pid, watch POLLERR on both pid fd */
880 pollfds
[FROM_PID
].fd
= from_pid
;
881 pollfds
[FROM_PID
].events
= POLLIN
;
882 pollfds
[FROM_PID
].revents
= 0;
883 pollfds
[TO_PID
].fd
= to_pid
;
884 pollfds
[TO_PID
].events
= 0;
885 pollfds
[TO_PID
].revents
= 0;
891 : -1 /* infinite */));
892 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
894 /* check for unexpected error */
895 if (ret
<= 0 && errno
!= EINTR
) {
896 ERROR(errno
, "unexpected poll ret %d\n", ret
);
897 shutting_down
= True
;
901 /* check for data to read */
902 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
903 if (pollfds
[ck
].revents
& POLLIN
) {
906 if (!read_from_gdb_write_to_pid(to_pid
))
907 shutting_down
= True
;
910 if (!read_from_pid_write_to_gdb(from_pid
))
911 shutting_down
= True
;
913 default: XERROR(0, "unexpected POLLIN on %s\n",
914 ppConnectionKind(ck
));
919 /* check for an fd being in error condition */
920 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
921 if (pollfds
[ck
].revents
& POLLERR
) {
922 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
923 ppConnectionKind(ck
), pollfds
[ck
].fd
);
924 invoker_valgrind_dying();
925 shutting_down
= True
;
927 if (pollfds
[ck
].revents
& POLLHUP
) {
928 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
929 ppConnectionKind(ck
), pollfds
[ck
].fd
);
930 invoker_valgrind_dying();
931 shutting_down
= True
;
933 if (pollfds
[ck
].revents
& POLLNVAL
) {
934 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
935 ppConnectionKind(ck
), pollfds
[ck
].fd
);
936 invoker_valgrind_dying();
937 shutting_down
= True
;
942 /* we let some time to the final packets to be transferred */
944 if (shutdown_loop
> 3)
948 close_connection(to_pid
, from_pid
);
951 static int packet_len_for_command(char *cmd
)
953 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
954 return 7+ 2*strlen(cmd
) +3 + 1;
957 /* hyper-minimal protocol implementation that
958 sends the provided commands (using qRcmd packets)
959 and read and display their replies. */
961 void standalone_send_commands(int pid
,
965 int from_pid
= -1; /* fd to read from pid */
966 int to_pid
= -1; /* fd to write to pid */
973 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
978 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
979 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
980 invoke_gdbserver_in_valgrind
, (void *) &pid
);
982 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
983 acquire_lock(shared_mem_fd
, pid
);
985 /* first send a C-c \003 to pid, so that it wakes up the process
986 After that, we can open the fifo from the pid in read mode
987 We then start to wait for packets (normally first a resume reply)
988 At that point, we send our command and expect replies */
991 while (!write_buf(to_pid
, buf
, 1,
992 "write \\003 to wake up", /* notify */ True
)) {
993 /* If write fails, retries up to 10 times every 0.5 seconds
994 This aims at solving the race condition described in
995 remote-utils.c remote_finish function. */
999 XERROR(errno
, "failed to send wake up char after 10 trials\n");
1001 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
1002 "read cmd result from pid");
1004 /* Enable no ack mode. */
1005 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1007 buflen
= getpkt(buf
, from_pid
, to_pid
);
1008 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1010 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen
);
1012 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1015 for (nc
= 0; nc
<= last_command
; nc
++) {
1016 TSFPRINTF(stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
1018 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1019 hexcommand
= vmalloc(packet_len_for_command(commands
[nc
]));
1021 strcat(hexcommand
, "$qRcmd,");
1022 for (i
= 0; i
< strlen(commands
[nc
]); i
++) {
1023 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][i
]);
1024 // Need to use unsigned char, to avoid sign extension.
1025 strcat(hexcommand
, hex
);
1027 /* checksum (but without the $) */
1029 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1030 cksum
+=hexcommand
[hi
];
1031 strcat(hexcommand
, "#");
1032 sprintf(hex
, "%02x", cksum
);
1033 strcat(hexcommand
, hex
);
1034 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1035 "writing hex command to pid", /* notify */ True
);
1037 /* we exit of the below loop explicitly when the command has
1038 been handled or because a signal handler will set
1040 while (!shutting_down
) {
1041 buflen
= getpkt(buf
, from_pid
, to_pid
);
1043 ERROR(0, "error reading packet\n");
1045 invoker_valgrind_dying();
1048 if (strlen(buf
) == 0) {
1049 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1052 if (strcmp(buf
, "OK") == 0) {
1053 DEBUG(1, "OK packet rcvd\n");
1056 if (buf
[0] == 'E') {
1058 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1062 if (buf
[0] == 'W') {
1063 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1066 if (buf
[0] == 'T') {
1067 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1071 /* must be here an O packet with hex encoded string reply
1072 => decode and print it */
1073 if (buf
[0] != 'O') {
1074 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1078 char buf_print
[buflen
/2 + 1];
1079 for (i
= 1; i
< buflen
; i
= i
+ 2)
1080 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1081 + fromhex(*(buf
+i
+1));
1082 buf_print
[buflen
/2] = 0;
1083 printf("%s", buf_print
);
1089 shutting_down
= True
;
1091 close_connection(to_pid
, from_pid
);
1094 /* report to user the existence of a vgdb-able valgrind process
1096 Note: this function does not use XERROR if an error is encountered
1097 while producing the command line for pid, as this is not critical
1098 and at least on MacOS, reading cmdline is not available. */
1100 void report_pid(int pid
, Bool on_stdout
)
1102 char cmdline_file
[50]; // large enough
1104 FILE *out
= on_stdout
? stdout
: stderr
;
1106 TSFPRINTF(out
, "use --pid=%d for ", pid
);
1108 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
1109 fd
= open(cmdline_file
, O_RDONLY
);
1111 DEBUG(1, "error opening cmdline file %s %s\n",
1112 cmdline_file
, strerror(errno
));
1113 fprintf(out
, "(could not open process command line)\n");
1117 while ((sz
= read(fd
, cmdline
, sizeof cmdline
- 1)) > 0) {
1118 for (i
= 0; i
< sz
; i
++)
1119 if (cmdline
[i
] == 0)
1122 fprintf(out
, "%s", cmdline
);
1125 DEBUG(1, "error reading cmdline file %s %s\n",
1126 cmdline_file
, strerror(errno
));
1127 fprintf(out
, "(error reading process command line)");
1139 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1140 "vgdb (valgrind gdb) has two usages\n"
1141 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1142 " The OPTION(s) must be followed by the command to send\n"
1143 " To send more than one command, separate the commands with -c\n"
1144 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1145 " Only OPTION(s) can be given.\n"
1147 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1148 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1149 " [--port=<portnr>\n"
1150 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1152 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1153 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1154 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1155 " between the Valgrind gdbserver and vgdb.\n"
1156 " --wait (default 0) tells vgdb to check during the specified number\n"
1157 " of seconds if a Valgrind gdbserver can be found.\n"
1158 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1159 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1160 " process is blocked in a system call).\n"
1161 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1162 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1163 " gdbserver has not processed a command after number seconds\n"
1164 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1165 " -T arg tells to add timestamps to vgdb information messages.\n"
1166 " -D arg tells to show shared mem status and then exit.\n"
1167 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1169 " -h --help shows this message\n"
1170 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
1171 " To get help from the Valgrind gdbserver, use vgdb help\n"
1172 "\n", vgdb_prefix_default(), VG_LIBDIR
"/valgrind-monitor.py"
1174 invoker_restrictions_msg();
1177 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1180 else if arg_pid == -1, waits maximum check_trials seconds to discover
1181 a valgrind pid appearing.
1183 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1184 with gdbserver activated.
1186 Returns the pid to work with
1187 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1190 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
1195 if (arg_pid
== 0 || arg_pid
< -1) {
1196 TSFPRINTF(stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
1199 /* search for a matching named fifo.
1200 If we have been given a pid, we will check that the matching FIFO is
1201 there (or wait the nr of check_trials for this to appear).
1202 If no pid has been given, then if we find only one FIFO,
1203 we will use this to build the pid to use.
1204 If we find multiple processes with valid FIFO, we report them and will
1205 exit with an error. */
1207 char *vgdb_dir_name
= vmalloc(strlen (vgdb_prefix
) + 3);
1210 int nr_valid_pid
= 0;
1211 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
1212 char *vgdb_format
= vmalloc(strlen(vgdb_prefix
) + strlen(suffix
) + 1);
1214 strcpy(vgdb_format
, vgdb_prefix
);
1215 strcat(vgdb_format
, suffix
);
1217 if (strchr(vgdb_prefix
, '/') != NULL
) {
1218 strcpy(vgdb_dir_name
, vgdb_prefix
);
1219 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
1220 if (vgdb_dir_name
[is
] == '/') {
1221 vgdb_dir_name
[is
+1] = '\0';
1225 strcpy(vgdb_dir_name
, "");
1228 DEBUG(1, "searching pid in directory %s format %s\n",
1229 vgdb_dir_name
, vgdb_format
);
1231 /* try to find FIFOs with valid pid.
1232 On exit of the loop, pid is set to:
1233 the last pid found if show_list (or -1 if no process was listed)
1234 -1 if no FIFOs matching a running process is found
1235 -2 if multiple FIFOs of running processes are found
1236 otherwise it is set to the (only) pid found that can be debugged
1238 for (i
= 0; i
< check_trials
; i
++) {
1239 DEBUG(1, "check_trial %d \n", i
);
1241 /* wait one second before checking again */
1244 vgdb_dir
= opendir(strlen(vgdb_dir_name
) ? vgdb_dir_name
: "./");
1245 if (vgdb_dir
== NULL
)
1247 "vgdb error: opening directory %s searching vgdb fifo\n",
1250 errno
= 0; /* avoid complain if vgdb_dir is empty */
1251 while ((f
= readdir(vgdb_dir
))) {
1253 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
1257 strcpy(pathname
, vgdb_dir_name
);
1258 strcat(pathname
, f
->d_name
);
1259 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
1260 if (stat(pathname
, &st
) != 0) {
1261 if (debuglevel
>= 3)
1262 ERROR(errno
, "vgdb error: stat %s searching vgdb fifo\n",
1264 } else if (S_ISFIFO(st
.st_mode
)) {
1265 DEBUG(3, "trying FIFO %s\n", pathname
);
1266 if (strncmp(pathname
, vgdb_format
,
1267 strlen(vgdb_format
)) == 0) {
1268 newpid
= strtol(pathname
+ strlen(vgdb_format
),
1270 if (*wrongpid
== '-' && newpid
> 0
1271 && kill(newpid
, 0) == 0) {
1274 report_pid(newpid
, /*on_stdout*/ True
);
1276 } else if (arg_pid
!= -1) {
1277 if (arg_pid
== newpid
) {
1280 } else if (nr_valid_pid
> 1) {
1281 if (nr_valid_pid
== 2) {
1284 "no --pid= arg given"
1285 " and multiple valgrind pids found:\n");
1286 report_pid(pid
, /*on_stdout*/ False
);
1289 report_pid(newpid
, /*on_stdout*/ False
);
1296 errno
= 0; /* avoid complain if at the end of vgdb_dir */
1298 if (f
== NULL
&& errno
!= 0)
1299 XERROR(errno
, "vgdb error: reading directory %s for vgdb fifo\n",
1307 free(vgdb_dir_name
);
1313 } else if (pid
== -1) {
1315 TSFPRINTF(stderr
, "vgdb error: no FIFO found and no pid given\n");
1317 TSFPRINTF(stderr
, "vgdb error: no FIFO found matching pid %d\n",
1321 else if (pid
== -2) {
1322 /* no arg_pid given, multiple FIFOs found */
1330 /* return true if the numeric value of an option of the
1331 form --xxxxxxxxx=<number> could properly be extracted
1332 from arg. If True is returned, *value contains the
1335 Bool
numeric_val(char* arg
, int *value
)
1337 const char *eq_pos
= strchr(arg
, '=');
1339 long long int long_value
;
1344 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
1345 if (long_value
< 0 || long_value
> INT_MAX
)
1350 *value
= (int) long_value
;
1354 /* true if arg matches the provided option */
1356 Bool
is_opt(char* arg
, const char *option
)
1358 int option_len
= strlen(option
);
1359 if (option
[option_len
-1] == '=')
1360 return (0 == strncmp(option
, arg
, option_len
));
1362 return (0 == strcmp(option
, arg
));
1365 /* Parse command lines options. If error(s), exits.
1366 Otherwise returns the options in *p_... args.
1367 commands must be big enough for the commands extracted from argv.
1368 On return, *p_last_command gives the position in commands where
1369 the last command has been allocated (using vmalloc). */
1371 void parse_options(int argc
, char** argv
,
1372 Bool
*p_show_shared_mem
,
1375 int *p_check_trials
,
1377 int *p_last_command
,
1380 Bool show_shared_mem
= False
;
1381 Bool show_list
= False
;
1383 int check_trials
= 1;
1384 int last_command
= -1;
1390 for (i
= 1; i
< argc
; i
++) {
1391 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
1394 } else if (is_opt(argv
[i
], "-d")) {
1396 } else if (is_opt(argv
[i
], "-D")) {
1397 show_shared_mem
= True
;
1398 } else if (is_opt(argv
[i
], "-l")) {
1400 } else if (is_opt(argv
[i
], "-T")) {
1402 } else if (is_opt(argv
[i
], "--pid=")) {
1404 if (!numeric_val(argv
[i
], &newpid
)) {
1405 TSFPRINTF(stderr
, "invalid --pid argument %s\n", argv
[i
]);
1407 } else if (arg_pid
!= -1) {
1408 TSFPRINTF(stderr
, "multiple --pid arguments given\n");
1413 } else if (is_opt(argv
[i
], "--wait=")) {
1414 if (!numeric_val(argv
[i
], &check_trials
)) {
1415 TSFPRINTF(stderr
, "invalid --wait argument %s\n", argv
[i
]);
1418 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
1419 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
1420 TSFPRINTF(stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
1423 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
1424 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
1425 TSFPRINTF(stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
1428 } else if (is_opt(argv
[i
], "--port=")) {
1429 if (!numeric_val(argv
[i
], &int_port
)) {
1430 TSFPRINTF(stderr
, "invalid --port argument %s\n", argv
[i
]);
1433 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
1434 vgdb_prefix
= argv
[i
] + 14;
1435 } else if (is_opt(argv
[i
], "-c")) {
1437 commands
[last_command
] = vmalloc(1);
1438 commands
[last_command
][0] = '\0';
1439 } else if (0 == strncmp(argv
[i
], "-", 1)) {
1440 TSFPRINTF(stderr
, "unknown or invalid argument %s\n", argv
[i
]);
1444 if (last_command
== -1) {
1445 /* only one command, no -c command indicator */
1447 commands
[last_command
] = vmalloc(1);
1448 commands
[last_command
][0] = '\0';
1450 len
= strlen(commands
[last_command
]);
1451 commands
[last_command
] = vrealloc(commands
[last_command
],
1452 len
+ 1 + strlen(argv
[i
]) + 1);
1454 strcat(commands
[last_command
], " ");
1455 strcat(commands
[last_command
], argv
[i
]);
1456 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
1457 TSFPRINTF(stderr
, "command %s too long\n", commands
[last_command
]);
1464 if (vgdb_prefix
== NULL
)
1465 vgdb_prefix
= vgdb_prefix_default();
1471 && last_command
== -1) {
1474 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1477 if (show_shared_mem
&& show_list
) {
1480 "Can't use both -D and -l options\n");
1483 if (max_invoke_ms
> 0
1484 && cmd_time_out
!= NEVER
1485 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
1488 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1491 if (show_list
&& arg_pid
!= -1) {
1494 "Can't use both --pid and -l options\n");
1497 if (int_port
> 0 && last_command
!= -1) {
1500 "Can't use --port to send commands\n");
1503 if (arg_errors
> 0) {
1504 TSFPRINTF(stderr
, "args error. Try `vgdb --help` for more information\n");
1508 *p_show_shared_mem
= show_shared_mem
;
1509 *p_show_list
= show_list
;
1510 *p_arg_pid
= arg_pid
;
1511 *p_check_trials
= check_trials
;
1513 *p_last_command
= last_command
;
1516 int main(int argc
, char** argv
)
1521 Bool show_shared_mem
;
1527 char *commands
[argc
]; // we will never have more commands than args.
1529 parse_options(argc
, argv
,
1538 /* when we are working as a relay for gdb, handle some signals by
1539 only reporting them (according to debug level). Also handle these
1540 when ptrace will be used: vgdb must clean up the ptrace effect before
1542 if (max_invoke_ms
> 0 || last_command
== -1)
1545 pid
= search_arg_pid(arg_pid
, check_trials
, show_list
);
1547 prepare_fifos_and_shared_mem(pid
);
1550 wait_for_gdb_connect(in_port
);
1552 if (show_shared_mem
) {
1555 "written_by_vgdb %d "
1556 "seen_by_valgrind %d\n",
1559 VS_seen_by_valgrind
);
1560 TSFPRINTF(stderr
, "vgdb pid %d\n", VS_vgdb_pid
);
1564 if (last_command
>= 0) {
1565 standalone_send_commands(pid
, last_command
, commands
);
1571 free(from_gdb_to_pid
);
1572 free(to_gdb_from_pid
);
1575 for (i
= 0; i
<= last_command
; i
++)