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 /* vgdb has three usages:
53 1. relay application between gdb and the gdbserver embedded in valgrind.
54 2. standalone to send monitor commands to a running valgrind-ified process
55 3. multi mode where vgdb uses the GDB extended remote protocol.
57 It is made of a main program which reads arguments. If no
58 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
61 As relay application, vgdb reads bytes from gdb on stdin and
62 writes these bytes to valgrind. Bytes read from valgrind are
63 written to gdb on stdout. Read/Write from/to valgrind is done
64 using FIFOs. There is one thread reading from stdin, writing to
65 valgrind on a FIFO. There is one thread reading from valgrind on a
66 FIFO, writing to gdb on stdout
68 As a standalone utility, vgdb builds command packets to write to valgrind,
69 sends it and reads the reply. The same two threads are used to write/read.
70 Once all the commands are sent and their replies received, vgdb will exit.
72 When --multi is given vgdb communicates with GDB through the extended remote
73 protocol and will launch valgrind whenever GDB sends the vRun packet, after
74 which it will function in the first mode, relaying packets between GDB and
75 the gdbserver embedded in valgrind till that valgrind quits. vgdb will stay
80 Bool timestamp
= False
;
81 char timestamp_out
[20];
82 static char *vgdb_prefix
= NULL
;
83 static char *valgrind_path
= NULL
;
85 static char cvargs
= 0;
87 char *timestamp_str (Bool produce
)
95 gettimeofday(&dbgtv
, NULL
);
96 ts_tm
= localtime(&dbgtv
.tv_sec
);
97 ptr
= out
+ strftime(out
, sizeof(out
), "%H:%M:%S", ts_tm
);
98 sprintf(ptr
, ".%6.6ld ", dbgtv
.tv_usec
);
105 /* Will be set to True when any condition indicating we have to shutdown
107 Bool shutting_down
= False
;
109 VgdbShared32
*shared32
;
110 VgdbShared64
*shared64
;
111 #define VS_written_by_vgdb (shared32 != NULL ? \
112 shared32->written_by_vgdb \
113 : shared64->written_by_vgdb)
114 #define VS_seen_by_valgrind (shared32 != NULL ? \
115 shared32->seen_by_valgrind \
116 : shared64->seen_by_valgrind)
118 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
120 void *vmalloc(size_t size
)
122 void * mem
= malloc(size
);
124 XERROR(errno
, "can't allocate memory\n");
128 void *vrealloc(void *ptr
,size_t size
)
130 void * mem
= realloc(ptr
, size
);
132 XERROR(errno
, "can't reallocate memory\n");
136 /* Return the name of a directory for temporary files. */
138 const char *vgdb_tmpdir(void)
142 tmpdir
= getenv("TMPDIR");
143 if (tmpdir
== NULL
|| *tmpdir
== '\0')
145 if (tmpdir
== NULL
|| *tmpdir
== '\0')
146 tmpdir
= "/tmp"; /* fallback */
151 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
152 to communicate with valgrind */
154 char *vgdb_prefix_default(void)
156 static HChar
*prefix
;
158 if (prefix
== NULL
) {
159 const char *tmpdir
= vgdb_tmpdir();
160 prefix
= vmalloc(strlen(tmpdir
) + strlen("/vgdb-pipe") + 1);
161 strcpy(prefix
, tmpdir
);
162 strcat(prefix
, "/vgdb-pipe");
167 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
169 void add_written(int nrw
)
171 if (shared32
!= NULL
)
172 shared32
->written_by_vgdb
+= nrw
;
173 else if (shared64
!= NULL
)
174 shared64
->written_by_vgdb
+= nrw
;
179 static int shared_mem_fd
= -1;
181 void map_vgdbshared(char* shared_mem
, int check_trials
)
188 /* valgrind might still be starting up, give it 5 seconds by
189 * default, or check_trails seconds if it is set by --wait
190 * to more than a second. */
191 if (check_trials
> 1) {
192 DEBUG(1, "check_trials %d\n", check_trials
);
193 tries
= check_trials
* 10;
196 shared_mem_fd
= open(shared_mem
, O_RDWR
| O_CLOEXEC
);
198 if (shared_mem_fd
== -1 && err
== ENOENT
&& tries
> 0)
199 usleep (100000); /* wait 0.1 seconds */
200 } while (shared_mem_fd
== -1 && err
== ENOENT
&& tries
-- > 0);
202 /* shared_mem_fd will not be closed till vgdb exits. */
204 if (shared_mem_fd
== -1)
205 XERROR(errno
, "error opening %s shared memory file\n", shared_mem
);
207 if (fstat(shared_mem_fd
, &fdstat
) != 0)
208 XERROR(errno
, "fstat\n");
210 if (fdstat
.st_size
== sizeof(VgdbShared64
))
211 s
= (void*) &shared64
;
212 else if (fdstat
.st_size
== sizeof(VgdbShared32
))
213 s
= (void*) &shared32
;
215 #if VEX_HOST_WORDSIZE == 8
217 "error size shared memory file %s.\n"
218 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
220 (int) sizeof(VgdbShared64
), (int) sizeof(VgdbShared32
),
221 (long int)fdstat
.st_size
);
222 #elif VEX_HOST_WORDSIZE == 4
224 "error size shared memory file %s.\n"
225 "expecting size %d (32bits) got %ld.\n",
227 (int) sizeof(VgdbShared32
),
230 # error "unexpected wordsize"
233 #if VEX_HOST_WORDSIZE == 4
234 if (shared64
!= NULL
)
235 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
236 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
239 *s
= (void*) mmap(NULL
, fdstat
.st_size
,
240 PROT_READ
|PROT_WRITE
, MAP_SHARED
,
243 if (*s
== (void *) -1)
244 XERROR(errno
, "error mmap shared memory file %s\n", shared_mem
);
248 /* This function loops till shutting_down becomes true. In this loop,
249 it verifies if valgrind process is reading the characters written
250 by vgdb. The verification is done every max_invoke_ms ms. If
251 valgrind is not reading characters, it will use invoker_invoke_gdbserver
252 to ensure that the gdbserver code is called soon by valgrind. */
253 static int max_invoke_ms
= 100;
254 #define NEVER 99999999
255 static int cmd_time_out
= NEVER
;
257 void *invoke_gdbserver_in_valgrind(void *v_pid
)
259 struct timeval cmd_max_end_time
;
260 Bool cmd_started
= False
;
261 struct timeval invoke_time
;
263 int pid
= *(int *)v_pid
;
264 int written_by_vgdb_before_sleep
;
265 int seen_by_valgrind_before_sleep
;
267 int invoked_written
= -1;
270 pthread_cleanup_push(invoker_cleanup_restore_and_detach
, v_pid
);
272 while (!shutting_down
) {
273 written_by_vgdb_before_sleep
= VS_written_by_vgdb
;
274 seen_by_valgrind_before_sleep
= VS_seen_by_valgrind
;
276 "written_by_vgdb_before_sleep %d "
277 "seen_by_valgrind_before_sleep %d\n",
278 written_by_vgdb_before_sleep
,
279 seen_by_valgrind_before_sleep
);
280 if (cmd_time_out
!= NEVER
282 && written_by_vgdb_before_sleep
> seen_by_valgrind_before_sleep
) {
283 /* A command was started. Record the time at which it was started. */
284 DEBUG(1, "IO for command started\n");
285 gettimeofday(&cmd_max_end_time
, NULL
);
286 cmd_max_end_time
.tv_sec
+= cmd_time_out
;
289 if (max_invoke_ms
> 0) {
290 usecs
= 1000 * max_invoke_ms
;
291 gettimeofday(&invoke_time
, NULL
);
292 invoke_time
.tv_sec
+= max_invoke_ms
/ 1000;
293 invoke_time
.tv_usec
+= 1000 * (max_invoke_ms
% 1000);
294 invoke_time
.tv_sec
+= invoke_time
.tv_usec
/ (1000 * 1000);
295 invoke_time
.tv_usec
= invoke_time
.tv_usec
% (1000 * 1000);
300 // 0 usecs here means the thread just has to check gdbserver eats
301 // the characters in <= cmd_time_out seconds.
302 // We will just wait by 1 second max at a time.
303 if (usecs
== 0 || usecs
> 1000 * 1000)
308 /* If nothing happened during our sleep, let's try to wake up valgrind
309 or check for cmd time out. */
310 if (written_by_vgdb_before_sleep
== VS_written_by_vgdb
311 && seen_by_valgrind_before_sleep
== VS_seen_by_valgrind
312 && VS_written_by_vgdb
> VS_seen_by_valgrind
) {
314 gettimeofday(&now
, NULL
);
317 "written_by_vgdb %d "
318 "seen_by_valgrind %d "
319 "invoked_written %d\n",
323 /* if the pid does not exist anymore, we better stop */
324 if (kill(pid
, 0) != 0)
326 "invoke_gdbserver_in_valgrind: "
327 "check for pid %d existence failed\n", pid
);
329 if (timercmp(&now
, &cmd_max_end_time
, >))
331 "pid %d did not handle a command in %d seconds\n",
334 if (max_invoke_ms
> 0 && timercmp (&now
, &invoke_time
, >=)) {
335 /* only need to wake up if the nr written has changed since
337 if (invoked_written
!= written_by_vgdb_before_sleep
) {
338 if (invoker_invoke_gdbserver(pid
)) {
339 /* If invoke successful, no need to invoke again
340 for the same value of written_by_vgdb_before_sleep. */
341 invoked_written
= written_by_vgdb_before_sleep
;
346 // Something happened => restart timer check.
347 if (cmd_time_out
!= NEVER
) {
348 DEBUG(2, "some IO was done => restart command\n");
353 pthread_cleanup_pop(0);
358 int open_fifo(const char* name
, int flags
, const char* desc
)
361 DEBUG(1, "opening %s %s\n", name
, desc
);
362 fd
= open(name
, flags
| O_CLOEXEC
);
364 XERROR(errno
, "error opening %s %s\n", name
, desc
);
366 DEBUG(1, "opened %s %s fd %d\n", name
, desc
, fd
);
370 /* acquire a lock on the first byte of the given fd. If not successful,
372 This allows to avoid having two vgdb speaking with the same Valgrind
373 gdbserver as this causes serious headaches to the protocol. */
375 void acquire_lock(int fd
, int valgrind_pid
)
379 fl
.l_whence
= SEEK_SET
;
382 if (fcntl(fd
, F_SETLK
, &fl
) < 0) {
383 if (errno
== EAGAIN
|| errno
== EACCES
) {
385 "Cannot acquire lock.\n"
386 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
390 XERROR(errno
, "cannot acquire lock.\n");
394 /* Here, we have the lock. It will be released when fd will be closed. */
395 /* We indicate our pid to Valgrind gdbserver */
396 if (shared32
!= NULL
)
397 shared32
->vgdb_pid
= getpid();
398 else if (shared64
!= NULL
)
399 shared64
->vgdb_pid
= getpid();
404 #define PBUFSIZ 16384 /* keep in sync with server.h */
406 /* read some characters from fd.
407 Returns the nr of characters read, -1 if error.
408 desc is a string used in tracing */
410 int read_buf(int fd
, char* buf
, const char* desc
)
413 DEBUG(2, "reading %s\n", desc
);
414 /* The file descriptor is on non-blocking mode and read_buf should only
415 be called when poll gave us an POLLIN event signaling the file
416 descriptor is ready for reading from. Still sometimes we do get an
417 occasional EAGAIN. Just do as told in that case and try to read
420 nrread
= read(fd
, buf
, PBUFSIZ
);
421 } while (nrread
== -1 && errno
== EAGAIN
);
423 ERROR(errno
, "error reading %s\n", desc
);
427 DEBUG(2, "read %s %s\n", desc
, buf
);
431 /* write size bytes from buf to fd.
432 desc is a description of the action for which the write is done.
433 If notify, then add size to the shared cntr indicating to the
434 valgrind process that there is new data.
435 Returns True if write is ok, False if there was a problem. */
437 Bool
write_buf(int fd
, const char* buf
, int size
, const char* desc
, Bool notify
)
441 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc
, size
,
444 while (nrwritten
< size
) {
445 nrw
= write(fd
, buf
+nrwritten
, size
- nrwritten
);
447 ERROR(errno
, "error write %s\n", desc
);
450 nrwritten
= nrwritten
+ nrw
;
461 TO_PID
} ConnectionKind
;
462 static const int NumConnectionKind
= TO_PID
+1;
464 const char *ppConnectionKind(ConnectionKind con
)
467 case FROM_GDB
: return "FROM_GDB";
468 case TO_GDB
: return "TO_GDB";
469 case FROM_PID
: return "FROM_PID";
470 case TO_PID
: return "TO_PID";
471 default: return "invalid connection kind";
475 static char *shared_mem
;
477 static int from_gdb
= 0; /* stdin by default, changed if --port is given. */
478 static char *from_gdb_to_pid
; /* fifo name to write gdb command to pid */
480 static int to_gdb
= 1; /* stdout by default, changed if --port is given. */
481 static char *to_gdb_from_pid
; /* fifo name to read pid replies */
483 /* Returns True in case read/write operations were done properly.
484 Returns False in case of error.
485 to_pid is the file descriptor to write to the process pid. */
487 Bool
read_from_gdb_write_to_pid(int to_pid
)
489 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
493 nrread
= read_buf(from_gdb
, buf
, "from gdb on stdin");
496 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
498 DEBUG(1, "error reading bytes from gdb\n");
500 shutting_down
= True
;
503 ret
= write_buf(to_pid
, buf
, nrread
, "to_pid", /* notify */ True
);
505 /* Let gdb know the packet couldn't be delivered. */
506 write_buf(to_gdb
, "$E01#a6", 8, "error back to gdb", False
);
511 /* Returns True in case read/write operations were done properly.
512 Returns False in case of error.
513 from_pid is the file descriptor to read data from the process pid. */
515 Bool
read_from_pid_write_to_gdb(int from_pid
)
517 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
520 nrread
= read_buf(from_pid
, buf
, "from pid");
523 DEBUG(1, "read 0 bytes from pid => assume exit\n");
525 DEBUG(1, "error reading bytes from pid\n");
527 shutting_down
= True
;
530 return write_buf(to_gdb
, buf
, nrread
, "to_gdb", /* notify */ False
);
534 void wait_for_gdb_connect(int in_port
)
536 struct sockaddr_in addr
;
539 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, IPPROTO_TCP
);
541 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
546 if (-1 == listen_gdb
) {
547 XERROR(errno
, "cannot create socket\n");
550 /* allow address reuse to avoid "address already in use" errors */
553 if (setsockopt(listen_gdb
, SOL_SOCKET
, SO_REUSEADDR
,
554 &one
, sizeof(one
)) < 0) {
555 XERROR(errno
, "cannot enable address reuse\n");
558 memset(&addr
, 0, sizeof(addr
));
560 addr
.sin_family
= AF_INET
;
561 addr
.sin_port
= htons((unsigned short int)in_port
);
562 addr
.sin_addr
.s_addr
= INADDR_ANY
;
564 if (-1 == bind(listen_gdb
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
565 XERROR(errno
, "bind failed\n");
567 TSFPRINTF(stderr
, "listening on port %d ...", in_port
);
568 if (-1 == listen(listen_gdb
, 1)) {
569 XERROR(errno
, "error listen failed\n");
573 gdb_connect
= accept4(listen_gdb
, NULL
, NULL
, SOCK_CLOEXEC
);
575 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
578 if (gdb_connect
< 0) {
579 XERROR(errno
, "accept failed\n");
581 fprintf(stderr
, "connected.\n");
584 from_gdb
= gdb_connect
;
585 to_gdb
= gdb_connect
;
588 /* prepares the FIFOs filenames, map the shared memory. */
590 void prepare_fifos_and_shared_mem(int pid
, int check_trials
)
592 const HChar
*user
, *host
;
595 user
= getenv("LOGNAME");
596 if (user
== NULL
) user
= getenv("USER");
597 if (user
== NULL
) user
= "???";
598 if (strchr(user
, '/')) user
= "???";
600 host
= getenv("HOST");
601 if (host
== NULL
) host
= getenv("HOSTNAME");
602 if (host
== NULL
) host
= "???";
603 if (strchr(host
, '/')) host
= "???";
605 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
606 from_gdb_to_pid
= vmalloc(len
);
607 to_gdb_from_pid
= vmalloc(len
);
608 shared_mem
= vmalloc(len
);
609 /* below 3 lines must match the equivalent in remote-utils.c */
610 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
612 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
614 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
616 DEBUG(1, "vgdb: using %s %s %s\n",
617 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
619 map_vgdbshared(shared_mem
, check_trials
);
623 cleanup_fifos_and_shared_mem(void)
625 free(from_gdb_to_pid
);
626 free(to_gdb_from_pid
);
628 close(shared_mem_fd
);
631 /* Convert hex digit A to a number. */
636 if (a
>= '0' && a
<= '9')
638 else if (a
>= 'a' && a
<= 'f')
641 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
645 /* Returns next char from fd. -1 if error, -2 if EOF.
646 NB: must always call it with the same fd */
650 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
651 static int bufcnt
= 0;
652 static unsigned char *bufp
;
653 // unsigned bufp to e.g. avoid having 255 converted to int -1
658 bufcnt
= read_buf(fd
, buf
, "static buf readchar");
662 TSFPRINTF(stderr
, "readchar: Got EOF\n");
665 ERROR(errno
, "readchar\n");
670 bufp
= (unsigned char *)buf
;
675 /* Read a packet from fromfd, with error checking,
677 If checksum incorrect, writes a - on ackfd.
678 Returns length of packet, or -1 if error or -2 if EOF. */
680 getpkt(char *buf
, int fromfd
, int ackfd
)
683 unsigned char csum
, c1
, c2
;
690 c
= readchar(fromfd
);
693 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
700 c
= readchar(fromfd
);
711 repeat
= readchar(fromfd
);
713 for (r
= 0; r
< repeat
- 29; r
++)
722 c1
= fromhex(readchar (fromfd
));
723 c2
= fromhex(readchar (fromfd
));
725 if (csum
== (c1
<< 4) + c2
)
728 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
729 (c1
<< 4) + c2
, csum
, buf
);
730 if (write(ackfd
, "-", 1) != 1)
731 ERROR(errno
, "error when writing - (nack)\n");
736 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
740 static int sigint
= 0;
741 static int sigterm
= 0;
742 static int sigpipe
= 0;
743 static int sighup
= 0;
744 static int sigusr1
= 0;
745 static int sigalrm
= 0;
746 static int sigusr1_fd
= -1;
747 static pthread_t invoke_gdbserver_in_valgrind_thread
;
750 void received_signal(int signum
)
752 if (signum
== SIGINT
)
754 else if (signum
== SIGUSR1
) {
756 if (sigusr1_fd
>= 0) {
757 char control_c
= '\003';
758 write_buf(sigusr1_fd
, &control_c
, 1,
759 "write \\003 on SIGUSR1", /* notify */ True
);
762 else if (signum
== SIGTERM
) {
763 shutting_down
= True
;
765 } else if (signum
== SIGHUP
) {
766 shutting_down
= True
;
768 } else if (signum
== SIGPIPE
) {
770 } else if (signum
== SIGALRM
) {
772 #if defined(VGPV_arm_linux_android) \
773 || defined(VGPV_x86_linux_android) \
774 || defined(VGPV_mips32_linux_android) \
775 || defined(VGPV_arm64_linux_android)
776 /* Android has no pthread_cancel. As it also does not have
777 an invoker implementation, there is no need for cleanup action.
778 So, we just do nothing. */
779 DEBUG(1, "sigalrm received, no action on android\n");
781 /* Note: we cannot directly invoke restore_and_detach : this must
782 be done by the thread that has attached.
783 We have in this thread pushed a cleanup handler that will
784 cleanup what is needed. */
785 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
786 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
789 ERROR(0, "unexpected signal %d\n", signum
);
793 /* install the signal handlers allowing e.g. vgdb to cleanup in
794 case of termination. */
796 void install_handlers(void)
798 struct sigaction action
, oldaction
;
800 action
.sa_handler
= received_signal
;
801 sigemptyset(&action
.sa_mask
);
804 /* SIGINT: when user types C-c in gdb, this sends
805 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
806 The later is enough to wakeup the valgrind process. */
807 if (sigaction(SIGINT
, &action
, &oldaction
) != 0)
808 XERROR(errno
, "vgdb error sigaction SIGINT\n");
809 /* We might do something more intelligent than just
810 reporting this SIGINT E.g. behave similarly to the gdb: two
811 control-C without feedback from the debugged process would
812 mean to stop debugging it. */
814 /* SIGUSR1: this is used to facilitate automatic testing. When
815 vgdb receives this signal, it will simulate the user typing C-c. */
816 if (sigaction(SIGUSR1
, &action
, &oldaction
) != 0)
817 XERROR(errno
, "vgdb error sigaction SIGUSR1\n");
820 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
821 when detaching or similar. A clean shutdown will be done as both
822 the read and write side will detect an end of file. */
823 if (sigaction(SIGTERM
, &action
, &oldaction
) != 0)
824 XERROR(errno
, "vgdb error sigaction SIGTERM\n");
826 /* SIGPIPE: can receive this signal when gdb detaches or kill the
827 process debugged: gdb will close its pipes to vgdb. vgdb
828 must resist to this signal to allow a clean shutdown. */
829 if (sigaction(SIGPIPE
, &action
, &oldaction
) != 0)
830 XERROR(errno
, "vgdb error sigaction SIGPIPE\n");
832 /* SIGALRM: in case invoke thread is blocked, alarm is used
834 if (sigaction(SIGALRM
, &action
, &oldaction
) != 0)
835 XERROR(errno
, "vgdb error sigaction SIGALRM\n");
837 /* unmask all signals, in case the process that launched vgdb
839 if (sigprocmask(SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
840 XERROR(errno
, "vgdb error sigprocmask\n");
843 /* close the FIFOs provided connections, terminate the invoker thread. */
845 void close_connection(int to_pid
, int from_pid
)
847 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
848 sigint
, sigterm
, sighup
, sigpipe
);
849 /* Note that we do not forward sigterm to the valgrind process:
850 a sigterm signal is (probably) received from gdb if the user wants to
851 kill the debugged process. The kill instruction has been given to
852 the valgrind process, which should execute a clean exit. */
854 /* We first close the connection to pid. The pid will then
855 terminates its gdbserver work. We keep the from pid
856 fifo opened till the invoker thread is finished.
857 This allows the gdbserver to finish sending its last reply. */
858 if (close(to_pid
) != 0)
859 ERROR(errno
, "close to_pid\n");
861 /* if there is a task that was busy trying to wake up valgrind
862 process, we wait for it to be terminated otherwise threads
863 in the valgrind process can stay stopped if vgdb main
864 exits before the invoke thread had time to detach from
865 all valgrind threads. */
866 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
869 /* It is surprisingly complex to properly shutdown or exit the
870 valgrind process in which gdbserver has been invoked through
871 ptrace. In the normal case (gdb detaches from the process,
872 or process is continued), the valgrind process will reach the
873 breakpoint place. Using ptrace, vgdb will ensure the
874 previous activity of the process is resumed (e.g. restart a
875 blocking system call). The special case is when gdb asks the
876 valgrind process to exit (using either the "kill" command or
877 "monitor exit"). In such a case, the valgrind process will
878 call exit. But a ptraced process will be blocked in exit,
879 waiting for the ptracing process to detach or die. vgdb
880 cannot detach unconditionally as otherwise, in the normal
881 case, the valgrind process would stop abnormally with SIGSTOP
882 (as vgdb would not be there to catch it). vgdb can also not
883 die unconditionally otherwise again, similar problem. So, we
884 assume that most of the time, we arrive here in the normal
885 case, and so, the breakpoint has been encountered by the
886 valgrind process, so the invoker thread will exit and the
887 join will succeed. For the "kill" case, we cause an alarm
888 signal to be sent after a few seconds. This means that in the
889 normal case, the gdbserver code in valgrind process must have
890 returned the control in less than the alarm nr of seconds,
891 otherwise, valgrind will stop abnormally with SIGSTOP. */
894 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
895 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
899 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
901 #if !defined(VGO_freebsd)
902 if (close(from_pid
) != 0)
903 ERROR(errno
, "close from_pid\n");
913 return 'a' + nib
- 10;
916 /* Returns an allocated hex-decoded string from the buf. Stops decoding
917 at end of buf (zero) or when seeing the delim char. */
919 char *decode_hexstring (const char *buf
, size_t prefixlen
, size_t len
)
927 buflen
= strlen(buf
) - prefixlen
;
929 buf_print
= vmalloc (buflen
/2 + 1);
931 for (int i
= 0; i
< buflen
; i
= i
+ 2) {
932 buf_print
[i
/2] = ((fromhex(buf
[i
+prefixlen
]) << 4)
933 + fromhex(buf
[i
+prefixlen
+1]));
935 buf_print
[buflen
/2] = '\0';
936 DEBUG(1, "decode_hexstring: %s\n", buf_print
);
941 write_to_gdb (const char *m
, int cnt
)
944 while (written
< cnt
) {
945 int res
= write (to_gdb
, m
+ written
, cnt
- written
);
947 perror ("write_to_gdb");
957 write_checksum (const char *str
)
959 unsigned char csum
= 0;
965 p
[0] = tohex ((csum
>> 4) & 0x0f);
966 p
[1] = tohex (csum
& 0x0f);
967 return write_to_gdb (p
, 2);
971 write_reply(const char *reply
)
973 write_to_gdb ("$", 1);
974 write_to_gdb (reply
, strlen (reply
));
975 write_to_gdb ("#", 1);
976 return write_checksum (reply
);
979 /* Creates a packet from a string message, caller needs to free. */
981 create_packet(const char *msg
)
983 unsigned char csum
= 0;
985 char *p
= vmalloc (strlen (msg
) + 5); /* $ + msg + # + hexhex + 0 */
991 p
[i
++] = tohex ((csum
>> 4) & 0x0f);
992 p
[i
++] = tohex (csum
& 0x0f);
997 static int read_one_char (char *c
)
1001 i
= read (from_gdb
, c
, 1);
1002 while (i
== -1 && errno
== EINTR
);
1008 send_packet(const char *reply
, int noackmode
)
1014 if (!write_reply(reply
))
1017 // Look for '+' or '-'.
1018 // We must wait for "+" if !noackmode.
1020 ret
= read_one_char(&c
);
1023 // And if in !noackmode if we get "-" we should resent the packet.
1025 goto send_packet_start
;
1027 DEBUG(1, "sent packet to gdb got: %c\n",c
);
1032 // Reads one packet from_gdb starting with $ into buf.
1033 // Skipping any other characters.
1034 // Returns the size of the packet, 0 for end of input,
1035 // or -1 if no packet could be read.
1036 static int receive_packet(char *buf
, int noackmode
)
1043 unsigned char csum
= 0;
1045 // Look for first '$' (start of packet) or error.
1046 receive_packet_start
:
1048 ret
= read_one_char(&c
);
1053 // Found start of packet ('$')
1054 while (bufcnt
< (PBUFSIZ
+1)) {
1055 ret
= read_one_char(&c
);
1059 if ((ret
= read_one_char(&c1
)) <= 0
1060 || (ret
= read_one_char(&c2
)) <= 0) {
1068 csum
+= buf
[bufcnt
];
1072 // Packet complete, add terminator.
1075 if (!(csum
== (c1
<< 4) + c2
)) {
1076 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1077 (c1
<< 4) + c2
, csum
, buf
);
1079 if (!write_to_gdb ("-", 1))
1081 /* Try again, gdb should resend the packet. */
1084 goto receive_packet_start
;
1088 if (!write_to_gdb ("+", 1))
1093 // Returns a pointer to the char after the next delim char.
1094 static const char *next_delim_string (const char *buf
, char delim
)
1097 if (*buf
++ == delim
)
1103 /* buf starts with the packet name followed by the delimiter, for example
1104 * vRun;2f62696e2f6c73, ";" is the delimiter here, or
1105 * qXfer:features:read:target.xml:0,1000, where the delimiter is ":".
1106 * The packet name is thrown away and the hex string is decoded and
1107 * is placed in decoded_string (the caller owns this and is responsible
1108 * for freeing it). */
1109 static int split_hexdecode(const char *buf
, const char *string
,
1110 const char *delim
, char **decoded_string
)
1112 const char *next_str
= next_delim_string(buf
, *delim
);
1114 *decoded_string
= decode_hexstring (next_str
, 0, 0);
1115 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string
);
1118 TSFPRINTF(stderr
, "%s decoding error: finding the hex string in %s failed!\n", string
, buf
);
1123 static size_t count_delims(char delim
, char *buf
)
1129 count
+= *ptr
++ == delim
;
1133 // Determine the length of the arguments.
1134 // This depends on the len array being initialized to -1 for each element.
1135 // We first skip the command (e.g. vRun;arg0;arg1)
1136 static void count_len(char delim
, char *buf
, size_t *len
)
1142 while (*ptr
&& *ptr
!= delim
)
1145 // Delimiter counts towards the first arg0
1146 if (*ptr
== delim
) {
1151 // For each arg0... count chars (delim counts towards next arg)
1153 i
+= *ptr
++ == delim
;
1158 /* Declare here, will be used early, implementation follows later. */
1159 static void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
);
1161 /* Returns zero on success (and the pid of the valgrind process),
1162 or the errno from the child on failure. */
1164 int fork_and_exec_valgrind (int argc
, char **argv
, const char *working_dir
,
1165 int in_port
, pid_t
*pid
)
1168 // We will use a pipe to track what the child does,
1169 // so we can report failure.
1172 if (pipe2 (pipefd
, O_CLOEXEC
) == -1) {
1174 perror ("pipe2 failed");
1178 if (pipe (pipefd
) == -1) {
1180 perror ("pipe failed");
1183 if (fcntl (pipefd
[0], F_SETFD
, FD_CLOEXEC
) == -1
1184 || fcntl (pipefd
[1], F_SETFD
, FD_CLOEXEC
) == -1) {
1186 perror ("fcntl failed");
1197 perror ("fork failed");
1200 // I am the parent (vgdb), p is the pid of the child (valgrind)
1201 // We only read from the child to see if everything is OK.
1202 // If the pipe closes, we get zero back, which is good.
1203 // An error reading the pipe is bad (and really shouldn't happen).
1204 // Otherwise the child sent us an errno code about what went wrong.
1208 int r
= read (pipefd
[0], &err
, sizeof (int));
1209 if (r
== 0) // end of file, good pipe closed after execve
1216 perror ("pipe read");
1229 // p == 0, I am the child (will start valgrind)
1230 // We write success to the pipe, no need to read from it.
1233 if (working_dir
!= NULL
&& working_dir
[0] != '\0') {
1234 if (chdir (working_dir
) != 0) {
1237 // We try to write the result to the parent, but always exit.
1239 while (written
< sizeof (int)) {
1240 int nrw
= write (pipefd
[1], &err
, sizeof (int) - written
);
1249 /* When in stdio mode (talking to gdb through stdin/stdout, not
1250 through a socket), redirect stdout to stderr and close stdin
1251 for the inferior. That way at least some output can be seen,
1252 but there will be no input. */
1256 /* open /dev/null as new stdin */
1257 open ("/dev/null", O_RDONLY
);
1258 /* redirect stdout as stderr */
1262 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1263 can attach and --launched-with-multi to let valgrind know it doesn't
1264 need to show a banner how to connect to gdb, we will do that
1265 automagically. And add --vgdb-shadow-registers=yes to make shadow
1266 registers available by default. Add any other valgrind arguments the
1267 user gave with --vargs. Then the rest of the arguments to valgrind are
1268 the program to exec plus its arguments. */
1269 const int extra_vargs
= 3;
1270 /* vargv[0] == "valgrind",
1271 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1272 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1273 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1274 vargs[arguments - 1] = NULL */
1275 int arguments
= 1 + extra_vargs
+ cvargs
+ argc
+ 1;
1276 // We combine const and non-const char[]. This is mildly annoying
1277 // since we then need a char *const * for execvp. So we strdup the
1278 // const char*. Not pretty :{
1279 char **vargv
= vmalloc (arguments
* sizeof (char *));
1280 vargv
[0] = strdup ("valgrind");
1281 vargv
[1] = strdup ("--vgdb-error=0");
1282 vargv
[2] = strdup ("--launched-with-multi=yes");
1283 vargv
[3] = strdup ("--vgdb-shadow-registers=yes");
1285 for (int i
= 0; i
< cvargs
; i
++) {
1286 vargv
[i
+ extra_vargs
+ 1] = vargs
[i
];
1288 // Add command and args
1289 for (int i
= 0; i
< argc
; i
++) {
1290 vargv
[i
+ extra_vargs
+ 1 + cvargs
] = argv
[i
];
1292 vargv
[arguments
- 1] = NULL
;
1294 if (!valgrind_path
) {
1295 // TODO use execvpe (or something else if not on GNU/Linux
1296 /* We want to make a copy of the environ on start. When we
1297 get a QEnvironmentReset we copy that back. If we get an
1298 EvironSet/Add/Remove we update the copy. */
1299 execvp ("valgrind", vargv
);
1302 vargv
[0] = valgrind_path
;
1303 execvp (vargv
[0], vargv
);
1306 // We really shouldn't get here...
1308 /* Note we are after fork and exec failed, we cannot really call
1309 perror or printf in this situation since they aren't async-safe. */
1310 // perror ("execvp valgrind");
1311 // printf ("execve returned??? confusing: %d\n", res);
1312 // We try to write the result to the parent, but always exit.
1314 while (written
< sizeof (int)) {
1315 int nrw
= write (pipefd
[1], &err
, sizeof (int) - written
);
1323 abort (); // Impossible
1326 /* Do multi stuff. */
1328 void do_multi_mode(int check_trials
, int in_port
)
1330 char *buf
= vmalloc(PBUFSIZ
+1);
1331 char *q_buf
= vmalloc(PBUFSIZ
+1); //save the qSupported packet sent by gdb
1332 //to send it to the valgrind gdbserver later
1334 int noackmode
= 0, pkt_size
= 0, bad_unknown_packets
= 0;
1335 char *string
= NULL
;
1336 char *working_dir
= NULL
;
1337 DEBUG(1, "doing multi stuff...\n");
1339 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1341 pkt_size
= receive_packet(buf
, noackmode
);
1342 if (pkt_size
<= 0) {
1343 DEBUG(1, "receive_packet: %d\n", pkt_size
);
1347 DEBUG(1, "packet received: '%s'\n", buf
);
1349 #define QSUPPORTED "qSupported:"
1350 #define STARTNOACKMODE "QStartNoAckMode"
1351 #define QRCMD "qRcmd" // This is the monitor command in gdb
1353 #define XFER "qXfer"
1354 #define QATTACHED "qAttached"
1355 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1356 #define QENVIRONMENTRESET "QEnvironmentReset"
1357 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1358 #define QSETWORKINGDIR "QSetWorkingDir"
1359 #define QTSTATUS "qTStatus"
1361 if (strncmp(QSUPPORTED
, buf
, strlen(QSUPPORTED
)) == 0) {
1362 DEBUG(1, "CASE %s\n", QSUPPORTED
);
1363 // And here is our reply.
1364 // XXX error handling? We don't check the arguments.
1367 // Keep this in sync with coregrind/m_gdbserver/server.c
1368 if (asprintf (&reply
,
1373 /* Just report support always. */
1375 /* We'll force --vgdb-shadow-registers=yes */
1376 "qXfer:features:read+;"
1377 "qXfer:exec-file:read+;"
1378 "qXfer:siginfo:read+;"
1379 /* Extra vgdb support before valgrind starts up. */
1380 "QEnvironmentHexEncoded+;"
1381 "QEnvironmentReset+;"
1382 "QEnvironmentUnset+;"
1383 "QSetWorkingDir+", (UInt
)PBUFSIZ
- 1) != -1) {
1384 send_packet(reply
, noackmode
);
1387 XERROR(errno
, "asprintf failed\n");
1390 else if (strncmp(STARTNOACKMODE
, buf
, strlen(STARTNOACKMODE
)) == 0) {
1391 // We have to ack this one
1392 send_packet("OK", 0);
1395 else if (buf
[0] == '!') {
1396 send_packet("OK", noackmode
);
1398 else if (buf
[0] == '?') {
1399 send_packet("W00", noackmode
);
1401 else if (strncmp("H", buf
, strlen("H")) == 0) {
1402 // Set thread packet, but we are not running yet.
1403 send_packet("E01", noackmode
);
1405 else if (strncmp("vMustReplyEmpty", buf
, strlen("vMustReplyEmpty")) == 0) {
1406 send_packet ("", noackmode
);
1408 else if (strncmp(QRCMD
, buf
, strlen(QRCMD
)) == 0) {
1409 send_packet ("No running target, monitor commands not available yet.", noackmode
);
1411 char *decoded_string
= decode_hexstring (buf
, strlen (QRCMD
) + 1, 0);
1412 DEBUG(1, "qRcmd decoded: %s\n", decoded_string
);
1413 free (decoded_string
);
1415 else if (strncmp(VRUN
, buf
, strlen(VRUN
)) == 0) {
1416 // vRun;filename[;argument]*
1417 // vRun, filename and arguments are split on ';',
1418 // no ';' at the end.
1419 // If there are no arguments count is one (just the filename).
1420 // Otherwise it is the number of arguments plus one (the filename).
1421 // The filename must be there and starts after the first ';'.
1422 // TODO: Handle vRun;[;argument]*
1423 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1424 // If filename is an empty string, the stub may use a default program
1425 // (e.g. the last program run).
1426 size_t count
= count_delims(';', buf
);
1427 size_t *len
= vmalloc(count
* sizeof(count
));
1428 const char *delim
= ";";
1429 const char *next_str
= next_delim_string(buf
, *delim
);
1430 char **decoded_string
= vmalloc(count
* sizeof (char *));
1432 // Count the lenghts of each substring, init to -1 to compensate for
1433 // each substring starting with a delim char.
1434 for (size_t i
= 0; i
< count
; i
++)
1436 count_len(';', buf
, len
);
1438 DEBUG(1, "vRun: next_str %s\n", next_str
);
1439 for (size_t i
= 0; i
< count
; i
++) {
1440 /* Handle the case when the arguments
1441 * was specified to gdb's run command
1442 * but no remote exec-file was set,
1443 * so the first vRun argument is missing.
1444 * For example vRun;;6c. */
1445 if (*next_str
== *delim
) {
1447 /* empty string that can be freed. */
1448 decoded_string
[i
] = strdup("");
1451 decoded_string
[i
] = decode_hexstring (next_str
, 0, len
[i
]);
1453 next_str
= next_delim_string(next_str
, *delim
);
1455 DEBUG(1, "vRun decoded: %s, next_str %s, len[%zu] %zu\n",
1456 decoded_string
[i
], next_str
, i
, len
[i
]);
1459 /* If we didn't get any arguments or the filename is an empty
1460 string, valgrind won't know which program to run. */
1461 DEBUG (1, "count: %zu, len[0]: %zu\n", count
, len
[0]);
1462 if (! count
|| len
[0] == 0) {
1464 for (size_t i
= 0; i
< count
; i
++)
1465 free (decoded_string
[i
]);
1466 free (decoded_string
);
1467 send_packet ("E01", noackmode
);
1471 /* We have collected the decoded strings so we can use them to
1472 launch valgrind with the correct arguments... We then use the
1473 valgrind pid to start relaying packets. */
1474 pid_t valgrind_pid
= -1;
1475 int res
= fork_and_exec_valgrind ((int)count
,
1482 // Lets report we Stopped with SIGTRAP (05).
1483 send_packet ("S05", noackmode
);
1484 prepare_fifos_and_shared_mem(valgrind_pid
, check_trials
);
1485 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n",
1486 from_gdb_to_pid
, to_gdb_from_pid
);
1487 // gdb_relay is an endless loop till valgrind quits.
1488 shutting_down
= False
;
1490 gdb_relay (valgrind_pid
, 1, q_buf
);
1491 cleanup_fifos_and_shared_mem();
1492 DEBUG(1, "valgrind relay done\n");
1494 pid_t p
= waitpid (valgrind_pid
, &status
, 0);
1495 DEBUG(2, "waitpid: %d\n", (int) p
);
1497 DEBUG(1, "waitpid error %s\n", strerror (errno
));
1499 if (WIFEXITED(status
))
1500 DEBUG(1, "valgrind exited with %d\n",
1501 WEXITSTATUS(status
));
1502 else if (WIFSIGNALED(status
))
1503 DEBUG(1, "valgrind kill by signal %d\n",
1506 DEBUG(1, "valgrind unexpectedly stopped or continued");
1509 send_packet ("E01", noackmode
);
1510 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1515 for (int i
= 0; i
< count
; i
++)
1516 free (decoded_string
[i
]);
1517 free (decoded_string
);
1520 send_packet ("E01", noackmode
);
1521 DEBUG(1, "vRun decoding error: no next_string!\n");
1524 } else if (strncmp(QATTACHED
, buf
, strlen(QATTACHED
)) == 0) {
1525 send_packet ("1", noackmode
);
1526 DEBUG(1, "qAttached sent: '1'\n");
1527 const char *next_str
= next_delim_string(buf
, ':');
1529 char *decoded_string
= decode_hexstring (next_str
, 0, 0);
1530 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string
, next_str
);
1531 free (decoded_string
);
1533 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf
);
1536 } /* Reset the state of environment variables in the remote target
1537 before starting the inferior. In this context, reset means
1538 unsetting all environment variables that were previously set
1539 by the user (i.e., were not initially present in the environment). */
1540 else if (strncmp(QENVIRONMENTRESET
, buf
,
1541 strlen(QENVIRONMENTRESET
)) == 0) {
1542 send_packet ("OK", noackmode
);
1543 // TODO clear all environment strings. We're not using
1544 // environment strings now. But we should.
1545 } else if (strncmp(QENVIRONMENTHEXENCODED
, buf
,
1546 strlen(QENVIRONMENTHEXENCODED
)) == 0) {
1547 send_packet ("OK", noackmode
);
1548 if (!split_hexdecode(buf
, QENVIRONMENTHEXENCODED
, ":", &string
))
1550 // TODO Collect all environment strings and add them to environ
1551 // before launching valgrind.
1554 } else if (strncmp(QENVIRONMENTUNSET
, buf
,
1555 strlen(QENVIRONMENTUNSET
)) == 0) {
1556 send_packet ("OK", noackmode
);
1557 if (!split_hexdecode(buf
, QENVIRONMENTUNSET
, ":", &string
))
1559 // TODO Remove this environment string from the collection.
1562 } else if (strncmp(QSETWORKINGDIR
, buf
,
1563 strlen(QSETWORKINGDIR
)) == 0) {
1564 // Silly, but we can only reply OK, even if the working directory is
1565 // bad. Errors will be reported when we try to execute the actual
1567 send_packet ("OK", noackmode
);
1568 // Free any previously set working_dir
1571 if (!split_hexdecode(buf
, QSETWORKINGDIR
, ":", &working_dir
)) {
1572 continue; // We cannot report the error to gdb...
1574 DEBUG(1, "set working dir to: %s\n", working_dir
);
1575 } else if (strncmp(XFER
, buf
, strlen(XFER
)) == 0) {
1576 char *buf_dup
= strdup(buf
);
1577 DEBUG(1, "strdup: buf_dup %s\n", buf_dup
);
1579 const char *delim
= ":";
1580 size_t count
= count_delims(delim
[0], buf
);
1582 strsep(&buf_dup
, delim
);
1583 strsep(&buf_dup
, delim
);
1584 strsep(&buf_dup
, delim
);
1585 char *decoded_string
= decode_hexstring (buf_dup
, 0, 0);
1586 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string
, buf_dup
);
1587 free (decoded_string
);
1591 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf
);
1595 // Whether we could decode it or not, we cannot handle it now. We
1596 // need valgrind gdbserver to properly reply. So error out here.
1597 send_packet ("E00", noackmode
);
1598 } else if (strncmp(QTSTATUS
, buf
, strlen(QTSTATUS
)) == 0) {
1599 // We don't support trace experiments
1600 DEBUG(1, "Got QTSTATUS\n");
1601 send_packet ("", noackmode
);
1602 } else if (strcmp("qfThreadInfo", buf
) == 0) {
1603 DEBUG(1, "Got qfThreadInfo\n");
1604 /* There are no threads yet, reply 'l' end of list. */
1605 send_packet ("l", noackmode
);
1606 } else if (buf
[0] != '\0') {
1607 // We didn't understand.
1608 DEBUG(1, "Unknown packet received: '%s'\n", buf
);
1609 bad_unknown_packets
++;
1610 if (bad_unknown_packets
> 10) {
1611 DEBUG(1, "Too many bad/unknown packets received\n");
1614 send_packet ("", noackmode
);
1617 DEBUG(1, "done doing multi stuff...\n");
1622 shutting_down
= True
;
1627 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1628 encountered. q_buf is the qSupported packet received from gdb. */
1630 void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
)
1632 int from_pid
= -1; /* fd to read from pid */
1633 int to_pid
= -1; /* fd to write to pid */
1635 int shutdown_loop
= 0;
1636 TSFPRINTF(stderr
, "relaying data between gdb and process %d\n", pid
);
1638 if (max_invoke_ms
> 0)
1639 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1640 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1641 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1642 acquire_lock(shared_mem_fd
, pid
);
1644 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
1645 "read mode from pid");
1647 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
1649 Bool waiting_for_noack_mode
= False
;
1650 Bool waiting_for_qsupported
= False
;
1651 if(send_noack_mode
) {
1652 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid
, from_pid
);
1653 write_buf(to_pid
, "$QStartNoAckMode#b0", 19,
1654 "write start no ack mode",
1656 waiting_for_noack_mode
= True
;
1662 struct pollfd pollfds
[NumConnectionKind
];
1664 /* watch data written by gdb, watch POLLERR on both gdb fd */
1665 pollfds
[FROM_GDB
].fd
= from_gdb
;
1666 pollfds
[FROM_GDB
].events
= POLLIN
;
1667 pollfds
[FROM_GDB
].revents
= 0;
1668 pollfds
[TO_GDB
].fd
= to_gdb
;
1669 pollfds
[TO_GDB
].events
= 0;
1670 pollfds
[TO_GDB
].revents
= 0;
1672 /* watch data written by pid, watch POLLERR on both pid fd */
1673 pollfds
[FROM_PID
].fd
= from_pid
;
1674 pollfds
[FROM_PID
].events
= POLLIN
;
1675 pollfds
[FROM_PID
].revents
= 0;
1676 pollfds
[TO_PID
].fd
= to_pid
;
1677 pollfds
[TO_PID
].events
= 0;
1678 pollfds
[TO_PID
].revents
= 0;
1684 : -1 /* infinite */));
1685 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
1687 /* check for unexpected error */
1688 if (ret
<= 0 && errno
!= EINTR
) {
1689 ERROR(errno
, "unexpected poll ret %d\n", ret
);
1690 shutting_down
= True
;
1694 /* check for data to read */
1695 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1696 if (pollfds
[ck
].revents
& POLLIN
) {
1699 if (waiting_for_noack_mode
|| waiting_for_qsupported
)
1700 break; /* Don't add any messages while vgdb is talking. */
1701 if (!read_from_gdb_write_to_pid(to_pid
))
1702 shutting_down
= True
;
1705 // First handle any messages from vgdb
1706 if (waiting_for_noack_mode
) {
1707 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1709 buflen
= getpkt(buf
, from_pid
, to_pid
);
1710 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1712 ERROR(0, "no ack mode: unexpected buflen %zu, buf %s\n",
1715 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1717 waiting_for_noack_mode
= False
;
1719 /* Propagate qSupported to valgrind, we already replied. */
1720 if (q_buf
!= NULL
&& q_buf
[0] != '\0') {
1721 char *pkt
= create_packet (q_buf
);
1722 write_buf(to_pid
, pkt
, strlen(pkt
),
1723 "write qSupported", /* notify */ True
);
1725 waiting_for_qsupported
= True
;
1727 } else if (waiting_for_qsupported
) {
1728 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1730 buflen
= getpkt(buf
, from_pid
, to_pid
);
1731 /* Should we sanity check the result? */
1733 waiting_for_qsupported
= False
;
1735 ERROR(0, "Unexpected getpkt for qSupported reply: %zu\n",
1738 } else if (!read_from_pid_write_to_gdb(from_pid
))
1739 shutting_down
= True
;
1741 default: XERROR(0, "unexpected POLLIN on %s\n",
1742 ppConnectionKind(ck
));
1747 /* check for an fd being in error condition */
1748 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1749 if (pollfds
[ck
].revents
& POLLERR
) {
1750 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1751 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1752 invoker_valgrind_dying();
1753 shutting_down
= True
;
1755 if (pollfds
[ck
].revents
& POLLHUP
) {
1756 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1757 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1758 invoker_valgrind_dying();
1759 shutting_down
= True
;
1761 if (pollfds
[ck
].revents
& POLLNVAL
) {
1762 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1763 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1764 invoker_valgrind_dying();
1765 shutting_down
= True
;
1769 if (shutting_down
) {
1770 /* we let some time to the final packets to be transferred */
1772 if (shutdown_loop
> 3)
1776 close_connection(to_pid
, from_pid
);
1779 static int packet_len_for_command(char *cmd
)
1781 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1782 return 7+ 2*strlen(cmd
) +3 + 1;
1785 /* hyper-minimal protocol implementation that
1786 sends the provided commands (using qRcmd packets)
1787 and read and display their replies. */
1789 void standalone_send_commands(int pid
,
1793 int from_pid
= -1; /* fd to read from pid */
1794 int to_pid
= -1; /* fd to write to pid */
1799 unsigned char cksum
;
1801 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1806 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
1807 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1808 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1810 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1811 acquire_lock(shared_mem_fd
, pid
);
1813 /* first send a C-c \003 to pid, so that it wakes up the process
1814 After that, we can open the fifo from the pid in read mode
1815 We then start to wait for packets (normally first a resume reply)
1816 At that point, we send our command and expect replies */
1819 while (!write_buf(to_pid
, buf
, 1,
1820 "write \\003 to wake up", /* notify */ True
)) {
1821 /* If write fails, retries up to 10 times every 0.5 seconds
1822 This aims at solving the race condition described in
1823 remote-utils.c remote_finish function. */
1827 XERROR(errno
, "failed to send wake up char after 10 trials\n");
1829 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
1830 "read cmd result from pid");
1832 /* Enable no ack mode. */
1833 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1835 buflen
= getpkt(buf
, from_pid
, to_pid
);
1836 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1838 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen
);
1840 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1843 for (nc
= 0; nc
<= last_command
; nc
++) {
1844 TSFPRINTF(stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
1846 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1847 hexcommand
= vmalloc(packet_len_for_command(commands
[nc
]));
1849 strcat(hexcommand
, "$qRcmd,");
1850 for (i
= 0; i
< strlen(commands
[nc
]); i
++) {
1851 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][i
]);
1852 // Need to use unsigned char, to avoid sign extension.
1853 strcat(hexcommand
, hex
);
1855 /* checksum (but without the $) */
1857 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1858 cksum
+=hexcommand
[hi
];
1859 strcat(hexcommand
, "#");
1860 sprintf(hex
, "%02x", cksum
);
1861 strcat(hexcommand
, hex
);
1862 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1863 "writing hex command to pid", /* notify */ True
);
1865 /* we exit of the below loop explicitly when the command has
1866 been handled or because a signal handler will set
1868 while (!shutting_down
) {
1869 buflen
= getpkt(buf
, from_pid
, to_pid
);
1871 ERROR(0, "error reading packet\n");
1873 invoker_valgrind_dying();
1876 if (strlen(buf
) == 0) {
1877 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1880 if (strcmp(buf
, "OK") == 0) {
1881 DEBUG(1, "OK packet rcvd\n");
1884 if (buf
[0] == 'E') {
1886 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1890 if (buf
[0] == 'W') {
1891 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1894 if (buf
[0] == 'T') {
1895 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1899 /* must be here an O packet with hex encoded string reply
1900 => decode and print it */
1901 if (buf
[0] != 'O') {
1902 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1906 char buf_print
[buflen
/2 + 1];
1907 for (i
= 1; i
< buflen
; i
= i
+ 2)
1908 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1909 + fromhex(*(buf
+i
+1));
1910 buf_print
[buflen
/2] = 0;
1911 printf("%s", buf_print
);
1917 shutting_down
= True
;
1919 close_connection(to_pid
, from_pid
);
1922 /* report to user the existence of a vgdb-able valgrind process
1924 Note: this function does not use XERROR if an error is encountered
1925 while producing the command line for pid, as this is not critical
1926 and at least on MacOS, reading cmdline is not available. */
1928 void report_pid(int pid
, Bool on_stdout
)
1930 char cmdline_file
[50]; // large enough
1932 FILE *out
= on_stdout
? stdout
: stderr
;
1934 TSFPRINTF(out
, "use --pid=%d for ", pid
);
1936 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
1937 fd
= open(cmdline_file
, O_RDONLY
| O_CLOEXEC
);
1939 DEBUG(1, "error opening cmdline file %s %s\n",
1940 cmdline_file
, strerror(errno
));
1941 fprintf(out
, "(could not open process command line)\n");
1945 while ((sz
= read(fd
, cmdline
, sizeof cmdline
- 1)) > 0) {
1946 for (i
= 0; i
< sz
; i
++)
1947 if (cmdline
[i
] == 0)
1950 fprintf(out
, "%s", cmdline
);
1953 DEBUG(1, "error reading cmdline file %s %s\n",
1954 cmdline_file
, strerror(errno
));
1955 fprintf(out
, "(error reading process command line)");
1967 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1968 "vgdb (valgrind gdb) has two usages\n"
1969 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1970 " The OPTION(s) must be followed by the command to send\n"
1971 " To send more than one command, separate the commands with -c\n"
1972 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1973 " Only OPTION(s) can be given.\n"
1975 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1976 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1977 " [--port=<portnr>\n"
1978 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1979 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
1981 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1982 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1983 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1984 " between the Valgrind gdbserver and vgdb.\n"
1985 " --wait (default 0) tells vgdb to check during the specified number\n"
1986 " of seconds if a Valgrind gdbserver can be found.\n"
1987 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1988 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1989 " process is blocked in a system call).\n"
1990 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1991 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1992 " gdbserver has not processed a command after number seconds\n"
1993 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
1994 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
1995 " --vargs everything that follows is an argument for valgrind.\n"
1996 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1997 " -T arg tells to add timestamps to vgdb information messages.\n"
1998 " -D arg tells to show shared mem status and then exit.\n"
1999 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
2001 " -h --help shows this message\n"
2002 #ifdef VG_GDBSCRIPTS_DIR
2003 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
2005 " To get help from the Valgrind gdbserver, use vgdb help\n"
2006 "\n", vgdb_prefix_default()
2007 #ifdef VG_GDBSCRIPTS_DIR
2008 , VG_GDBSCRIPTS_DIR
"/valgrind-monitor.py"
2011 invoker_restrictions_msg();
2014 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
2017 else if arg_pid == -1, waits maximum check_trials seconds to discover
2018 a valgrind pid appearing.
2020 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2021 with gdbserver activated.
2023 Returns the pid to work with
2024 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2027 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
2032 if (arg_pid
== 0 || arg_pid
< -1) {
2033 TSFPRINTF(stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
2036 /* search for a matching named fifo.
2037 If we have been given a pid, we will check that the matching FIFO is
2038 there (or wait the nr of check_trials for this to appear).
2039 If no pid has been given, then if we find only one FIFO,
2040 we will use this to build the pid to use.
2041 If we find multiple processes with valid FIFO, we report them and will
2042 exit with an error. */
2044 char *vgdb_dir_name
= vmalloc(strlen (vgdb_prefix
) + 3);
2047 int nr_valid_pid
= 0;
2048 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
2049 char *vgdb_format
= vmalloc(strlen(vgdb_prefix
) + strlen(suffix
) + 1);
2051 strcpy(vgdb_format
, vgdb_prefix
);
2052 strcat(vgdb_format
, suffix
);
2054 if (strchr(vgdb_prefix
, '/') != NULL
) {
2055 strcpy(vgdb_dir_name
, vgdb_prefix
);
2056 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
2057 if (vgdb_dir_name
[is
] == '/') {
2058 vgdb_dir_name
[is
+1] = '\0';
2062 strcpy(vgdb_dir_name
, "");
2065 DEBUG(1, "searching pid in directory %s format %s\n",
2066 vgdb_dir_name
, vgdb_format
);
2068 /* try to find FIFOs with valid pid.
2069 On exit of the loop, pid is set to:
2070 the last pid found if show_list (or -1 if no process was listed)
2071 -1 if no FIFOs matching a running process is found
2072 -2 if multiple FIFOs of running processes are found
2073 otherwise it is set to the (only) pid found that can be debugged
2075 for (i
= 0; i
< check_trials
; i
++) {
2076 DEBUG(1, "check_trial %d \n", i
);
2078 /* wait one second before checking again */
2081 vgdb_dir
= opendir(strlen(vgdb_dir_name
) ? vgdb_dir_name
: "./");
2082 if (vgdb_dir
== NULL
)
2084 "vgdb error: opening directory %s searching vgdb fifo\n",
2087 errno
= 0; /* avoid complain if vgdb_dir is empty */
2088 while ((f
= readdir(vgdb_dir
))) {
2090 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
2094 strcpy(pathname
, vgdb_dir_name
);
2095 strcat(pathname
, f
->d_name
);
2096 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
2097 if (stat(pathname
, &st
) != 0) {
2098 if (debuglevel
>= 3)
2099 ERROR(errno
, "vgdb error: stat %s searching vgdb fifo\n",
2101 } else if (S_ISFIFO(st
.st_mode
)) {
2102 DEBUG(3, "trying FIFO %s\n", pathname
);
2103 if (strncmp(pathname
, vgdb_format
,
2104 strlen(vgdb_format
)) == 0) {
2105 newpid
= strtol(pathname
+ strlen(vgdb_format
),
2107 if (*wrongpid
== '-' && newpid
> 0
2108 && kill(newpid
, 0) == 0) {
2111 report_pid(newpid
, /*on_stdout*/ True
);
2113 } else if (arg_pid
!= -1) {
2114 if (arg_pid
== newpid
) {
2117 } else if (nr_valid_pid
> 1) {
2118 if (nr_valid_pid
== 2) {
2121 "no --pid= arg given"
2122 " and multiple valgrind pids found:\n");
2123 report_pid(pid
, /*on_stdout*/ False
);
2126 report_pid(newpid
, /*on_stdout*/ False
);
2133 errno
= 0; /* avoid complain if at the end of vgdb_dir */
2135 if (f
== NULL
&& errno
!= 0)
2136 XERROR(errno
, "vgdb error: reading directory %s for vgdb fifo\n",
2144 free(vgdb_dir_name
);
2150 } else if (pid
== -1) {
2152 TSFPRINTF(stderr
, "vgdb error: no FIFO found and no pid given\n");
2154 TSFPRINTF(stderr
, "vgdb error: no FIFO found matching pid %d\n",
2158 else if (pid
== -2) {
2159 /* no arg_pid given, multiple FIFOs found */
2167 /* return true if the numeric value of an option of the
2168 form --xxxxxxxxx=<number> could properly be extracted
2169 from arg. If True is returned, *value contains the
2172 Bool
numeric_val(char* arg
, int *value
)
2174 const char *eq_pos
= strchr(arg
, '=');
2176 long long int long_value
;
2181 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
2182 if (long_value
< 0 || long_value
> INT_MAX
)
2187 *value
= (int) long_value
;
2191 /* true if arg matches the provided option */
2193 Bool
is_opt(char* arg
, const char *option
)
2195 int option_len
= strlen(option
);
2196 if (option
[option_len
-1] == '=')
2197 return (0 == strncmp(option
, arg
, option_len
));
2199 return (0 == strcmp(option
, arg
));
2202 /* Parse command lines options. If error(s), exits.
2203 Otherwise returns the options in *p_... args.
2204 commands must be big enough for the commands extracted from argv.
2205 On return, *p_last_command gives the position in commands where
2206 the last command has been allocated (using vmalloc). */
2208 void parse_options(int argc
, char** argv
,
2209 Bool
*p_show_shared_mem
,
2213 int *p_check_trials
,
2215 int *p_last_command
,
2218 Bool show_shared_mem
= False
;
2219 Bool show_list
= False
;
2220 Bool multi_mode
= False
;
2222 int check_trials
= 1;
2223 int last_command
= -1;
2229 for (i
= 1; i
< argc
; i
++) {
2230 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
2233 } else if (is_opt(argv
[i
], "-d")) {
2235 } else if (is_opt(argv
[i
], "-D")) {
2236 show_shared_mem
= True
;
2237 } else if (is_opt(argv
[i
], "-l")) {
2239 } else if (is_opt(argv
[i
], "--multi")) {
2241 } else if (is_opt(argv
[i
], "-T")) {
2243 } else if (is_opt(argv
[i
], "--pid=")) {
2245 if (!numeric_val(argv
[i
], &newpid
)) {
2246 TSFPRINTF(stderr
, "invalid --pid argument %s\n", argv
[i
]);
2248 } else if (arg_pid
!= -1) {
2249 TSFPRINTF(stderr
, "multiple --pid arguments given\n");
2254 } else if (is_opt(argv
[i
], "--wait=")) {
2255 if (!numeric_val(argv
[i
], &check_trials
)) {
2256 TSFPRINTF(stderr
, "invalid --wait argument %s\n", argv
[i
]);
2259 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
2260 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
2261 TSFPRINTF(stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
2264 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
2265 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
2266 TSFPRINTF(stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
2269 } else if (is_opt(argv
[i
], "--port=")) {
2270 if (!numeric_val(argv
[i
], &int_port
)) {
2271 TSFPRINTF(stderr
, "invalid --port argument %s\n", argv
[i
]);
2274 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
2276 // was specified more than once on the command line
2277 // ignore earlier uses
2280 vgdb_prefix
= strdup (argv
[i
] + 14);
2281 } else if (is_opt(argv
[i
], "--valgrind=")) {
2282 char *path
= argv
[i
] + 11;
2283 /* Compute the absolute path. */
2284 valgrind_path
= realpath(path
, NULL
);
2285 if (!valgrind_path
) {
2286 TSFPRINTF(stderr
, "%s is not a correct path. %s, exiting.\n",
2287 path
, strerror (errno
));
2290 DEBUG(2, "valgrind's real path: %s\n", valgrind_path
);
2291 } else if (is_opt(argv
[i
], "--vargs")) {
2292 // Everything that follows now is an argument for valgrind
2293 // No other options (or commands) can follow
2294 // argc - i is the number of left over arguments
2295 // allocate enough space, put all args in it.
2296 cvargs
= argc
- i
- 1;
2297 vargs
= vmalloc (cvargs
* sizeof(vargs
));
2299 for (int j
= 0; i
< argc
; i
++) {
2303 } else if (is_opt(argv
[i
], "-c")) {
2305 commands
[last_command
] = vmalloc(1);
2306 commands
[last_command
][0] = '\0';
2307 } else if (0 == strncmp(argv
[i
], "-", 1)) {
2308 TSFPRINTF(stderr
, "unknown or invalid argument %s\n", argv
[i
]);
2312 if (last_command
== -1) {
2313 /* only one command, no -c command indicator */
2315 commands
[last_command
] = vmalloc(1);
2316 commands
[last_command
][0] = '\0';
2318 len
= strlen(commands
[last_command
]);
2319 commands
[last_command
] = vrealloc(commands
[last_command
],
2320 len
+ 1 + strlen(argv
[i
]) + 1);
2322 strcat(commands
[last_command
], " ");
2323 strcat(commands
[last_command
], argv
[i
]);
2324 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
2325 TSFPRINTF(stderr
, "command %s too long\n", commands
[last_command
]);
2332 if (vgdb_prefix
== NULL
)
2333 vgdb_prefix
= vgdb_prefix_default();
2338 || last_command
!= -1)) {
2341 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2348 && last_command
== -1) {
2351 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2354 if (show_shared_mem
&& show_list
) {
2357 "Can't use both -D and -l options\n");
2360 if (max_invoke_ms
> 0
2361 && cmd_time_out
!= NEVER
2362 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
2365 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2368 if (show_list
&& arg_pid
!= -1) {
2371 "Can't use both --pid and -l options\n");
2374 if (int_port
> 0 && last_command
!= -1) {
2377 "Can't use --port to send commands\n");
2380 if (arg_errors
> 0) {
2381 TSFPRINTF(stderr
, "args error. Try `vgdb --help` for more information\n");
2385 *p_show_shared_mem
= show_shared_mem
;
2386 *p_show_list
= show_list
;
2387 *p_multi_mode
= multi_mode
;
2388 *p_arg_pid
= arg_pid
;
2389 *p_check_trials
= check_trials
;
2391 *p_last_command
= last_command
;
2394 int main(int argc
, char** argv
)
2399 Bool show_shared_mem
;
2406 char *commands
[argc
]; // we will never have more commands than args.
2408 parse_options(argc
, argv
,
2418 /* when we are working as a relay for gdb, handle some signals by
2419 only reporting them (according to debug level). Also handle these
2420 when ptrace will be used: vgdb must clean up the ptrace effect before
2422 if (max_invoke_ms
> 0 || last_command
== -1)
2426 pid
= search_arg_pid(arg_pid
, check_trials
, show_list
);
2428 /* We pass 1 for check_trails here, because search_arg_pid already waited. */
2429 prepare_fifos_and_shared_mem(pid
, 1);
2435 wait_for_gdb_connect(in_port
);
2437 if (show_shared_mem
) {
2440 "written_by_vgdb %d "
2441 "seen_by_valgrind %d\n",
2444 VS_seen_by_valgrind
);
2445 TSFPRINTF(stderr
, "vgdb pid %d\n", VS_vgdb_pid
);
2450 /* check_trails is the --wait argument in seconds, defaulting to 1
2452 do_multi_mode (check_trials
, in_port
);
2453 } else if (last_command
>= 0) {
2454 standalone_send_commands(pid
, last_command
, commands
);
2456 gdb_relay(pid
, 0, NULL
);
2460 free(valgrind_path
);
2462 cleanup_fifos_and_shared_mem();
2464 for (i
= 0; i
<= last_command
; i
++)