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");
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");
501 memset(&addr
, 0, sizeof(addr
));
503 addr
.sin_family
= AF_INET
;
504 addr
.sin_port
= htons((unsigned short int)in_port
);
505 addr
.sin_addr
.s_addr
= INADDR_ANY
;
507 if (-1 == bind(listen_gdb
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
508 XERROR(errno
, "bind failed");
510 TSFPRINTF(stderr
, "listening on port %d ...", in_port
);
511 if (-1 == listen(listen_gdb
, 1)) {
512 XERROR(errno
, "error listen failed");
515 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
516 if (gdb_connect
< 0) {
517 XERROR(errno
, "accept failed");
519 fprintf(stderr
, "connected.\n");
522 from_gdb
= gdb_connect
;
523 to_gdb
= gdb_connect
;
526 /* prepares the FIFOs filenames, map the shared memory. */
528 void prepare_fifos_and_shared_mem(int pid
)
530 const HChar
*user
, *host
;
533 user
= getenv("LOGNAME");
534 if (user
== NULL
) user
= getenv("USER");
535 if (user
== NULL
) user
= "???";
536 if (strchr(user
, '/')) user
= "???";
538 host
= getenv("HOST");
539 if (host
== NULL
) host
= getenv("HOSTNAME");
540 if (host
== NULL
) host
= "???";
541 if (strchr(host
, '/')) host
= "???";
543 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
544 from_gdb_to_pid
= vmalloc(len
);
545 to_gdb_from_pid
= vmalloc(len
);
546 shared_mem
= vmalloc(len
);
547 /* below 3 lines must match the equivalent in remote-utils.c */
548 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
550 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
552 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
554 DEBUG(1, "vgdb: using %s %s %s\n",
555 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
557 map_vgdbshared(shared_mem
);
560 /* Convert hex digit A to a number. */
565 if (a
>= '0' && a
<= '9')
567 else if (a
>= 'a' && a
<= 'f')
570 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
574 /* Returns next char from fd. -1 if error, -2 if EOF.
575 NB: must always call it with the same fd */
579 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
580 static int bufcnt
= 0;
581 static unsigned char *bufp
;
582 // unsigned bufp to e.g. avoid having 255 converted to int -1
587 bufcnt
= read_buf(fd
, buf
, "static buf readchar");
591 TSFPRINTF(stderr
, "readchar: Got EOF\n");
594 ERROR(errno
, "readchar\n");
599 bufp
= (unsigned char *)buf
;
604 /* Read a packet from fromfd, with error checking,
606 If checksum incorrect, writes a - on ackfd.
607 Returns length of packet, or -1 if error or -2 if EOF. */
609 getpkt(char *buf
, int fromfd
, int ackfd
)
612 unsigned char csum
, c1
, c2
;
619 c
= readchar(fromfd
);
622 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
629 c
= readchar(fromfd
);
640 repeat
= readchar(fromfd
);
642 for (r
= 0; r
< repeat
- 29; r
++)
651 c1
= fromhex(readchar (fromfd
));
652 c2
= fromhex(readchar (fromfd
));
654 if (csum
== (c1
<< 4) + c2
)
657 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
658 (c1
<< 4) + c2
, csum
, buf
);
659 if (write(ackfd
, "-", 1) != 1)
660 ERROR(0, "error when writing - (nack)\n");
665 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
669 static int sigint
= 0;
670 static int sigterm
= 0;
671 static int sigpipe
= 0;
672 static int sighup
= 0;
673 static int sigusr1
= 0;
674 static int sigalrm
= 0;
675 static int sigusr1_fd
= -1;
676 static pthread_t invoke_gdbserver_in_valgrind_thread
;
679 void received_signal(int signum
)
681 if (signum
== SIGINT
)
683 else if (signum
== SIGUSR1
) {
685 if (sigusr1_fd
>= 0) {
686 char control_c
= '\003';
687 write_buf(sigusr1_fd
, &control_c
, 1,
688 "write \\003 on SIGUSR1", /* notify */ True
);
691 else if (signum
== SIGTERM
) {
692 shutting_down
= True
;
694 } else if (signum
== SIGHUP
) {
695 shutting_down
= True
;
697 } else if (signum
== SIGPIPE
) {
699 } else if (signum
== SIGALRM
) {
701 #if defined(VGPV_arm_linux_android) \
702 || defined(VGPV_x86_linux_android) \
703 || defined(VGPV_mips32_linux_android) \
704 || defined(VGPV_arm64_linux_android)
705 /* Android has no pthread_cancel. As it also does not have
706 an invoker implementation, there is no need for cleanup action.
707 So, we just do nothing. */
708 DEBUG(1, "sigalrm received, no action on android\n");
710 /* Note: we cannot directly invoke restore_and_detach : this must
711 be done by the thread that has attached.
712 We have in this thread pushed a cleanup handler that will
713 cleanup what is needed. */
714 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
715 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
718 ERROR(0, "unexpected signal %d\n", signum
);
722 /* install the signal handlers allowing e.g. vgdb to cleanup in
723 case of termination. */
725 void install_handlers(void)
727 struct sigaction action
, oldaction
;
729 action
.sa_handler
= received_signal
;
730 sigemptyset(&action
.sa_mask
);
733 /* SIGINT: when user types C-c in gdb, this sends
734 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
735 The later is enough to wakeup the valgrind process. */
736 if (sigaction(SIGINT
, &action
, &oldaction
) != 0)
737 XERROR(errno
, "vgdb error sigaction SIGINT\n");
738 /* We might do something more intelligent than just
739 reporting this SIGINT E.g. behave similarly to the gdb: two
740 control-C without feedback from the debugged process would
741 mean to stop debugging it. */
743 /* SIGUSR1: this is used to facilitate automatic testing. When
744 vgdb receives this signal, it will simulate the user typing C-c. */
745 if (sigaction(SIGUSR1
, &action
, &oldaction
) != 0)
746 XERROR(errno
, "vgdb error sigaction SIGUSR1\n");
749 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
750 when detaching or similar. A clean shutdown will be done as both
751 the read and write side will detect an end of file. */
752 if (sigaction(SIGTERM
, &action
, &oldaction
) != 0)
753 XERROR(errno
, "vgdb error sigaction SIGTERM\n");
755 /* SIGPIPE: can receive this signal when gdb detaches or kill the
756 process debugged: gdb will close its pipes to vgdb. vgdb
757 must resist to this signal to allow a clean shutdown. */
758 if (sigaction(SIGPIPE
, &action
, &oldaction
) != 0)
759 XERROR(errno
, "vgdb error sigaction SIGPIPE\n");
761 /* SIGALRM: in case invoke thread is blocked, alarm is used
763 if (sigaction(SIGALRM
, &action
, &oldaction
) != 0)
764 XERROR(errno
, "vgdb error sigaction SIGALRM\n");
766 /* unmask all signals, in case the process that launched vgdb
768 if (sigprocmask(SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
769 XERROR(errno
, "vgdb error sigprocmask");
772 /* close the FIFOs provided connections, terminate the invoker thread. */
774 void close_connection(int to_pid
, int from_pid
)
776 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
777 sigint
, sigterm
, sighup
, sigpipe
);
778 /* Note that we do not forward sigterm to the valgrind process:
779 a sigterm signal is (probably) received from gdb if the user wants to
780 kill the debugged process. The kill instruction has been given to
781 the valgrind process, which should execute a clean exit. */
783 /* We first close the connection to pid. The pid will then
784 terminates its gdbserver work. We keep the from pid
785 fifo opened till the invoker thread is finished.
786 This allows the gdbserver to finish sending its last reply. */
787 if (close(to_pid
) != 0)
788 ERROR(errno
, "close to_pid\n");
790 /* if there is a task that was busy trying to wake up valgrind
791 process, we wait for it to be terminated otherwise threads
792 in the valgrind process can stay stopped if vgdb main
793 exits before the invoke thread had time to detach from
794 all valgrind threads. */
795 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
798 /* It is surprisingly complex to properly shutdown or exit the
799 valgrind process in which gdbserver has been invoked through
800 ptrace. In the normal case (gdb detaches from the process,
801 or process is continued), the valgrind process will reach the
802 breakpoint place. Using ptrace, vgdb will ensure the
803 previous activity of the process is resumed (e.g. restart a
804 blocking system call). The special case is when gdb asks the
805 valgrind process to exit (using either the "kill" command or
806 "monitor exit"). In such a case, the valgrind process will
807 call exit. But a ptraced process will be blocked in exit,
808 waiting for the ptracing process to detach or die. vgdb
809 cannot detach unconditionally as otherwise, in the normal
810 case, the valgrind process would stop abnormally with SIGSTOP
811 (as vgdb would not be there to catch it). vgdb can also not
812 die unconditionally otherwise again, similar problem. So, we
813 assume that most of the time, we arrive here in the normal
814 case, and so, the breakpoint has been encountered by the
815 valgrind process, so the invoker thread will exit and the
816 join will succeed. For the "kill" case, we cause an alarm
817 signal to be sent after a few seconds. This means that in the
818 normal case, the gdbserver code in valgrind process must have
819 returned the control in less than the alarm nr of seconds,
820 otherwise, valgrind will stop abnormally with SIGSTOP. */
823 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
824 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
828 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
830 if (close(from_pid
) != 0)
831 ERROR(errno
, "close from_pid\n");
834 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
835 error is encountered. */
837 void gdb_relay(int pid
)
839 int from_pid
= -1; /* fd to read from pid */
840 int to_pid
= -1; /* fd to write to pid */
842 int shutdown_loop
= 0;
843 TSFPRINTF(stderr
, "relaying data between gdb and process %d\n", pid
);
845 if (max_invoke_ms
> 0)
846 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
847 invoke_gdbserver_in_valgrind
, (void *) &pid
);
848 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
849 acquire_lock(shared_mem_fd
, pid
);
851 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
852 "read mode from pid");
854 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
859 struct pollfd pollfds
[NumConnectionKind
];
861 /* watch data written by gdb, watch POLLERR on both gdb fd */
862 pollfds
[FROM_GDB
].fd
= from_gdb
;
863 pollfds
[FROM_GDB
].events
= POLLIN
;
864 pollfds
[FROM_GDB
].revents
= 0;
865 pollfds
[TO_GDB
].fd
= to_gdb
;
866 pollfds
[TO_GDB
].events
= 0;
867 pollfds
[TO_GDB
].revents
= 0;
869 /* watch data written by pid, watch POLLERR on both pid fd */
870 pollfds
[FROM_PID
].fd
= from_pid
;
871 pollfds
[FROM_PID
].events
= POLLIN
;
872 pollfds
[FROM_PID
].revents
= 0;
873 pollfds
[TO_PID
].fd
= to_pid
;
874 pollfds
[TO_PID
].events
= 0;
875 pollfds
[TO_PID
].revents
= 0;
881 : -1 /* infinite */));
882 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
884 /* check for unexpected error */
885 if (ret
<= 0 && errno
!= EINTR
) {
886 ERROR(errno
, "unexpected poll ret %d\n", ret
);
887 shutting_down
= True
;
891 /* check for data to read */
892 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
893 if (pollfds
[ck
].revents
& POLLIN
) {
896 if (!read_from_gdb_write_to_pid(to_pid
))
897 shutting_down
= True
;
900 if (!read_from_pid_write_to_gdb(from_pid
))
901 shutting_down
= True
;
903 default: XERROR(0, "unexpected POLLIN on %s\n",
904 ppConnectionKind(ck
));
909 /* check for an fd being in error condition */
910 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
911 if (pollfds
[ck
].revents
& POLLERR
) {
912 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
913 ppConnectionKind(ck
), pollfds
[ck
].fd
);
914 invoker_valgrind_dying();
915 shutting_down
= True
;
917 if (pollfds
[ck
].revents
& POLLHUP
) {
918 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
919 ppConnectionKind(ck
), pollfds
[ck
].fd
);
920 invoker_valgrind_dying();
921 shutting_down
= True
;
923 if (pollfds
[ck
].revents
& POLLNVAL
) {
924 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
925 ppConnectionKind(ck
), pollfds
[ck
].fd
);
926 invoker_valgrind_dying();
927 shutting_down
= True
;
932 /* we let some time to the final packets to be transferred */
934 if (shutdown_loop
> 3)
938 close_connection(to_pid
, from_pid
);
941 static int packet_len_for_command(char *cmd
)
943 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
944 return 7+ 2*strlen(cmd
) +3 + 1;
947 /* hyper-minimal protocol implementation that
948 sends the provided commands (using qRcmd packets)
949 and read and display their replies. */
951 void standalone_send_commands(int pid
,
955 int from_pid
= -1; /* fd to read from pid */
956 int to_pid
= -1; /* fd to write to pid */
963 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
968 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
969 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
970 invoke_gdbserver_in_valgrind
, (void *) &pid
);
972 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
973 acquire_lock(shared_mem_fd
, pid
);
975 /* first send a C-c \003 to pid, so that it wakes up the process
976 After that, we can open the fifo from the pid in read mode
977 We then start to wait for packets (normally first a resume reply)
978 At that point, we send our command and expect replies */
981 while (!write_buf(to_pid
, buf
, 1,
982 "write \\003 to wake up", /* notify */ True
)) {
983 /* If write fails, retries up to 10 times every 0.5 seconds
984 This aims at solving the race condition described in
985 remote-utils.c remote_finish function. */
989 XERROR(errno
, "failed to send wake up char after 10 trials\n");
991 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
992 "read cmd result from pid");
994 /* Enable no ack mode. */
995 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
997 buflen
= getpkt(buf
, from_pid
, to_pid
);
998 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1000 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen
);
1002 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1005 for (nc
= 0; nc
<= last_command
; nc
++) {
1006 TSFPRINTF(stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
1008 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1009 hexcommand
= vmalloc(packet_len_for_command(commands
[nc
]));
1011 strcat(hexcommand
, "$qRcmd,");
1012 for (i
= 0; i
< strlen(commands
[nc
]); i
++) {
1013 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][i
]);
1014 // Need to use unsigned char, to avoid sign extension.
1015 strcat(hexcommand
, hex
);
1017 /* checksum (but without the $) */
1019 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1020 cksum
+=hexcommand
[hi
];
1021 strcat(hexcommand
, "#");
1022 sprintf(hex
, "%02x", cksum
);
1023 strcat(hexcommand
, hex
);
1024 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1025 "writing hex command to pid", /* notify */ True
);
1027 /* we exit of the below loop explicitly when the command has
1028 been handled or because a signal handler will set
1030 while (!shutting_down
) {
1031 buflen
= getpkt(buf
, from_pid
, to_pid
);
1033 ERROR(0, "error reading packet\n");
1035 invoker_valgrind_dying();
1038 if (strlen(buf
) == 0) {
1039 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1042 if (strcmp(buf
, "OK") == 0) {
1043 DEBUG(1, "OK packet rcvd\n");
1046 if (buf
[0] == 'E') {
1048 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1052 if (buf
[0] == 'W') {
1053 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1056 if (buf
[0] == 'T') {
1057 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1061 /* must be here an O packet with hex encoded string reply
1062 => decode and print it */
1063 if (buf
[0] != 'O') {
1064 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1068 char buf_print
[buflen
/2 + 1];
1069 for (i
= 1; i
< buflen
; i
= i
+ 2)
1070 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1071 + fromhex(*(buf
+i
+1));
1072 buf_print
[buflen
/2] = 0;
1073 printf("%s", buf_print
);
1079 shutting_down
= True
;
1081 close_connection(to_pid
, from_pid
);
1084 /* report to user the existence of a vgdb-able valgrind process
1086 Note: this function does not use XERROR if an error is encountered
1087 while producing the command line for pid, as this is not critical
1088 and at least on MacOS, reading cmdline is not available. */
1090 void report_pid(int pid
, Bool on_stdout
)
1092 char cmdline_file
[50]; // large enough
1094 FILE *out
= on_stdout
? stdout
: stderr
;
1096 TSFPRINTF(out
, "use --pid=%d for ", pid
);
1098 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
1099 fd
= open(cmdline_file
, O_RDONLY
);
1101 DEBUG(1, "error opening cmdline file %s %s\n",
1102 cmdline_file
, strerror(errno
));
1103 fprintf(out
, "(could not open process command line)\n");
1107 while ((sz
= read(fd
, cmdline
, sizeof cmdline
- 1)) > 0) {
1108 for (i
= 0; i
< sz
; i
++)
1109 if (cmdline
[i
] == 0)
1112 fprintf(out
, "%s", cmdline
);
1115 DEBUG(1, "error reading cmdline file %s %s\n",
1116 cmdline_file
, strerror(errno
));
1117 fprintf(out
, "(error reading process command line)");
1129 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1130 "vgdb (valgrind gdb) has two usages\n"
1131 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1132 " The OPTION(s) must be followed by the command to send\n"
1133 " To send more than one command, separate the commands with -c\n"
1134 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1135 " Only OPTION(s) can be given.\n"
1137 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1138 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1139 " [--port=<portnr>\n"
1140 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1142 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1143 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1144 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1145 " between the Valgrind gdbserver and vgdb.\n"
1146 " --wait (default 0) tells vgdb to check during the specified number\n"
1147 " of seconds if a Valgrind gdbserver can be found.\n"
1148 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1149 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1150 " process is blocked in a system call).\n"
1151 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1152 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1153 " gdbserver has not processed a command after number seconds\n"
1154 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1155 " -T arg tells to add timestamps to vgdb information messages.\n"
1156 " -D arg tells to show shared mem status and then exit.\n"
1157 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1159 " -h --help shows this message\n"
1160 " To get help from the Valgrind gdbserver, use vgdb help\n"
1161 "\n", vgdb_prefix_default()
1163 invoker_restrictions_msg();
1166 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1169 else if arg_pid == -1, waits maximum check_trials seconds to discover
1170 a valgrind pid appearing.
1172 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1173 with gdbserver activated.
1175 Returns the pid to work with
1176 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1179 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
1184 if (arg_pid
== 0 || arg_pid
< -1) {
1185 TSFPRINTF(stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
1188 /* search for a matching named fifo.
1189 If we have been given a pid, we will check that the matching FIFO is
1190 there (or wait the nr of check_trials for this to appear).
1191 If no pid has been given, then if we find only one FIFO,
1192 we will use this to build the pid to use.
1193 If we find multiple processes with valid FIFO, we report them and will
1194 exit with an error. */
1196 char *vgdb_dir_name
= vmalloc(strlen (vgdb_prefix
) + 3);
1199 int nr_valid_pid
= 0;
1200 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
1201 char *vgdb_format
= vmalloc(strlen(vgdb_prefix
) + strlen(suffix
) + 1);
1203 strcpy(vgdb_format
, vgdb_prefix
);
1204 strcat(vgdb_format
, suffix
);
1206 if (strchr(vgdb_prefix
, '/') != NULL
) {
1207 strcpy(vgdb_dir_name
, vgdb_prefix
);
1208 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
1209 if (vgdb_dir_name
[is
] == '/') {
1210 vgdb_dir_name
[is
+1] = '\0';
1214 strcpy(vgdb_dir_name
, "");
1217 DEBUG(1, "searching pid in directory %s format %s\n",
1218 vgdb_dir_name
, vgdb_format
);
1220 /* try to find FIFOs with valid pid.
1221 On exit of the loop, pid is set to:
1222 the last pid found if show_list (or -1 if no process was listed)
1223 -1 if no FIFOs matching a running process is found
1224 -2 if multiple FIFOs of running processes are found
1225 otherwise it is set to the (only) pid found that can be debugged
1227 for (i
= 0; i
< check_trials
; i
++) {
1228 DEBUG(1, "check_trial %d \n", i
);
1230 /* wait one second before checking again */
1233 vgdb_dir
= opendir(strlen(vgdb_dir_name
) ? vgdb_dir_name
: "./");
1234 if (vgdb_dir
== NULL
)
1236 "vgdb error: opening directory %s searching vgdb fifo\n",
1239 errno
= 0; /* avoid complain if vgdb_dir is empty */
1240 while ((f
= readdir(vgdb_dir
))) {
1242 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
1246 strcpy(pathname
, vgdb_dir_name
);
1247 strcat(pathname
, f
->d_name
);
1248 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
1249 if (stat(pathname
, &st
) != 0) {
1250 if (debuglevel
>= 3)
1251 ERROR(errno
, "vgdb error: stat %s searching vgdb fifo\n",
1253 } else if (S_ISFIFO(st
.st_mode
)) {
1254 DEBUG(3, "trying FIFO %s\n", pathname
);
1255 if (strncmp(pathname
, vgdb_format
,
1256 strlen(vgdb_format
)) == 0) {
1257 newpid
= strtol(pathname
+ strlen(vgdb_format
),
1259 if (*wrongpid
== '-' && newpid
> 0
1260 && kill(newpid
, 0) == 0) {
1263 report_pid(newpid
, /*on_stdout*/ True
);
1265 } else if (arg_pid
!= -1) {
1266 if (arg_pid
== newpid
) {
1269 } else if (nr_valid_pid
> 1) {
1270 if (nr_valid_pid
== 2) {
1273 "no --pid= arg given"
1274 " and multiple valgrind pids found:\n");
1275 report_pid(pid
, /*on_stdout*/ False
);
1278 report_pid(newpid
, /*on_stdout*/ False
);
1285 errno
= 0; /* avoid complain if at the end of vgdb_dir */
1287 if (f
== NULL
&& errno
!= 0)
1288 XERROR(errno
, "vgdb error: reading directory %s for vgdb fifo\n",
1296 free(vgdb_dir_name
);
1302 } else if (pid
== -1) {
1304 TSFPRINTF(stderr
, "vgdb error: no FIFO found and no pid given\n");
1306 TSFPRINTF(stderr
, "vgdb error: no FIFO found matching pid %d\n",
1310 else if (pid
== -2) {
1311 /* no arg_pid given, multiple FIFOs found */
1319 /* return true if the numeric value of an option of the
1320 form --xxxxxxxxx=<number> could properly be extracted
1321 from arg. If True is returned, *value contains the
1324 Bool
numeric_val(char* arg
, int *value
)
1326 const char *eq_pos
= strchr(arg
, '=');
1328 long long int long_value
;
1333 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
1334 if (long_value
< 0 || long_value
> INT_MAX
)
1339 *value
= (int) long_value
;
1343 /* true if arg matches the provided option */
1345 Bool
is_opt(char* arg
, const char *option
)
1347 int option_len
= strlen(option
);
1348 if (option
[option_len
-1] == '=')
1349 return (0 == strncmp(option
, arg
, option_len
));
1351 return (0 == strcmp(option
, arg
));
1354 /* Parse command lines options. If error(s), exits.
1355 Otherwise returns the options in *p_... args.
1356 commands must be big enough for the commands extracted from argv.
1357 On return, *p_last_command gives the position in commands where
1358 the last command has been allocated (using vmalloc). */
1360 void parse_options(int argc
, char** argv
,
1361 Bool
*p_show_shared_mem
,
1364 int *p_check_trials
,
1366 int *p_last_command
,
1369 Bool show_shared_mem
= False
;
1370 Bool show_list
= False
;
1372 int check_trials
= 1;
1373 int last_command
= -1;
1379 for (i
= 1; i
< argc
; i
++) {
1380 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
1383 } else if (is_opt(argv
[i
], "-d")) {
1385 } else if (is_opt(argv
[i
], "-D")) {
1386 show_shared_mem
= True
;
1387 } else if (is_opt(argv
[i
], "-l")) {
1389 } else if (is_opt(argv
[i
], "-T")) {
1391 } else if (is_opt(argv
[i
], "--pid=")) {
1393 if (!numeric_val(argv
[i
], &newpid
)) {
1394 TSFPRINTF(stderr
, "invalid --pid argument %s\n", argv
[i
]);
1396 } else if (arg_pid
!= -1) {
1397 TSFPRINTF(stderr
, "multiple --pid arguments given\n");
1402 } else if (is_opt(argv
[i
], "--wait=")) {
1403 if (!numeric_val(argv
[i
], &check_trials
)) {
1404 TSFPRINTF(stderr
, "invalid --wait argument %s\n", argv
[i
]);
1407 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
1408 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
1409 TSFPRINTF(stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
1412 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
1413 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
1414 TSFPRINTF(stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
1417 } else if (is_opt(argv
[i
], "--port=")) {
1418 if (!numeric_val(argv
[i
], &int_port
)) {
1419 TSFPRINTF(stderr
, "invalid --port argument %s\n", argv
[i
]);
1422 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
1423 vgdb_prefix
= argv
[i
] + 14;
1424 } else if (is_opt(argv
[i
], "-c")) {
1426 commands
[last_command
] = vmalloc(1);
1427 commands
[last_command
][0] = '\0';
1428 } else if (0 == strncmp(argv
[i
], "-", 1)) {
1429 TSFPRINTF(stderr
, "unknown or invalid argument %s\n", argv
[i
]);
1433 if (last_command
== -1) {
1434 /* only one command, no -c command indicator */
1436 commands
[last_command
] = vmalloc(1);
1437 commands
[last_command
][0] = '\0';
1439 len
= strlen(commands
[last_command
]);
1440 commands
[last_command
] = vrealloc(commands
[last_command
],
1441 len
+ 1 + strlen(argv
[i
]) + 1);
1443 strcat(commands
[last_command
], " ");
1444 strcat(commands
[last_command
], argv
[i
]);
1445 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
1446 TSFPRINTF(stderr
, "command %s too long\n", commands
[last_command
]);
1453 if (vgdb_prefix
== NULL
)
1454 vgdb_prefix
= vgdb_prefix_default();
1460 && last_command
== -1) {
1463 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1466 if (show_shared_mem
&& show_list
) {
1469 "Can't use both -D and -l options\n");
1472 if (max_invoke_ms
> 0
1473 && cmd_time_out
!= NEVER
1474 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
1477 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1480 if (show_list
&& arg_pid
!= -1) {
1483 "Can't use both --pid and -l options\n");
1486 if (int_port
> 0 && last_command
!= -1) {
1489 "Can't use --port to send commands\n");
1492 if (arg_errors
> 0) {
1493 TSFPRINTF(stderr
, "args error. Try `vgdb --help` for more information\n");
1497 *p_show_shared_mem
= show_shared_mem
;
1498 *p_show_list
= show_list
;
1499 *p_arg_pid
= arg_pid
;
1500 *p_check_trials
= check_trials
;
1502 *p_last_command
= last_command
;
1505 int main(int argc
, char** argv
)
1510 Bool show_shared_mem
;
1516 char *commands
[argc
]; // we will never have more commands than args.
1518 parse_options(argc
, argv
,
1527 /* when we are working as a relay for gdb, handle some signals by
1528 only reporting them (according to debug level). Also handle these
1529 when ptrace will be used: vgdb must clean up the ptrace effect before
1531 if (max_invoke_ms
> 0 || last_command
== -1)
1534 pid
= search_arg_pid(arg_pid
, check_trials
, show_list
);
1536 prepare_fifos_and_shared_mem(pid
);
1539 wait_for_gdb_connect(in_port
);
1541 if (show_shared_mem
) {
1544 "written_by_vgdb %d "
1545 "seen_by_valgrind %d\n",
1548 VS_seen_by_valgrind
);
1549 TSFPRINTF(stderr
, "vgdb pid %d\n", VS_vgdb_pid
);
1553 if (last_command
>= 0) {
1554 standalone_send_commands(pid
, last_command
, commands
);
1560 free(from_gdb_to_pid
);
1561 free(to_gdb_from_pid
);
1564 for (i
= 0; i
<= last_command
; i
++)