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.
45 #include <netinet/in.h>
47 #include <sys/socket.h>
52 #include "m_gdbserver/remote-utils-shared.h"
54 /* vgdb has three usages:
55 1. relay application between gdb and the gdbserver embedded in valgrind.
56 2. standalone to send monitor commands to a running valgrind-ified process
57 3. multi mode where vgdb uses the GDB extended remote protocol.
59 It is made of a main program which reads arguments. If no
60 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
63 As relay application, vgdb reads bytes from gdb on stdin and
64 writes these bytes to valgrind. Bytes read from valgrind are
65 written to gdb on stdout. Read/Write from/to valgrind is done
66 using FIFOs. There is one thread reading from stdin, writing to
67 valgrind on a FIFO. There is one thread reading from valgrind on a
68 FIFO, writing to gdb on stdout
70 As a standalone utility, vgdb builds command packets to write to valgrind,
71 sends it and reads the reply. The same two threads are used to write/read.
72 Once all the commands are sent and their replies received, vgdb will exit.
74 When --multi is given vgdb communicates with GDB through the extended remote
75 protocol and will launch valgrind whenever GDB sends the vRun packet, after
76 which it will function in the first mode, relaying packets between GDB and
77 the gdbserver embedded in valgrind till that valgrind quits. vgdb will stay
82 Bool timestamp
= False
;
83 char timestamp_out
[20];
84 static char *vgdb_prefix
= NULL
;
85 static char *valgrind_path
= NULL
;
87 static int cvargs
= 0;
89 char *timestamp_str (Bool produce
)
97 gettimeofday(&dbgtv
, NULL
);
98 ts_tm
= localtime(&dbgtv
.tv_sec
);
99 ptr
= out
+ strftime(out
, sizeof(out
), "%H:%M:%S", ts_tm
);
100 sprintf(ptr
, ".%6.6ld ", (long)dbgtv
.tv_usec
);
107 /* Will be set to True when any condition indicating we have to shutdown
109 Bool shutting_down
= False
;
111 VgdbShared32
*shared32
;
112 VgdbShared64
*shared64
;
113 #define VS_written_by_vgdb (shared32 != NULL ? \
114 shared32->written_by_vgdb \
115 : shared64->written_by_vgdb)
116 #define VS_seen_by_valgrind (shared32 != NULL ? \
117 shared32->seen_by_valgrind \
118 : shared64->seen_by_valgrind)
120 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
122 void *vmalloc(size_t size
)
124 void * mem
= malloc(size
);
126 XERROR(errno
, "can't allocate memory\n");
130 void *vrealloc(void *ptr
,size_t size
)
132 void * mem
= realloc(ptr
, size
);
134 XERROR(errno
, "can't reallocate memory\n");
138 /* Return the name of a directory for temporary files. */
140 const char *vgdb_tmpdir(void)
144 tmpdir
= getenv("TMPDIR");
145 if (tmpdir
== NULL
|| *tmpdir
== '\0')
147 if (tmpdir
== NULL
|| *tmpdir
== '\0')
148 tmpdir
= "/tmp"; /* fallback */
153 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
154 to communicate with valgrind */
156 char *vgdb_prefix_default(void)
158 static HChar
*prefix
;
160 if (prefix
== NULL
) {
161 const char *tmpdir
= vgdb_tmpdir();
162 prefix
= vmalloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
163 strcpy(prefix
, tmpdir
);
164 strcat(prefix
, "/vgdb-pipe");
169 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
171 void add_written(int nrw
)
173 if (shared32
!= NULL
)
174 shared32
->written_by_vgdb
+= nrw
;
175 else if (shared64
!= NULL
)
176 shared64
->written_by_vgdb
+= nrw
;
181 static int shared_mem_fd
= -1;
183 void map_vgdbshared(char* shared_mem
, int check_trials
)
190 /* valgrind might still be starting up, give it 5 seconds by
191 * default, or check_trials seconds if it is set by --wait
192 * to more than a second. */
193 if (check_trials
> 1) {
194 DEBUG(1, "check_trials %d\n", check_trials
);
195 tries
= check_trials
* 10;
198 shared_mem_fd
= open(shared_mem
, O_RDWR
| O_CLOEXEC
);
200 if (shared_mem_fd
== -1 && err
== ENOENT
&& tries
> 0)
201 usleep (100000); /* wait 0.1 seconds */
202 } while (shared_mem_fd
== -1 && err
== ENOENT
&& tries
-- > 0);
204 /* shared_mem_fd will not be closed till vgdb exits. */
206 if (shared_mem_fd
== -1)
207 XERROR(errno
, "error opening %s shared memory file\n", shared_mem
);
209 if (fstat(shared_mem_fd
, &fdstat
) != 0)
210 XERROR(errno
, "fstat\n");
212 if (fdstat
.st_size
== sizeof(VgdbShared64
))
213 s
= (void*) &shared64
;
214 else if (fdstat
.st_size
== sizeof(VgdbShared32
))
215 s
= (void*) &shared32
;
217 #if VEX_HOST_WORDSIZE == 8
219 "error size shared memory file %s.\n"
220 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
222 (int) sizeof(VgdbShared64
), (int) sizeof(VgdbShared32
),
223 (long int)fdstat
.st_size
);
224 #elif VEX_HOST_WORDSIZE == 4
226 "error size shared memory file %s.\n"
227 "expecting size %d (32bits) got %ld.\n",
229 (int) sizeof(VgdbShared32
),
232 # error "unexpected wordsize"
235 #if VEX_HOST_WORDSIZE == 4
236 if (shared64
!= NULL
)
237 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
238 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
241 *s
= (void*) mmap(NULL
, fdstat
.st_size
,
242 PROT_READ
|PROT_WRITE
, MAP_SHARED
,
245 if (*s
== (void *) -1)
246 XERROR(errno
, "error mmap shared memory file %s\n", shared_mem
);
250 /* This function loops till shutting_down becomes true. In this loop,
251 it verifies if valgrind process is reading the characters written
252 by vgdb. The verification is done every max_invoke_ms ms. If
253 valgrind is not reading characters, it will use invoker_invoke_gdbserver
254 to ensure that the gdbserver code is called soon by valgrind. */
255 static int max_invoke_ms
= 100;
256 #define NEVER 99999999
257 static int cmd_time_out
= NEVER
;
259 void *invoke_gdbserver_in_valgrind(void *v_pid
)
261 struct timeval cmd_max_end_time
;
262 Bool cmd_started
= False
;
263 struct timeval invoke_time
;
265 int pid
= *(int *)v_pid
;
266 int written_by_vgdb_before_sleep
;
267 int seen_by_valgrind_before_sleep
;
269 int invoked_written
= -1;
272 pthread_cleanup_push(invoker_cleanup_restore_and_detach
, v_pid
);
274 while (!shutting_down
) {
275 written_by_vgdb_before_sleep
= VS_written_by_vgdb
;
276 seen_by_valgrind_before_sleep
= VS_seen_by_valgrind
;
278 "written_by_vgdb_before_sleep %d "
279 "seen_by_valgrind_before_sleep %d\n",
280 written_by_vgdb_before_sleep
,
281 seen_by_valgrind_before_sleep
);
282 if (cmd_time_out
!= NEVER
284 && written_by_vgdb_before_sleep
> seen_by_valgrind_before_sleep
) {
285 /* A command was started. Record the time at which it was started. */
286 DEBUG(1, "IO for command started\n");
287 gettimeofday(&cmd_max_end_time
, NULL
);
288 cmd_max_end_time
.tv_sec
+= cmd_time_out
;
291 if (max_invoke_ms
> 0) {
292 usecs
= 1000 * max_invoke_ms
;
293 gettimeofday(&invoke_time
, NULL
);
294 invoke_time
.tv_sec
+= max_invoke_ms
/ 1000;
295 invoke_time
.tv_usec
+= 1000 * (max_invoke_ms
% 1000);
296 invoke_time
.tv_sec
+= invoke_time
.tv_usec
/ (1000 * 1000);
297 invoke_time
.tv_usec
= invoke_time
.tv_usec
% (1000 * 1000);
302 // 0 usecs here means the thread just has to check gdbserver eats
303 // the characters in <= cmd_time_out seconds.
304 // We will just wait by 1 second max at a time.
305 if (usecs
== 0 || usecs
> 1000 * 1000)
310 /* If nothing happened during our sleep, let's try to wake up valgrind
311 or check for cmd time out. */
312 if (written_by_vgdb_before_sleep
== VS_written_by_vgdb
313 && seen_by_valgrind_before_sleep
== VS_seen_by_valgrind
314 && VS_written_by_vgdb
> VS_seen_by_valgrind
) {
316 gettimeofday(&now
, NULL
);
319 "written_by_vgdb %d "
320 "seen_by_valgrind %d "
321 "invoked_written %d\n",
325 /* if the pid does not exist anymore, we better stop */
326 if (kill(pid
, 0) != 0)
328 "invoke_gdbserver_in_valgrind: "
329 "check for pid %d existence failed\n", pid
);
331 if (timercmp(&now
, &cmd_max_end_time
, >))
333 "pid %d did not handle a command in %d seconds\n",
336 if (max_invoke_ms
> 0 && timercmp (&now
, &invoke_time
, >=)) {
337 /* only need to wake up if the nr written has changed since
339 if (invoked_written
!= written_by_vgdb_before_sleep
) {
340 if (invoker_invoke_gdbserver(pid
)) {
341 /* If invoke successful, no need to invoke again
342 for the same value of written_by_vgdb_before_sleep. */
343 invoked_written
= written_by_vgdb_before_sleep
;
348 // Something happened => restart timer check.
349 if (cmd_time_out
!= NEVER
) {
350 DEBUG(2, "some IO was done => restart command\n");
355 pthread_cleanup_pop(0);
360 int open_fifo(const char* name
, int flags
, const char* desc
)
363 DEBUG(1, "opening %s %s\n", name
, desc
);
364 fd
= open(name
, flags
| O_CLOEXEC
);
366 XERROR(errno
, "error opening %s %s\n", name
, desc
);
368 DEBUG(1, "opened %s %s fd %d\n", name
, desc
, fd
);
372 /* acquire a lock on the first byte of the given fd. If not successful,
374 This allows to avoid having two vgdb speaking with the same Valgrind
375 gdbserver as this causes serious headaches to the protocol. */
377 void acquire_lock(int fd
, int valgrind_pid
)
381 fl
.l_whence
= SEEK_SET
;
384 if (fcntl(fd
, F_SETLK
, &fl
) < 0) {
385 if (errno
== EAGAIN
|| errno
== EACCES
) {
387 "Cannot acquire lock.\n"
388 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
392 XERROR(errno
, "cannot acquire lock.\n");
396 /* Here, we have the lock. It will be released when fd will be closed. */
397 /* We indicate our pid to Valgrind gdbserver */
398 if (shared32
!= NULL
)
399 shared32
->vgdb_pid
= getpid();
400 else if (shared64
!= NULL
)
401 shared64
->vgdb_pid
= getpid();
406 #define PBUFSIZ 16384 /* keep in sync with server.h */
408 /* read some characters from fd.
409 Returns the nr of characters read, -1 if error.
410 desc is a string used in tracing */
412 int read_buf(int fd
, char* buf
, const char* desc
)
415 DEBUG(2, "reading %s\n", desc
);
416 /* The file descriptor is on non-blocking mode and read_buf should only
417 be called when poll gave us an POLLIN event signaling the file
418 descriptor is ready for reading from. Still sometimes we do get an
419 occasional EAGAIN. Just do as told in that case and try to read
422 nrread
= read(fd
, buf
, PBUFSIZ
);
423 } while (nrread
== -1 && errno
== EAGAIN
);
425 ERROR(errno
, "error reading %s\n", desc
);
429 DEBUG(2, "read %s %s\n", desc
, buf
);
433 /* write size bytes from buf to fd.
434 desc is a description of the action for which the write is done.
435 If notify, then add size to the shared cntr indicating to the
436 valgrind process that there is new data.
437 Returns True if write is ok, False if there was a problem. */
439 Bool
write_buf(int fd
, const char* buf
, int size
, const char* desc
, Bool notify
)
443 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc
, size
,
446 while (nrwritten
< size
) {
447 nrw
= write(fd
, buf
+nrwritten
, size
- nrwritten
);
449 ERROR(errno
, "error write %s\n", desc
);
452 nrwritten
= nrwritten
+ nrw
;
463 TO_PID
} ConnectionKind
;
464 static const int NumConnectionKind
= TO_PID
+1;
466 const char *ppConnectionKind(ConnectionKind con
)
469 case FROM_GDB
: return "FROM_GDB";
470 case TO_GDB
: return "TO_GDB";
471 case FROM_PID
: return "FROM_PID";
472 case TO_PID
: return "TO_PID";
473 default: return "invalid connection kind";
477 static char *shared_mem
;
479 static int from_gdb
= 0; /* stdin by default, changed if --port is given. */
480 static char *from_gdb_to_pid
; /* fifo name to write gdb command to pid */
482 static int to_gdb
= 1; /* stdout by default, changed if --port is given. */
483 static char *to_gdb_from_pid
; /* fifo name to read pid replies */
485 /* Returns True in case read/write operations were done properly.
486 Returns False in case of error.
487 to_pid is the file descriptor to write to the process pid. */
489 Bool
read_from_gdb_write_to_pid(int to_pid
)
491 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
495 nrread
= read_buf(from_gdb
, buf
, "from gdb on stdin");
498 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
500 DEBUG(1, "error reading bytes from gdb\n");
502 shutting_down
= True
;
505 ret
= write_buf(to_pid
, buf
, nrread
, "to_pid", /* notify */ True
);
507 /* Let gdb know the packet couldn't be delivered. */
508 write_buf(to_gdb
, "$E01#a6", 8, "error back to gdb", False
);
513 /* Returns True in case read/write operations were done properly.
514 Returns False in case of error.
515 from_pid is the file descriptor to read data from the process pid. */
517 Bool
read_from_pid_write_to_gdb(int from_pid
)
519 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
522 nrread
= read_buf(from_pid
, buf
, "from pid");
525 DEBUG(1, "read 0 bytes from pid => assume exit\n");
527 DEBUG(1, "error reading bytes from pid\n");
529 shutting_down
= True
;
532 return write_buf(to_gdb
, buf
, nrread
, "to_gdb", /* notify */ False
);
536 void wait_for_gdb_connect(int in_port
)
538 struct sockaddr_in addr
;
541 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, IPPROTO_TCP
);
543 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
548 if (-1 == listen_gdb
) {
549 XERROR(errno
, "cannot create socket\n");
552 /* allow address reuse to avoid "address already in use" errors */
555 if (setsockopt(listen_gdb
, SOL_SOCKET
, SO_REUSEADDR
,
556 &one
, sizeof(one
)) < 0) {
557 XERROR(errno
, "cannot enable address reuse\n");
560 memset(&addr
, 0, sizeof(addr
));
562 addr
.sin_family
= AF_INET
;
563 addr
.sin_port
= htons((unsigned short int)in_port
);
564 addr
.sin_addr
.s_addr
= INADDR_ANY
;
566 if (-1 == bind(listen_gdb
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
567 XERROR(errno
, "bind failed\n");
569 TSFPRINTF(stderr
, "listening on port %d ...", in_port
);
570 if (-1 == listen(listen_gdb
, 1)) {
571 XERROR(errno
, "error listen failed\n");
575 gdb_connect
= accept4(listen_gdb
, NULL
, NULL
, SOCK_CLOEXEC
);
577 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
580 if (gdb_connect
< 0) {
581 XERROR(errno
, "accept failed\n");
583 fprintf(stderr
, "connected.\n");
586 from_gdb
= gdb_connect
;
587 to_gdb
= gdb_connect
;
590 /* prepares the FIFOs filenames, map the shared memory. */
592 void prepare_fifos_and_shared_mem(int pid
, int check_trials
)
594 const HChar
*user
, *host
;
597 user
= getenv("LOGNAME");
598 if (user
== NULL
) user
= getenv("USER");
599 if (user
== NULL
) user
= "???";
600 if (strchr(user
, '/')) user
= "???";
602 host
= getenv("HOST");
603 if (host
== NULL
) host
= getenv("HOSTNAME");
604 if (host
== NULL
) host
= "???";
605 if (strchr(host
, '/')) host
= "???";
607 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
608 from_gdb_to_pid
= vmalloc(len
);
609 to_gdb_from_pid
= vmalloc(len
);
610 shared_mem
= vmalloc(len
);
611 /* below 3 lines must match the equivalent in remote-utils.c */
612 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
614 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
616 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
618 DEBUG(1, "vgdb: using %s %s %s\n",
619 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
621 map_vgdbshared(shared_mem
, check_trials
);
625 cleanup_fifos_and_shared_mem(void)
627 free(from_gdb_to_pid
);
628 free(to_gdb_from_pid
);
630 close(shared_mem_fd
);
633 /* Convert hex digit A to a number. */
638 if (a
>= '0' && a
<= '9')
640 else if (a
>= 'a' && a
<= 'f')
643 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
647 /* Returns next char from fd. -1 if error, -2 if EOF.
648 NB: must always call it with the same fd */
652 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
653 static int bufcnt
= 0;
654 static unsigned char *bufp
;
655 // unsigned bufp to e.g. avoid having 255 converted to int -1
660 bufcnt
= read_buf(fd
, buf
, "static buf readchar");
664 TSFPRINTF(stderr
, "readchar: Got EOF\n");
667 ERROR(errno
, "readchar\n");
672 bufp
= (unsigned char *)buf
;
677 /* Read a packet from fromfd, with error checking,
679 If checksum incorrect, writes a - on ackfd.
680 Returns length of packet, or -1 if error or -2 if EOF. */
682 getpkt(char *buf
, int fromfd
, int ackfd
)
685 unsigned char csum
, c1
, c2
;
692 c
= readchar(fromfd
);
695 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
702 c
= readchar(fromfd
);
713 repeat
= readchar(fromfd
);
715 for (r
= 0; r
< repeat
- 29; r
++)
724 c1
= fromhex(readchar (fromfd
));
725 c2
= fromhex(readchar (fromfd
));
727 if (csum
== (c1
<< 4) + c2
)
730 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
731 (c1
<< 4) + c2
, csum
, buf
);
732 if (write(ackfd
, "-", 1) != 1)
733 ERROR(errno
, "error when writing - (nack)\n");
738 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
742 static int sigint
= 0;
743 static int sigterm
= 0;
744 static int sigpipe
= 0;
745 static int sighup
= 0;
746 static int sigusr1
= 0;
747 static int sigalrm
= 0;
748 static int sigusr1_fd
= -1;
749 static pthread_t invoke_gdbserver_in_valgrind_thread
;
752 void received_signal(int signum
)
754 if (signum
== SIGINT
)
756 else if (signum
== SIGUSR1
) {
758 if (sigusr1_fd
>= 0) {
759 char control_c
= '\003';
760 write_buf(sigusr1_fd
, &control_c
, 1,
761 "write \\003 on SIGUSR1", /* notify */ True
);
764 else if (signum
== SIGTERM
) {
765 shutting_down
= True
;
767 } else if (signum
== SIGHUP
) {
768 shutting_down
= True
;
770 } else if (signum
== SIGPIPE
) {
772 } else if (signum
== SIGALRM
) {
774 #if defined(VGPV_arm_linux_android) \
775 || defined(VGPV_x86_linux_android) \
776 || defined(VGPV_mips32_linux_android) \
777 || defined(VGPV_arm64_linux_android)
778 /* Android has no pthread_cancel. As it also does not have
779 an invoker implementation, there is no need for cleanup action.
780 So, we just do nothing. */
781 DEBUG(1, "sigalrm received, no action on android\n");
783 /* Note: we cannot directly invoke restore_and_detach : this must
784 be done by the thread that has attached.
785 We have in this thread pushed a cleanup handler that will
786 cleanup what is needed. */
787 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
788 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
791 ERROR(0, "unexpected signal %d\n", signum
);
795 /* install the signal handlers allowing e.g. vgdb to cleanup in
796 case of termination. */
798 void install_handlers(void)
800 struct sigaction action
, oldaction
;
802 action
.sa_handler
= received_signal
;
803 sigemptyset(&action
.sa_mask
);
806 /* SIGINT: when user types C-c in gdb, this sends
807 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
808 The later is enough to wakeup the valgrind process. */
809 if (sigaction(SIGINT
, &action
, &oldaction
) != 0)
810 XERROR(errno
, "vgdb error sigaction SIGINT\n");
811 /* We might do something more intelligent than just
812 reporting this SIGINT E.g. behave similarly to the gdb: two
813 control-C without feedback from the debugged process would
814 mean to stop debugging it. */
816 /* SIGUSR1: this is used to facilitate automatic testing. When
817 vgdb receives this signal, it will simulate the user typing C-c. */
818 if (sigaction(SIGUSR1
, &action
, &oldaction
) != 0)
819 XERROR(errno
, "vgdb error sigaction SIGUSR1\n");
822 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
823 when detaching or similar. A clean shutdown will be done as both
824 the read and write side will detect an end of file. */
825 if (sigaction(SIGTERM
, &action
, &oldaction
) != 0)
826 XERROR(errno
, "vgdb error sigaction SIGTERM\n");
828 /* SIGPIPE: can receive this signal when gdb detaches or kill the
829 process debugged: gdb will close its pipes to vgdb. vgdb
830 must resist to this signal to allow a clean shutdown. */
831 if (sigaction(SIGPIPE
, &action
, &oldaction
) != 0)
832 XERROR(errno
, "vgdb error sigaction SIGPIPE\n");
834 /* SIGALRM: in case invoke thread is blocked, alarm is used
836 if (sigaction(SIGALRM
, &action
, &oldaction
) != 0)
837 XERROR(errno
, "vgdb error sigaction SIGALRM\n");
839 /* unmask all signals, in case the process that launched vgdb
841 if (sigprocmask(SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
842 XERROR(errno
, "vgdb error sigprocmask\n");
845 /* close the FIFOs provided connections, terminate the invoker thread. */
847 void close_connection(int to_pid
, int from_pid
)
849 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
850 sigint
, sigterm
, sighup
, sigpipe
);
851 /* Note that we do not forward sigterm to the valgrind process:
852 a sigterm signal is (probably) received from gdb if the user wants to
853 kill the debugged process. The kill instruction has been given to
854 the valgrind process, which should execute a clean exit. */
856 /* We first close the connection to pid. The pid will then
857 terminates its gdbserver work. We keep the from pid
858 fifo opened till the invoker thread is finished.
859 This allows the gdbserver to finish sending its last reply. */
860 if (close(to_pid
) != 0)
861 ERROR(errno
, "close to_pid\n");
863 /* if there is a task that was busy trying to wake up valgrind
864 process, we wait for it to be terminated otherwise threads
865 in the valgrind process can stay stopped if vgdb main
866 exits before the invoke thread had time to detach from
867 all valgrind threads. */
868 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
871 /* It is surprisingly complex to properly shutdown or exit the
872 valgrind process in which gdbserver has been invoked through
873 ptrace. In the normal case (gdb detaches from the process,
874 or process is continued), the valgrind process will reach the
875 breakpoint place. Using ptrace, vgdb will ensure the
876 previous activity of the process is resumed (e.g. restart a
877 blocking system call). The special case is when gdb asks the
878 valgrind process to exit (using either the "kill" command or
879 "monitor exit"). In such a case, the valgrind process will
880 call exit. But a ptraced process will be blocked in exit,
881 waiting for the ptracing process to detach or die. vgdb
882 cannot detach unconditionally as otherwise, in the normal
883 case, the valgrind process would stop abnormally with SIGSTOP
884 (as vgdb would not be there to catch it). vgdb can also not
885 die unconditionally otherwise again, similar problem. So, we
886 assume that most of the time, we arrive here in the normal
887 case, and so, the breakpoint has been encountered by the
888 valgrind process, so the invoker thread will exit and the
889 join will succeed. For the "kill" case, we cause an alarm
890 signal to be sent after a few seconds. This means that in the
891 normal case, the gdbserver code in valgrind process must have
892 returned the control in less than the alarm nr of seconds,
893 otherwise, valgrind will stop abnormally with SIGSTOP. */
896 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
897 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
901 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
903 #if !defined(VGO_freebsd)
904 if (close(from_pid
) != 0)
905 ERROR(errno
, "close from_pid\n");
909 /* Returns an allocated hex-decoded string from the buf. Stops decoding
910 at end of buf (zero) or when seeing the delim char. */
912 char *decode_hexstring (const char *buf
, size_t prefixlen
, size_t len
)
920 buflen
= strlen(buf
) - prefixlen
;
922 buf_print
= vmalloc (buflen
/2 + 1);
924 for (int i
= 0; i
< buflen
; i
= i
+ 2) {
925 buf_print
[i
/2] = ((fromhex(buf
[i
+prefixlen
]) << 4)
926 + fromhex(buf
[i
+prefixlen
+1]));
928 buf_print
[buflen
/2] = '\0';
929 DEBUG(1, "decode_hexstring: %s\n", buf_print
);
934 write_to_gdb (const char *m
, int cnt
)
937 while (written
< cnt
) {
938 int res
= write (to_gdb
, m
+ written
, cnt
- written
);
940 perror ("write_to_gdb");
950 write_checksum (const char *str
)
952 unsigned char csum
= 0;
958 p
[0] = tohex ((csum
>> 4) & 0x0f);
959 p
[1] = tohex (csum
& 0x0f);
960 return write_to_gdb (p
, 2);
964 write_reply(const char *reply
)
966 write_to_gdb ("$", 1);
967 write_to_gdb (reply
, strlen (reply
));
968 write_to_gdb ("#", 1);
969 return write_checksum (reply
);
972 /* Creates a packet from a string message, caller needs to free. */
974 create_packet(const char *msg
)
976 unsigned char csum
= 0;
978 char *p
= vmalloc (strlen (msg
) + 5); /* $ + msg + # + hexhex + 0 */
984 p
[i
++] = tohex ((csum
>> 4) & 0x0f);
985 p
[i
++] = tohex (csum
& 0x0f);
990 static int read_one_char (char *c
)
994 i
= read (from_gdb
, c
, 1);
995 while (i
== -1 && errno
== EINTR
);
1001 send_packet(const char *reply
, int noackmode
)
1007 if (!write_reply(reply
))
1010 // Look for '+' or '-'.
1011 // We must wait for "+" if !noackmode.
1013 ret
= read_one_char(&c
);
1016 // And if in !noackmode if we get "-" we should resent the packet.
1018 goto send_packet_start
;
1020 DEBUG(1, "sent packet to gdb got: %c\n",c
);
1025 // Reads one packet from_gdb starting with $ into buf.
1026 // Skipping any other characters.
1027 // Returns the size of the packet, 0 for end of input,
1028 // or -1 if no packet could be read.
1029 static int receive_packet(char *buf
, int noackmode
)
1036 unsigned char csum
= 0;
1038 // Look for first '$' (start of packet) or error.
1039 receive_packet_start
:
1041 ret
= read_one_char(&c
);
1046 // Found start of packet ('$')
1047 while (bufcnt
< (PBUFSIZ
+1)) {
1048 ret
= read_one_char(&c
);
1052 if ((ret
= read_one_char(&c1
)) <= 0
1053 || (ret
= read_one_char(&c2
)) <= 0) {
1061 csum
+= buf
[bufcnt
];
1065 // Packet complete, add terminator.
1068 if (!(csum
== (c1
<< 4) + c2
)) {
1069 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1070 (c1
<< 4) + c2
, csum
, buf
);
1072 if (!write_to_gdb ("-", 1))
1074 /* Try again, gdb should resend the packet. */
1077 goto receive_packet_start
;
1081 if (!write_to_gdb ("+", 1))
1086 // Returns a pointer to the char after the next delim char.
1087 static const char *next_delim_string (const char *buf
, char delim
)
1090 if (*buf
++ == delim
)
1096 /* buf starts with the packet name followed by the delimiter, for example
1097 * vRun;2f62696e2f6c73, ";" is the delimiter here, or
1098 * qXfer:features:read:target.xml:0,1000, where the delimiter is ":".
1099 * The packet name is thrown away and the hex string is decoded and
1100 * is placed in decoded_string (the caller owns this and is responsible
1101 * for freeing it). */
1102 static int split_hexdecode(const char *buf
, const char *string
,
1103 const char *delim
, char **decoded_string
)
1105 const char *next_str
= next_delim_string(buf
, *delim
);
1107 *decoded_string
= decode_hexstring (next_str
, 0, 0);
1108 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string
);
1111 TSFPRINTF(stderr
, "%s decoding error: finding the hex string in %s failed!\n", string
, buf
);
1116 static size_t count_delims(char delim
, char *buf
)
1122 count
+= *ptr
++ == delim
;
1126 // Determine the length of the arguments.
1127 // This depends on the len array being initialized to -1 for each element.
1128 // We first skip the command (e.g. vRun;arg0;arg1)
1129 static void count_len(char delim
, char *buf
, size_t *len
)
1135 while (*ptr
&& *ptr
!= delim
)
1138 // Delimiter counts towards the first arg0
1139 if (*ptr
== delim
) {
1144 // For each arg0... count chars (delim counts towards next arg)
1146 i
+= *ptr
++ == delim
;
1151 /* early_exit guesses if vgdb speaks with GDB by checking from_gdb is a FIFO
1152 (as GDB is likely the only program that would write data to vgdb stdin).
1153 If not speaking with GDB, early_exit will just call exit(exit_code).
1154 If speaking with GDB, early_exit will ensure the GDB user sees
1155 the error messages produced by vgdb:
1156 early_exit should be used when vgdb exits due to an early error i.e.
1157 error during arg processing, before it could succesfully process the
1158 first packet from GDB.
1159 early_exit will then read the first packet send by GDB (i.e.
1160 the qSupported packet) and will reply to it with an error and then exit.
1161 This should ensure the vgdb error messages are made visible to the user. */
1162 static void early_exit (int exit_code
, const char* exit_info
)
1164 char buf
[PBUFSIZ
+1];
1168 if (fstat(from_gdb
, &fdstat
) != 0)
1169 XERROR(errno
, "fstat\n");
1171 DEBUG(1, "early_exit %s ISFIFO %d\n", exit_info
, S_ISFIFO(fdstat
.st_mode
));
1173 if (S_ISFIFO(fdstat
.st_mode
)) {
1174 /* We assume that we speak with GDB when stdin is a FIFO, so we expect
1175 to get a first packet from GDB. This should ensure the vgdb messages
1176 are made visible. In case the whole stuff is blocked for any reason or
1177 GDB does not send a package or ..., schedule an alarm to exit in max 5
1180 pkt_size
= receive_packet(buf
, 0);
1182 DEBUG(1, "early_exit receive_packet: %d\n", pkt_size
);
1184 DEBUG(1, "packet received: '%s'\n", buf
);
1185 sprintf(buf
, "E.%s", exit_info
);
1186 send_packet(buf
, 0);
1191 DEBUG(1, "early_exit exiting %d\n", exit_code
);
1195 /* Declare here, will be used early, implementation follows later. */
1196 static void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
);
1198 /* Returns zero on success (and the pid of the valgrind process),
1199 or the errno from the child on failure. */
1201 int fork_and_exec_valgrind (int argc
, char **argv
, const char *working_dir
,
1202 int in_port
, pid_t
*pid
)
1205 // We will use a pipe to track what the child does,
1206 // so we can report failure.
1209 if (pipe2 (pipefd
, O_CLOEXEC
) == -1) {
1211 perror ("pipe2 failed");
1215 if (pipe (pipefd
) == -1) {
1217 perror ("pipe failed");
1220 if (fcntl (pipefd
[0], F_SETFD
, FD_CLOEXEC
) == -1
1221 || fcntl (pipefd
[1], F_SETFD
, FD_CLOEXEC
) == -1) {
1223 perror ("fcntl failed");
1234 perror ("fork failed");
1237 // I am the parent (vgdb), p is the pid of the child (valgrind)
1238 // We only read from the child to see if everything is OK.
1239 // If the pipe closes, we get zero back, which is good.
1240 // An error reading the pipe is bad (and really shouldn't happen).
1241 // Otherwise the child sent us an errno code about what went wrong.
1245 int r
= read (pipefd
[0], &err
, sizeof (int));
1246 if (r
== 0) // end of file, good pipe closed after execve
1253 perror ("pipe read");
1266 // p == 0, I am the child (will start valgrind)
1267 // We write success to the pipe, no need to read from it.
1270 if (working_dir
!= NULL
&& working_dir
[0] != '\0') {
1271 if (chdir (working_dir
) != 0) {
1274 // We try to write the result to the parent, but always exit.
1276 while (written
< sizeof (int)) {
1277 int nrw
= write (pipefd
[1], &err
, sizeof (int) - written
);
1286 /* When in stdio mode (talking to gdb through stdin/stdout, not
1287 through a socket), redirect stdout to stderr and close stdin
1288 for the inferior. That way at least some output can be seen,
1289 but there will be no input. */
1293 /* open /dev/null as new stdin */
1294 (void)open ("/dev/null", O_RDONLY
);
1295 /* redirect stdout as stderr */
1299 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1300 can attach and --launched-with-multi to let valgrind know it doesn't
1301 need to show a banner how to connect to gdb, we will do that
1302 automagically. And add --vgdb-shadow-registers=yes to make shadow
1303 registers available by default. Add any other valgrind arguments the
1304 user gave with --vargs. Then the rest of the arguments to valgrind are
1305 the program to exec plus its arguments. */
1306 const int extra_vargs
= 3;
1307 /* vargv[0] == "valgrind",
1308 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1309 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1310 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1311 vargs[arguments - 1] = NULL */
1312 int arguments
= 1 + extra_vargs
+ cvargs
+ argc
+ 1;
1313 // We combine const and non-const char[]. This is mildly annoying
1314 // since we then need a char *const * for execvp. So we strdup the
1315 // const char*. Not pretty :{
1316 char **vargv
= vmalloc (arguments
* sizeof (char *));
1317 vargv
[0] = strdup ("valgrind");
1318 vargv
[1] = strdup ("--vgdb-error=0");
1319 vargv
[2] = strdup ("--launched-with-multi=yes");
1320 vargv
[3] = strdup ("--vgdb-shadow-registers=yes");
1322 for (int i
= 0; i
< cvargs
; i
++) {
1323 vargv
[i
+ extra_vargs
+ 1] = vargs
[i
];
1325 // Add command and args
1326 for (int i
= 0; i
< argc
; i
++) {
1327 vargv
[i
+ extra_vargs
+ 1 + cvargs
] = argv
[i
];
1329 vargv
[arguments
- 1] = NULL
;
1331 if (!valgrind_path
) {
1332 // TODO use execvpe (or something else if not on GNU/Linux
1333 /* We want to make a copy of the environ on start. When we
1334 get a QEnvironmentReset we copy that back. If we get an
1335 EvironSet/Add/Remove we update the copy. */
1336 execvp ("valgrind", vargv
);
1339 vargv
[0] = valgrind_path
;
1340 execvp (vargv
[0], vargv
);
1343 // We really shouldn't get here...
1345 /* Note we are after fork and exec failed, we cannot really call
1346 perror or printf in this situation since they aren't async-safe. */
1347 // perror ("execvp valgrind");
1348 // printf ("execve returned??? confusing: %d\n", res);
1349 // We try to write the result to the parent, but always exit.
1351 while (written
< sizeof (int)) {
1352 int nrw
= write (pipefd
[1], &err
, sizeof (int) - written
);
1360 abort (); // Impossible
1363 /* Do multi stuff. */
1365 void do_multi_mode(int check_trials
, int in_port
)
1367 char *buf
= vmalloc(PBUFSIZ
+1);
1368 char *q_buf
= vmalloc(PBUFSIZ
+1); //save the qSupported packet sent by gdb
1369 //to send it to the valgrind gdbserver later
1371 int noackmode
= 0, pkt_size
= 0, bad_unknown_packets
= 0;
1372 char *string
= NULL
;
1373 char *working_dir
= NULL
;
1374 DEBUG(1, "doing multi stuff...\n");
1376 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1378 pkt_size
= receive_packet(buf
, noackmode
);
1379 if (pkt_size
<= 0) {
1380 DEBUG(1, "receive_packet: %d\n", pkt_size
);
1384 DEBUG(1, "packet received: '%s'\n", buf
);
1386 #define QSUPPORTED "qSupported:"
1387 #define STARTNOACKMODE "QStartNoAckMode"
1388 #define QRCMD "qRcmd" // This is the monitor command in gdb
1390 #define XFER "qXfer"
1391 #define QATTACHED "qAttached"
1392 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1393 #define QENVIRONMENTRESET "QEnvironmentReset"
1394 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1395 #define QSETWORKINGDIR "QSetWorkingDir"
1396 #define QTSTATUS "qTStatus"
1398 if (strncmp(QSUPPORTED
, buf
, strlen(QSUPPORTED
)) == 0) {
1399 DEBUG(1, "CASE %s\n", QSUPPORTED
);
1400 // And here is our reply.
1401 // XXX error handling? We don't check the arguments.
1404 // Keep this in sync with coregrind/m_gdbserver/server.c
1405 if (asprintf (&reply
,
1410 /* Just report support always. */
1412 /* We'll force --vgdb-shadow-registers=yes */
1413 "qXfer:features:read+;"
1414 "qXfer:exec-file:read+;"
1415 "qXfer:siginfo:read+;"
1416 /* Extra vgdb support before valgrind starts up. */
1417 "QEnvironmentHexEncoded+;"
1418 "QEnvironmentReset+;"
1419 "QEnvironmentUnset+;"
1420 "QSetWorkingDir+", (UInt
)PBUFSIZ
- 1) != -1) {
1421 send_packet(reply
, noackmode
);
1424 XERROR(errno
, "asprintf failed\n");
1427 else if (strncmp(STARTNOACKMODE
, buf
, strlen(STARTNOACKMODE
)) == 0) {
1428 // We have to ack this one
1429 send_packet("OK", 0);
1432 else if (buf
[0] == '!') {
1433 send_packet("OK", noackmode
);
1435 else if (buf
[0] == '?') {
1436 send_packet("W00", noackmode
);
1438 else if (strncmp("H", buf
, strlen("H")) == 0) {
1439 // Set thread packet, but we are not running yet.
1440 send_packet("E01", noackmode
);
1442 else if (strncmp("vMustReplyEmpty", buf
, strlen("vMustReplyEmpty")) == 0) {
1443 send_packet ("", noackmode
);
1445 else if (strncmp(QRCMD
, buf
, strlen(QRCMD
)) == 0) {
1446 static const char *no_running_str
=
1447 "No running target, monitor commands not available yet.\n";
1448 int str_count
= strlen (no_running_str
);
1449 char hex
[2 * str_count
+ 1];
1450 hexify(hex
, no_running_str
, str_count
);
1451 send_packet(hex
, noackmode
);
1453 char *decoded_string
= decode_hexstring (buf
, strlen (QRCMD
) + 1, 0);
1454 DEBUG(1, "qRcmd decoded: %s\n", decoded_string
);
1455 free (decoded_string
);
1457 else if (strncmp(VRUN
, buf
, strlen(VRUN
)) == 0) {
1458 // vRun;filename[;argument]*
1459 // vRun, filename and arguments are split on ';',
1460 // no ';' at the end.
1461 // If there are no arguments count is one (just the filename).
1462 // Otherwise it is the number of arguments plus one (the filename).
1463 // The filename must be there and starts after the first ';'.
1464 // TODO: Handle vRun;[;argument]*
1465 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1466 // If filename is an empty string, the stub may use a default program
1467 // (e.g. the last program run).
1468 size_t count
= count_delims(';', buf
);
1469 size_t *len
= vmalloc(count
* sizeof(count
));
1470 const char *delim
= ";";
1471 const char *next_str
= next_delim_string(buf
, *delim
);
1472 char **decoded_string
= vmalloc(count
* sizeof (char *));
1474 // Count the lenghts of each substring, init to -1 to compensate for
1475 // each substring starting with a delim char.
1476 for (size_t i
= 0; i
< count
; i
++)
1478 count_len(';', buf
, len
);
1480 DEBUG(1, "vRun: next_str %s\n", next_str
);
1481 for (size_t i
= 0; i
< count
; i
++) {
1482 /* Handle the case when the arguments
1483 * was specified to gdb's run command
1484 * but no remote exec-file was set,
1485 * so the first vRun argument is missing.
1486 * For example vRun;;6c. */
1487 if (*next_str
== *delim
) {
1489 /* empty string that can be freed. */
1490 decoded_string
[i
] = strdup("");
1493 decoded_string
[i
] = decode_hexstring (next_str
, 0, len
[i
]);
1495 next_str
= next_delim_string(next_str
, *delim
);
1497 DEBUG(1, "vRun decoded: %s, next_str %s, len[%zu] %zu\n",
1498 decoded_string
[i
], next_str
, i
, len
[i
]);
1501 /* If we didn't get any arguments or the filename is an empty
1502 string, valgrind won't know which program to run. */
1503 DEBUG (1, "count: %zu, len[0]: %zu\n", count
, len
[0]);
1504 if (! count
|| len
[0] == 0) {
1506 for (size_t i
= 0; i
< count
; i
++)
1507 free (decoded_string
[i
]);
1508 free (decoded_string
);
1509 send_packet ("E01", noackmode
);
1513 /* We have collected the decoded strings so we can use them to
1514 launch valgrind with the correct arguments... We then use the
1515 valgrind pid to start relaying packets. */
1516 pid_t valgrind_pid
= -1;
1517 int res
= fork_and_exec_valgrind ((int)count
,
1524 // Lets report we Stopped with SIGTRAP (05).
1525 send_packet ("S05", noackmode
);
1526 prepare_fifos_and_shared_mem(valgrind_pid
, check_trials
);
1527 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n",
1528 from_gdb_to_pid
, to_gdb_from_pid
);
1529 // gdb_relay is an endless loop till valgrind quits.
1530 shutting_down
= False
;
1532 gdb_relay (valgrind_pid
, 1, q_buf
);
1533 cleanup_fifos_and_shared_mem();
1534 DEBUG(1, "valgrind relay done\n");
1536 pid_t p
= waitpid (valgrind_pid
, &status
, 0);
1537 DEBUG(2, "waitpid: %d\n", (int) p
);
1539 DEBUG(1, "waitpid error %s\n", strerror (errno
));
1541 if (WIFEXITED(status
))
1542 DEBUG(1, "valgrind exited with %d\n",
1543 WEXITSTATUS(status
));
1544 else if (WIFSIGNALED(status
))
1545 DEBUG(1, "valgrind kill by signal %d\n",
1548 DEBUG(1, "valgrind unexpectedly stopped or continued");
1551 send_packet ("E01", noackmode
);
1552 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1557 for (int i
= 0; i
< count
; i
++)
1558 free (decoded_string
[i
]);
1559 free (decoded_string
);
1562 send_packet ("E01", noackmode
);
1563 DEBUG(1, "vRun decoding error: no next_string!\n");
1566 } else if (strncmp(QATTACHED
, buf
, strlen(QATTACHED
)) == 0) {
1567 send_packet ("1", noackmode
);
1568 DEBUG(1, "qAttached sent: '1'\n");
1569 const char *next_str
= next_delim_string(buf
, ':');
1571 char *decoded_string
= decode_hexstring (next_str
, 0, 0);
1572 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string
, next_str
);
1573 free (decoded_string
);
1575 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf
);
1578 } /* Reset the state of environment variables in the remote target
1579 before starting the inferior. In this context, reset means
1580 unsetting all environment variables that were previously set
1581 by the user (i.e., were not initially present in the environment). */
1582 else if (strncmp(QENVIRONMENTRESET
, buf
,
1583 strlen(QENVIRONMENTRESET
)) == 0) {
1584 send_packet ("OK", noackmode
);
1585 // TODO clear all environment strings. We're not using
1586 // environment strings now. But we should.
1587 } else if (strncmp(QENVIRONMENTHEXENCODED
, buf
,
1588 strlen(QENVIRONMENTHEXENCODED
)) == 0) {
1589 send_packet ("OK", noackmode
);
1590 if (!split_hexdecode(buf
, QENVIRONMENTHEXENCODED
, ":", &string
))
1592 // TODO Collect all environment strings and add them to environ
1593 // before launching valgrind.
1596 } else if (strncmp(QENVIRONMENTUNSET
, buf
,
1597 strlen(QENVIRONMENTUNSET
)) == 0) {
1598 send_packet ("OK", noackmode
);
1599 if (!split_hexdecode(buf
, QENVIRONMENTUNSET
, ":", &string
))
1601 // TODO Remove this environment string from the collection.
1604 } else if (strncmp(QSETWORKINGDIR
, buf
,
1605 strlen(QSETWORKINGDIR
)) == 0) {
1606 // Silly, but we can only reply OK, even if the working directory is
1607 // bad. Errors will be reported when we try to execute the actual
1609 send_packet ("OK", noackmode
);
1610 // Free any previously set working_dir
1613 if (!split_hexdecode(buf
, QSETWORKINGDIR
, ":", &working_dir
)) {
1614 continue; // We cannot report the error to gdb...
1616 DEBUG(1, "set working dir to: %s\n", working_dir
);
1617 } else if (strncmp(XFER
, buf
, strlen(XFER
)) == 0) {
1618 char *buf_dup
= strdup(buf
);
1619 DEBUG(1, "strdup: buf_dup %s\n", buf_dup
);
1621 const char *delim
= ":";
1622 size_t count
= count_delims(delim
[0], buf
);
1624 strsep(&buf_dup
, delim
);
1625 strsep(&buf_dup
, delim
);
1626 strsep(&buf_dup
, delim
);
1627 char *decoded_string
= decode_hexstring (buf_dup
, 0, 0);
1628 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string
, buf_dup
);
1629 free (decoded_string
);
1633 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf
);
1637 // Whether we could decode it or not, we cannot handle it now. We
1638 // need valgrind gdbserver to properly reply. So error out here.
1639 send_packet ("E00", noackmode
);
1640 } else if (strncmp(QTSTATUS
, buf
, strlen(QTSTATUS
)) == 0) {
1641 // We don't support trace experiments
1642 DEBUG(1, "Got QTSTATUS\n");
1643 send_packet ("", noackmode
);
1644 } else if (strcmp("qfThreadInfo", buf
) == 0) {
1645 DEBUG(1, "Got qfThreadInfo\n");
1646 /* There are no threads yet, reply 'l' end of list. */
1647 send_packet ("l", noackmode
);
1648 } else if (buf
[0] != '\0') {
1649 // We didn't understand.
1650 DEBUG(1, "Unknown packet received: '%s'\n", buf
);
1651 bad_unknown_packets
++;
1652 if (bad_unknown_packets
> 10) {
1653 DEBUG(1, "Too many bad/unknown packets received\n");
1656 send_packet ("", noackmode
);
1659 DEBUG(1, "done doing multi stuff...\n");
1664 shutting_down
= True
;
1669 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1670 encountered. q_buf is the qSupported packet received from gdb. */
1672 void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
)
1674 int from_pid
= -1; /* fd to read from pid */
1675 int to_pid
= -1; /* fd to write to pid */
1677 int shutdown_loop
= 0;
1678 TSFPRINTF(stderr
, "relaying data between gdb and process %d\n", pid
);
1680 if (max_invoke_ms
> 0)
1681 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1682 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1683 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1684 acquire_lock(shared_mem_fd
, pid
);
1686 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
1687 "read mode from pid");
1689 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
1691 Bool waiting_for_noack_mode
= False
;
1692 Bool waiting_for_qsupported
= False
;
1693 if(send_noack_mode
) {
1694 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid
, from_pid
);
1695 write_buf(to_pid
, "$QStartNoAckMode#b0", 19,
1696 "write start no ack mode",
1698 waiting_for_noack_mode
= True
;
1704 struct pollfd pollfds
[NumConnectionKind
];
1706 /* watch data written by gdb, watch POLLERR on both gdb fd */
1707 pollfds
[FROM_GDB
].fd
= from_gdb
;
1708 pollfds
[FROM_GDB
].events
= POLLIN
;
1709 pollfds
[FROM_GDB
].revents
= 0;
1710 pollfds
[TO_GDB
].fd
= to_gdb
;
1711 pollfds
[TO_GDB
].events
= 0;
1712 pollfds
[TO_GDB
].revents
= 0;
1714 /* watch data written by pid, watch POLLERR on both pid fd */
1715 pollfds
[FROM_PID
].fd
= from_pid
;
1716 pollfds
[FROM_PID
].events
= POLLIN
;
1717 pollfds
[FROM_PID
].revents
= 0;
1718 pollfds
[TO_PID
].fd
= to_pid
;
1719 pollfds
[TO_PID
].events
= 0;
1720 pollfds
[TO_PID
].revents
= 0;
1726 : -1 /* infinite */));
1727 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
1729 /* check for unexpected error */
1730 if (ret
<= 0 && errno
!= EINTR
) {
1731 ERROR(errno
, "unexpected poll ret %d\n", ret
);
1732 shutting_down
= True
;
1736 /* check for data to read */
1737 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1738 if (pollfds
[ck
].revents
& POLLIN
) {
1741 if (waiting_for_noack_mode
|| waiting_for_qsupported
)
1742 break; /* Don't add any messages while vgdb is talking. */
1743 if (!read_from_gdb_write_to_pid(to_pid
))
1744 shutting_down
= True
;
1747 // First handle any messages from vgdb
1748 if (waiting_for_noack_mode
) {
1749 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1751 buflen
= getpkt(buf
, from_pid
, to_pid
);
1752 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1754 ERROR(0, "no ack mode: unexpected buflen %zu, buf %s\n",
1757 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1759 waiting_for_noack_mode
= False
;
1761 /* Propagate qSupported to valgrind, we already replied. */
1762 if (q_buf
!= NULL
&& q_buf
[0] != '\0') {
1763 char *pkt
= create_packet (q_buf
);
1764 write_buf(to_pid
, pkt
, strlen(pkt
),
1765 "write qSupported", /* notify */ True
);
1767 waiting_for_qsupported
= True
;
1769 } else if (waiting_for_qsupported
) {
1770 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1772 buflen
= getpkt(buf
, from_pid
, to_pid
);
1773 /* Should we sanity check the result? */
1775 waiting_for_qsupported
= False
;
1777 ERROR(0, "Unexpected getpkt for qSupported reply: %zu\n",
1780 } else if (!read_from_pid_write_to_gdb(from_pid
))
1781 shutting_down
= True
;
1783 default: XERROR(0, "unexpected POLLIN on %s\n",
1784 ppConnectionKind(ck
));
1789 /* check for an fd being in error condition */
1790 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1791 if (pollfds
[ck
].revents
& POLLERR
) {
1792 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1793 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1794 invoker_valgrind_dying();
1795 shutting_down
= True
;
1797 if (pollfds
[ck
].revents
& POLLHUP
) {
1798 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1799 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1800 invoker_valgrind_dying();
1801 shutting_down
= True
;
1803 if (pollfds
[ck
].revents
& POLLNVAL
) {
1804 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1805 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1806 invoker_valgrind_dying();
1807 shutting_down
= True
;
1811 if (shutting_down
) {
1812 /* we let some time to the final packets to be transferred */
1814 if (shutdown_loop
> 3)
1818 close_connection(to_pid
, from_pid
);
1821 static int packet_len_for_command(char *cmd
)
1823 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1824 return 7+ 2*strlen(cmd
) +3 + 1;
1827 /* hyper-minimal protocol implementation that
1828 sends the provided commands (using qRcmd packets)
1829 and read and display their replies. */
1831 void standalone_send_commands(int pid
,
1835 int from_pid
= -1; /* fd to read from pid */
1836 int to_pid
= -1; /* fd to write to pid */
1841 unsigned char cksum
;
1843 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1848 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
1849 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1850 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1852 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1853 acquire_lock(shared_mem_fd
, pid
);
1855 /* first send a C-c \003 to pid, so that it wakes up the process
1856 After that, we can open the fifo from the pid in read mode
1857 We then start to wait for packets (normally first a resume reply)
1858 At that point, we send our command and expect replies */
1861 while (!write_buf(to_pid
, buf
, 1,
1862 "write \\003 to wake up", /* notify */ True
)) {
1863 /* If write fails, retries up to 10 times every 0.5 seconds
1864 This aims at solving the race condition described in
1865 remote-utils.c remote_finish function. */
1869 XERROR(errno
, "failed to send wake up char after 10 trials\n");
1871 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
1872 "read cmd result from pid");
1874 /* Enable no ack mode. */
1875 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1877 buflen
= getpkt(buf
, from_pid
, to_pid
);
1878 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1880 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen
);
1882 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1885 for (nc
= 0; nc
<= last_command
; nc
++) {
1886 TSFPRINTF(stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
1888 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1889 hexcommand
= vmalloc(packet_len_for_command(commands
[nc
]));
1891 strcat(hexcommand
, "$qRcmd,");
1892 for (i
= 0; i
< strlen(commands
[nc
]); i
++) {
1893 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][i
]);
1894 // Need to use unsigned char, to avoid sign extension.
1895 strcat(hexcommand
, hex
);
1897 /* checksum (but without the $) */
1899 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1900 cksum
+=hexcommand
[hi
];
1901 strcat(hexcommand
, "#");
1902 sprintf(hex
, "%02x", cksum
);
1903 strcat(hexcommand
, hex
);
1904 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1905 "writing hex command to pid", /* notify */ True
);
1907 /* we exit of the below loop explicitly when the command has
1908 been handled or because a signal handler will set
1910 while (!shutting_down
) {
1911 buflen
= getpkt(buf
, from_pid
, to_pid
);
1913 ERROR(0, "error reading packet\n");
1915 invoker_valgrind_dying();
1918 if (strlen(buf
) == 0) {
1919 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1922 if (strcmp(buf
, "OK") == 0) {
1923 DEBUG(1, "OK packet rcvd\n");
1926 if (buf
[0] == 'E') {
1928 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1932 if (buf
[0] == 'W') {
1933 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1936 if (buf
[0] == 'T') {
1937 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1941 /* must be here an O packet with hex encoded string reply
1942 => decode and print it */
1943 if (buf
[0] != 'O') {
1944 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1948 char buf_print
[buflen
/2 + 1];
1949 for (i
= 1; i
< buflen
; i
= i
+ 2)
1950 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1951 + fromhex(*(buf
+i
+1));
1952 buf_print
[buflen
/2] = 0;
1953 printf("%s", buf_print
);
1959 shutting_down
= True
;
1961 close_connection(to_pid
, from_pid
);
1964 /* report to user the existence of a vgdb-able valgrind process
1966 Note: this function does not use XERROR if an error is encountered
1967 while producing the command line for pid, as this is not critical
1968 and at least on MacOS, reading cmdline is not available. */
1970 void report_pid(int pid
, Bool on_stdout
)
1972 char cmdline_file
[50]; // large enough
1974 FILE *out
= on_stdout
? stdout
: stderr
;
1976 TSFPRINTF(out
, "use --pid=%d for ", pid
);
1978 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
1979 fd
= open(cmdline_file
, O_RDONLY
| O_CLOEXEC
);
1981 DEBUG(1, "error opening cmdline file %s %s\n",
1982 cmdline_file
, strerror(errno
));
1983 fprintf(out
, "(could not open process command line)\n");
1987 while ((sz
= read(fd
, cmdline
, sizeof cmdline
- 1)) > 0) {
1988 for (i
= 0; i
< sz
; i
++)
1989 if (cmdline
[i
] == 0)
1992 fprintf(out
, "%s", cmdline
);
1995 DEBUG(1, "error reading cmdline file %s %s\n",
1996 cmdline_file
, strerror(errno
));
1997 fprintf(out
, "(error reading process command line)");
2009 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
2010 "vgdb (valgrind gdb) has two usages\n"
2011 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
2012 " The OPTION(s) must be followed by the command to send\n"
2013 " To send more than one command, separate the commands with -c\n"
2014 " 2. relay application between gdb and a Valgrind gdbserver.\n"
2015 " Only OPTION(s) can be given.\n"
2017 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
2018 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
2019 " [--port=<portnr>\n"
2020 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
2021 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
2023 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
2024 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
2025 " if you want to change the prefix (default %s) for the FIFOs communication\n"
2026 " between the Valgrind gdbserver and vgdb.\n"
2027 " --wait (default 0) tells vgdb to check during the specified number\n"
2028 " of seconds if a Valgrind gdbserver can be found.\n"
2029 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
2030 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
2031 " process is blocked in a system call).\n"
2032 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
2033 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
2034 " gdbserver has not processed a command after number seconds\n"
2035 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
2036 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
2037 " --vargs everything that follows is an argument for valgrind.\n"
2038 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
2039 " -T arg tells to add timestamps to vgdb information messages.\n"
2040 " -D arg tells to show shared mem status and then exit.\n"
2041 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
2043 " -h --help shows this message\n"
2044 #ifdef VG_GDBSCRIPTS_DIR
2045 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
2047 " To get help from the Valgrind gdbserver, use vgdb help\n"
2048 "\n", vgdb_prefix_default()
2049 #ifdef VG_GDBSCRIPTS_DIR
2050 , VG_GDBSCRIPTS_DIR
"/valgrind-monitor.py"
2053 invoker_restrictions_msg();
2056 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
2059 else if arg_pid == -1, waits maximum check_trials seconds to discover
2060 a valgrind pid appearing.
2062 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2063 with gdbserver activated.
2065 Returns the pid to work with
2066 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2069 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
2074 if (arg_pid
== 0 || arg_pid
< -1) {
2075 TSFPRINTF(stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
2076 early_exit(1, "vgdb error: invalid pid given");
2078 /* search for a matching named fifo.
2079 If we have been given a pid, we will check that the matching FIFO is
2080 there (or wait the nr of check_trials for this to appear).
2081 If no pid has been given, then if we find only one FIFO,
2082 we will use this to build the pid to use.
2083 If we find multiple processes with valid FIFO, we report them and will
2084 exit with an error. */
2086 char *vgdb_dir_name
= vmalloc(strlen (vgdb_prefix
) + 3);
2089 int nr_valid_pid
= 0;
2090 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
2091 char *vgdb_format
= vmalloc(strlen(vgdb_prefix
) + strlen(suffix
) + 1);
2093 strcpy(vgdb_format
, vgdb_prefix
);
2094 strcat(vgdb_format
, suffix
);
2096 if (strchr(vgdb_prefix
, '/') != NULL
) {
2097 strcpy(vgdb_dir_name
, vgdb_prefix
);
2098 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
2099 if (vgdb_dir_name
[is
] == '/') {
2100 vgdb_dir_name
[is
+1] = '\0';
2104 strcpy(vgdb_dir_name
, "");
2107 DEBUG(1, "searching pid in directory %s format %s\n",
2108 vgdb_dir_name
, vgdb_format
);
2110 /* try to find FIFOs with valid pid.
2111 On exit of the loop, pid is set to:
2112 the last pid found if show_list (or -1 if no process was listed)
2113 -1 if no FIFOs matching a running process is found
2114 -2 if multiple FIFOs of running processes are found
2115 otherwise it is set to the (only) pid found that can be debugged
2117 for (i
= 0; i
< check_trials
; i
++) {
2118 DEBUG(1, "check_trial %d \n", i
);
2120 /* wait one second before checking again */
2123 vgdb_dir
= opendir(strlen(vgdb_dir_name
) ? vgdb_dir_name
: "./");
2124 if (vgdb_dir
== NULL
)
2126 "vgdb error: opening directory %s searching vgdb fifo\n",
2129 errno
= 0; /* avoid complain if vgdb_dir is empty */
2130 while ((f
= readdir(vgdb_dir
))) {
2132 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
2136 strcpy(pathname
, vgdb_dir_name
);
2137 strcat(pathname
, f
->d_name
);
2138 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
2139 if (stat(pathname
, &st
) != 0) {
2140 if (debuglevel
>= 3)
2141 ERROR(errno
, "vgdb error: stat %s searching vgdb fifo\n",
2143 } else if (S_ISFIFO(st
.st_mode
)) {
2144 DEBUG(3, "trying FIFO %s\n", pathname
);
2145 if (strncmp(pathname
, vgdb_format
,
2146 strlen(vgdb_format
)) == 0) {
2147 newpid
= strtol(pathname
+ strlen(vgdb_format
),
2149 if (*wrongpid
== '-' && newpid
> 0
2150 && kill(newpid
, 0) == 0) {
2153 report_pid(newpid
, /*on_stdout*/ True
);
2155 } else if (arg_pid
!= -1) {
2156 if (arg_pid
== newpid
) {
2159 } else if (nr_valid_pid
> 1) {
2160 if (nr_valid_pid
== 2) {
2163 "no --pid= arg given"
2164 " and multiple valgrind pids found:\n");
2165 report_pid(pid
, /*on_stdout*/ False
);
2168 report_pid(newpid
, /*on_stdout*/ False
);
2175 errno
= 0; /* avoid complain if at the end of vgdb_dir */
2177 if (f
== NULL
&& errno
!= 0) {
2178 ERROR(errno
, "vgdb error: reading directory %s for vgdb fifo\n",
2180 early_exit(1, "vgdb error reading vgdb fifo directory");
2188 free(vgdb_dir_name
);
2194 } else if (pid
== -1) {
2195 if (arg_pid
== -1) {
2196 TSFPRINTF(stderr
, "vgdb error: no FIFO found and no pid given\n");
2197 early_exit(1, "vgdb error: no FIFO found and no pid given");
2199 TSFPRINTF(stderr
, "vgdb error: no FIFO found matching pid %d\n",
2201 early_exit(1, "vgdb error: no FIFO found matching the give pid");
2204 else if (pid
== -2) {
2205 early_exit(1, "no --pid= arg_pid given and multiple valgrind pids found.");
2211 abort (); // Impossible
2214 /* return true if the numeric value of an option of the
2215 form --xxxxxxxxx=<number> could properly be extracted
2216 from arg. If True is returned, *value contains the
2219 Bool
numeric_val(char* arg
, int *value
)
2221 const char *eq_pos
= strchr(arg
, '=');
2223 long long int long_value
;
2228 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
2229 if (long_value
< 0 || long_value
> INT_MAX
)
2234 *value
= (int) long_value
;
2238 /* true if arg matches the provided option */
2240 Bool
is_opt(char* arg
, const char *option
)
2242 int option_len
= strlen(option
);
2243 if (option
[option_len
-1] == '=')
2244 return (0 == strncmp(option
, arg
, option_len
));
2246 return (0 == strcmp(option
, arg
));
2249 /* Parse command lines options. If error(s), exits.
2250 Otherwise returns the options in *p_... args.
2251 commands must be big enough for the commands extracted from argv.
2252 On return, *p_last_command gives the position in commands where
2253 the last command has been allocated (using vmalloc). */
2255 void parse_options(int argc
, char** argv
,
2256 Bool
*p_show_shared_mem
,
2260 int *p_check_trials
,
2262 int *p_last_command
,
2265 Bool show_shared_mem
= False
;
2266 Bool show_list
= False
;
2267 Bool multi_mode
= False
;
2269 int check_trials
= 1;
2270 int last_command
= -1;
2276 for (i
= 1; i
< argc
; i
++) {
2277 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
2279 early_exit(0, "--help requested");
2280 } else if (is_opt(argv
[i
], "-d")) {
2282 } else if (is_opt(argv
[i
], "-D")) {
2283 show_shared_mem
= True
;
2284 } else if (is_opt(argv
[i
], "-l")) {
2286 } else if (is_opt(argv
[i
], "--multi")) {
2288 } else if (is_opt(argv
[i
], "-T")) {
2290 } else if (is_opt(argv
[i
], "--pid=")) {
2292 if (!numeric_val(argv
[i
], &newpid
)) {
2293 TSFPRINTF(stderr
, "invalid --pid argument %s\n", argv
[i
]);
2295 } else if (arg_pid
!= -1) {
2296 TSFPRINTF(stderr
, "multiple --pid arguments given\n");
2301 } else if (is_opt(argv
[i
], "--wait=")) {
2302 if (!numeric_val(argv
[i
], &check_trials
)) {
2303 TSFPRINTF(stderr
, "invalid --wait argument %s\n", argv
[i
]);
2306 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
2307 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
2308 TSFPRINTF(stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
2311 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
2312 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
2313 TSFPRINTF(stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
2316 } else if (is_opt(argv
[i
], "--port=")) {
2317 if (!numeric_val(argv
[i
], &int_port
)) {
2318 TSFPRINTF(stderr
, "invalid --port argument %s\n", argv
[i
]);
2321 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
2323 // was specified more than once on the command line
2324 // ignore earlier uses
2327 vgdb_prefix
= strdup (argv
[i
] + 14);
2328 } else if (is_opt(argv
[i
], "--valgrind=")) {
2329 char *path
= argv
[i
] + 11;
2330 /* Compute the absolute path. */
2331 valgrind_path
= realpath(path
, NULL
);
2332 if (!valgrind_path
) {
2333 TSFPRINTF(stderr
, "%s is not a correct path. %s, exiting.\n",
2334 path
, strerror (errno
));
2335 early_exit(1, "incorrect valgrind path");
2337 DEBUG(2, "valgrind's real path: %s\n", valgrind_path
);
2338 } else if (is_opt(argv
[i
], "--vargs")) {
2339 // Everything that follows now is an argument for valgrind
2340 // No other options (or commands) can follow
2341 // argc - i is the number of left over arguments
2342 // allocate enough space, put all args in it.
2343 cvargs
= argc
- i
- 1;
2344 vargs
= vmalloc (cvargs
* sizeof(*vargs
));
2346 for (int j
= 0; i
< argc
; i
++) {
2350 } else if (is_opt(argv
[i
], "-c")) {
2352 commands
[last_command
] = vmalloc(1);
2353 commands
[last_command
][0] = '\0';
2354 } else if (0 == strncmp(argv
[i
], "-", 1)) {
2355 TSFPRINTF(stderr
, "unknown or invalid argument %s\n", argv
[i
]);
2359 if (last_command
== -1) {
2360 /* only one command, no -c command indicator */
2362 commands
[last_command
] = vmalloc(1);
2363 commands
[last_command
][0] = '\0';
2365 len
= strlen(commands
[last_command
]);
2366 commands
[last_command
] = vrealloc(commands
[last_command
],
2367 len
+ 1 + strlen(argv
[i
]) + 1);
2369 strcat(commands
[last_command
], " ");
2370 strcat(commands
[last_command
], argv
[i
]);
2371 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
2372 TSFPRINTF(stderr
, "command %s too long\n", commands
[last_command
]);
2379 if (vgdb_prefix
== NULL
)
2380 vgdb_prefix
= vgdb_prefix_default();
2385 || last_command
!= -1)) {
2388 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2391 if (isatty(from_gdb
)
2395 && last_command
== -1) {
2398 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2401 if (show_shared_mem
&& show_list
) {
2404 "Can't use both -D and -l options\n");
2407 if (max_invoke_ms
> 0
2408 && cmd_time_out
!= NEVER
2409 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
2412 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2415 if (show_list
&& arg_pid
!= -1) {
2418 "Can't use both --pid and -l options\n");
2421 if (int_port
> 0 && last_command
!= -1) {
2424 "Can't use --port to send commands\n");
2427 if (arg_errors
> 0) {
2428 TSFPRINTF(stderr
, "args error. Try `vgdb --help` for more information\n");
2429 early_exit(1, "invalid args given to vgdb");
2432 *p_show_shared_mem
= show_shared_mem
;
2433 *p_show_list
= show_list
;
2434 *p_multi_mode
= multi_mode
;
2435 *p_arg_pid
= arg_pid
;
2436 *p_check_trials
= check_trials
;
2438 *p_last_command
= last_command
;
2441 int main(int argc
, char** argv
)
2446 Bool show_shared_mem
;
2453 char *commands
[argc
]; // we will never have more commands than args.
2455 parse_options(argc
, argv
,
2465 /* when we are working as a relay for gdb, handle some signals by
2466 only reporting them (according to debug level). Also handle these
2467 when ptrace will be used: vgdb must clean up the ptrace effect before
2469 if (max_invoke_ms
> 0 || last_command
== -1)
2473 pid
= search_arg_pid(arg_pid
, check_trials
, show_list
);
2475 /* We pass 1 for check_trials here, because search_arg_pid already waited. */
2476 prepare_fifos_and_shared_mem(pid
, 1);
2482 wait_for_gdb_connect(in_port
);
2484 if (show_shared_mem
) {
2487 "written_by_vgdb %d "
2488 "seen_by_valgrind %d\n",
2491 VS_seen_by_valgrind
);
2492 TSFPRINTF(stderr
, "vgdb pid %d\n", VS_vgdb_pid
);
2493 early_exit(0, "-D arg to show shared memory and exit given.");
2497 /* check_trials is the --wait argument in seconds, defaulting to 1
2499 do_multi_mode (check_trials
, in_port
);
2500 } else if (last_command
>= 0) {
2501 standalone_send_commands(pid
, last_command
, commands
);
2503 gdb_relay(pid
, 0, NULL
);
2507 free(valgrind_path
);
2509 cleanup_fifos_and_shared_mem();
2511 for (i
= 0; i
<= last_command
; i
++)