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 size_t 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
== EINTR
|| 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
, size_t size
, const char* desc
,
444 DEBUG(2, "writing %s len %zu %.*s notify: %d\n", desc
, size
,
445 (int)size
, buf
, notify
);
447 while (nrwritten
< size
) {
448 nrw
= write(fd
, buf
+nrwritten
, size
- nrwritten
);
450 if (errno
== EINTR
|| errno
== EAGAIN
)
453 ERROR(errno
, "error write %s\n", desc
);
456 nrwritten
= nrwritten
+ nrw
;
467 TO_PID
} ConnectionKind
;
468 static const int NumConnectionKind
= TO_PID
+1;
470 const char *ppConnectionKind(ConnectionKind con
)
473 case FROM_GDB
: return "FROM_GDB";
474 case TO_GDB
: return "TO_GDB";
475 case FROM_PID
: return "FROM_PID";
476 case TO_PID
: return "TO_PID";
477 default: return "invalid connection kind";
481 static char *shared_mem
;
483 static int from_gdb
= 0; /* stdin by default, changed if --port is given. */
484 static char *from_gdb_to_pid
; /* fifo name to write gdb command to pid */
486 static int to_gdb
= 1; /* stdout by default, changed if --port is given. */
487 static char *to_gdb_from_pid
; /* fifo name to read pid replies */
489 /* Returns True in case read/write operations were done properly.
490 Returns False in case of error.
491 to_pid is the file descriptor to write to the process pid. */
493 Bool
read_from_gdb_write_to_pid(int to_pid
)
495 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
499 nrread
= read_buf(from_gdb
, buf
, "from gdb on stdin");
502 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
504 DEBUG(1, "error reading bytes from gdb\n");
506 shutting_down
= True
;
509 ret
= write_buf(to_pid
, buf
, nrread
, "to_pid", /* notify */ True
);
511 /* Let gdb know the packet couldn't be delivered. */
512 write_buf(to_gdb
, "$E01#a6", 8, "error back to gdb", False
);
517 /* Returns True in case read/write operations were done properly.
518 Returns False in case of error.
519 from_pid is the file descriptor to read data from the process pid. */
521 Bool
read_from_pid_write_to_gdb(int from_pid
)
523 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
526 nrread
= read_buf(from_pid
, buf
, "from pid");
529 DEBUG(1, "read 0 bytes from pid => assume exit\n");
531 DEBUG(1, "error reading bytes from pid\n");
533 shutting_down
= True
;
536 return write_buf(to_gdb
, buf
, nrread
, "to_gdb", /* notify */ False
);
540 void wait_for_gdb_connect(int in_port
)
542 struct sockaddr_in addr
;
545 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
| SOCK_CLOEXEC
, IPPROTO_TCP
);
547 int listen_gdb
= socket(PF_INET
, SOCK_STREAM
, IPPROTO_TCP
);
552 if (-1 == listen_gdb
) {
553 XERROR(errno
, "cannot create socket\n");
556 /* allow address reuse to avoid "address already in use" errors */
559 if (setsockopt(listen_gdb
, SOL_SOCKET
, SO_REUSEADDR
,
560 &one
, sizeof(one
)) < 0) {
561 XERROR(errno
, "cannot enable address reuse\n");
564 memset(&addr
, 0, sizeof(addr
));
566 addr
.sin_family
= AF_INET
;
567 addr
.sin_port
= htons((unsigned short int)in_port
);
568 addr
.sin_addr
.s_addr
= INADDR_ANY
;
570 if (-1 == bind(listen_gdb
, (struct sockaddr
*)&addr
, sizeof(addr
))) {
571 XERROR(errno
, "bind failed\n");
573 TSFPRINTF(stderr
, "listening on port %d ...", in_port
);
574 if (-1 == listen(listen_gdb
, 1)) {
575 XERROR(errno
, "error listen failed\n");
579 gdb_connect
= accept4(listen_gdb
, NULL
, NULL
, SOCK_CLOEXEC
);
581 gdb_connect
= accept(listen_gdb
, NULL
, NULL
);
584 if (gdb_connect
< 0) {
585 XERROR(errno
, "accept failed\n");
587 fprintf(stderr
, "connected.\n");
590 from_gdb
= gdb_connect
;
591 to_gdb
= gdb_connect
;
594 /* prepares the FIFOs filenames, map the shared memory. */
596 void prepare_fifos_and_shared_mem(int pid
, int check_trials
)
598 const HChar
*user
, *host
;
601 user
= getenv("LOGNAME");
602 if (user
== NULL
) user
= getenv("USER");
603 if (user
== NULL
) user
= "???";
604 if (strchr(user
, '/')) user
= "???";
606 host
= getenv("HOST");
607 if (host
== NULL
) host
= getenv("HOSTNAME");
608 if (host
== NULL
) host
= "???";
609 if (strchr(host
, '/')) host
= "???";
611 len
= strlen(vgdb_prefix
) + strlen(user
) + strlen(host
) + 40;
612 from_gdb_to_pid
= vmalloc(len
);
613 to_gdb_from_pid
= vmalloc(len
);
614 shared_mem
= vmalloc(len
);
615 /* below 3 lines must match the equivalent in remote-utils.c */
616 sprintf(from_gdb_to_pid
, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix
,
618 sprintf(to_gdb_from_pid
, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix
,
620 sprintf(shared_mem
, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix
,
622 DEBUG(1, "vgdb: using %s %s %s\n",
623 from_gdb_to_pid
, to_gdb_from_pid
, shared_mem
);
625 map_vgdbshared(shared_mem
, check_trials
);
629 cleanup_fifos_and_shared_mem(void)
631 free(from_gdb_to_pid
);
632 free(to_gdb_from_pid
);
634 close(shared_mem_fd
);
637 /* Convert hex digit A to a number. */
642 if (a
>= '0' && a
<= '9')
644 else if (a
>= 'a' && a
<= 'f')
647 XERROR(0, "Reply contains invalid hex digit %c\n", a
);
651 /* Returns next char from fd. -1 if error, -2 if EOF.
652 NB: must always call it with the same fd */
656 static char buf
[PBUFSIZ
+1]; // +1 for trailing \0
657 static int bufcnt
= 0;
658 static unsigned char *bufp
;
659 // unsigned bufp to e.g. avoid having 255 converted to int -1
664 bufcnt
= read_buf(fd
, buf
, "static buf readchar");
668 TSFPRINTF(stderr
, "readchar: Got EOF\n");
671 ERROR(errno
, "readchar\n");
676 bufp
= (unsigned char *)buf
;
681 /* Read a packet from fromfd, with error checking,
683 If checksum incorrect, writes a - on ackfd.
684 Returns length of packet, or -1 if error or -2 if EOF. */
686 getpkt(char *buf
, int fromfd
, int ackfd
)
689 unsigned char csum
, c1
, c2
;
696 c
= readchar(fromfd
);
699 DEBUG(2, "[getpkt: discarding char '%c']\n", c
);
706 c
= readchar(fromfd
);
717 repeat
= readchar(fromfd
);
719 for (r
= 0; r
< repeat
- 29; r
++)
728 c1
= fromhex(readchar (fromfd
));
729 c2
= fromhex(readchar (fromfd
));
731 if (csum
== (c1
<< 4) + c2
)
734 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
735 (c1
<< 4) + c2
, csum
, buf
);
738 res
= write(ackfd
, "-", 1);
739 if (res
== -1 && (errno
== EINTR
|| errno
== EAGAIN
))
743 ERROR(errno
, "error when writing - (nack)\n");
748 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf
);
752 static int sigint
= 0;
753 static int sigterm
= 0;
754 static int sigpipe
= 0;
755 static int sighup
= 0;
756 static int sigusr1
= 0;
757 static int sigalrm
= 0;
758 static int sigusr1_fd
= -1;
759 static pthread_t invoke_gdbserver_in_valgrind_thread
;
762 void received_signal(int signum
)
764 if (signum
== SIGINT
)
766 else if (signum
== SIGUSR1
) {
768 if (sigusr1_fd
>= 0) {
769 char control_c
= '\003';
770 write_buf(sigusr1_fd
, &control_c
, 1,
771 "write \\003 on SIGUSR1", /* notify */ True
);
774 else if (signum
== SIGTERM
) {
775 shutting_down
= True
;
777 } else if (signum
== SIGHUP
) {
778 shutting_down
= True
;
780 } else if (signum
== SIGPIPE
) {
782 } else if (signum
== SIGALRM
) {
784 #if defined(VGPV_arm_linux_android) \
785 || defined(VGPV_x86_linux_android) \
786 || defined(VGPV_mips32_linux_android) \
787 || defined(VGPV_arm64_linux_android)
788 /* Android has no pthread_cancel. As it also does not have
789 an invoker implementation, there is no need for cleanup action.
790 So, we just do nothing. */
791 DEBUG(1, "sigalrm received, no action on android\n");
793 /* Note: we cannot directly invoke restore_and_detach : this must
794 be done by the thread that has attached.
795 We have in this thread pushed a cleanup handler that will
796 cleanup what is needed. */
797 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
798 pthread_cancel(invoke_gdbserver_in_valgrind_thread
);
801 ERROR(0, "unexpected signal %d\n", signum
);
805 /* install the signal handlers allowing e.g. vgdb to cleanup in
806 case of termination. */
808 void install_handlers(void)
810 struct sigaction action
, oldaction
;
812 action
.sa_handler
= received_signal
;
813 sigemptyset(&action
.sa_mask
);
816 /* SIGINT: when user types C-c in gdb, this sends
817 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
818 The later is enough to wakeup the valgrind process. */
819 if (sigaction(SIGINT
, &action
, &oldaction
) != 0)
820 XERROR(errno
, "vgdb error sigaction SIGINT\n");
821 /* We might do something more intelligent than just
822 reporting this SIGINT E.g. behave similarly to the gdb: two
823 control-C without feedback from the debugged process would
824 mean to stop debugging it. */
826 /* SIGUSR1: this is used to facilitate automatic testing. When
827 vgdb receives this signal, it will simulate the user typing C-c. */
828 if (sigaction(SIGUSR1
, &action
, &oldaction
) != 0)
829 XERROR(errno
, "vgdb error sigaction SIGUSR1\n");
832 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
833 when detaching or similar. A clean shutdown will be done as both
834 the read and write side will detect an end of file. */
835 if (sigaction(SIGTERM
, &action
, &oldaction
) != 0)
836 XERROR(errno
, "vgdb error sigaction SIGTERM\n");
838 /* SIGPIPE: can receive this signal when gdb detaches or kill the
839 process debugged: gdb will close its pipes to vgdb. vgdb
840 must resist to this signal to allow a clean shutdown. */
841 if (sigaction(SIGPIPE
, &action
, &oldaction
) != 0)
842 XERROR(errno
, "vgdb error sigaction SIGPIPE\n");
844 /* SIGALRM: in case invoke thread is blocked, alarm is used
846 if (sigaction(SIGALRM
, &action
, &oldaction
) != 0)
847 XERROR(errno
, "vgdb error sigaction SIGALRM\n");
849 /* unmask all signals, in case the process that launched vgdb
851 if (sigprocmask(SIG_SETMASK
, &action
.sa_mask
, NULL
) != 0)
852 XERROR(errno
, "vgdb error sigprocmask\n");
855 /* close the FIFOs provided connections, terminate the invoker thread. */
857 void close_connection(int to_pid
, int from_pid
)
859 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
860 sigint
, sigterm
, sighup
, sigpipe
);
861 /* Note that we do not forward sigterm to the valgrind process:
862 a sigterm signal is (probably) received from gdb if the user wants to
863 kill the debugged process. The kill instruction has been given to
864 the valgrind process, which should execute a clean exit. */
866 /* We first close the connection to pid. The pid will then
867 terminates its gdbserver work. We keep the from pid
868 fifo opened till the invoker thread is finished.
869 This allows the gdbserver to finish sending its last reply. */
870 if (close(to_pid
) != 0)
871 ERROR(errno
, "close to_pid\n");
873 /* if there is a task that was busy trying to wake up valgrind
874 process, we wait for it to be terminated otherwise threads
875 in the valgrind process can stay stopped if vgdb main
876 exits before the invoke thread had time to detach from
877 all valgrind threads. */
878 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
) {
881 /* It is surprisingly complex to properly shutdown or exit the
882 valgrind process in which gdbserver has been invoked through
883 ptrace. In the normal case (gdb detaches from the process,
884 or process is continued), the valgrind process will reach the
885 breakpoint place. Using ptrace, vgdb will ensure the
886 previous activity of the process is resumed (e.g. restart a
887 blocking system call). The special case is when gdb asks the
888 valgrind process to exit (using either the "kill" command or
889 "monitor exit"). In such a case, the valgrind process will
890 call exit. But a ptraced process will be blocked in exit,
891 waiting for the ptracing process to detach or die. vgdb
892 cannot detach unconditionally as otherwise, in the normal
893 case, the valgrind process would stop abnormally with SIGSTOP
894 (as vgdb would not be there to catch it). vgdb can also not
895 die unconditionally otherwise again, similar problem. So, we
896 assume that most of the time, we arrive here in the normal
897 case, and so, the breakpoint has been encountered by the
898 valgrind process, so the invoker thread will exit and the
899 join will succeed. For the "kill" case, we cause an alarm
900 signal to be sent after a few seconds. This means that in the
901 normal case, the gdbserver code in valgrind process must have
902 returned the control in less than the alarm nr of seconds,
903 otherwise, valgrind will stop abnormally with SIGSTOP. */
906 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
907 join
= pthread_join(invoke_gdbserver_in_valgrind_thread
, NULL
);
911 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
913 #if !defined(VGO_freebsd)
914 if (close(from_pid
) != 0)
915 ERROR(errno
, "close from_pid\n");
919 /* Returns an allocated hex-decoded string from the buf. Stops decoding
920 at end of buf (zero) or when seeing the delim char. */
922 char *decode_hexstring (const char *buf
, size_t prefixlen
, size_t len
)
930 buflen
= strlen(buf
) - prefixlen
;
932 buf_print
= vmalloc (buflen
/2 + 1);
934 for (int i
= 0; i
< buflen
; i
= i
+ 2) {
935 buf_print
[i
/2] = ((fromhex(buf
[i
+prefixlen
]) << 4)
936 + fromhex(buf
[i
+prefixlen
+1]));
938 buf_print
[buflen
/2] = '\0';
939 DEBUG(1, "decode_hexstring: %s\n", buf_print
);
944 write_to_gdb (const char *m
, size_t cnt
)
947 while (written
< cnt
) {
948 ssize_t res
= write (to_gdb
, m
+ written
, cnt
- written
);
950 if (errno
== EINTR
|| errno
== EAGAIN
)
953 perror ("write_to_gdb");
963 write_checksum (const char *str
)
965 unsigned char csum
= 0;
971 p
[0] = tohex ((csum
>> 4) & 0x0f);
972 p
[1] = tohex (csum
& 0x0f);
973 return write_to_gdb (p
, 2);
977 write_reply(const char *reply
)
979 write_to_gdb ("$", 1);
980 write_to_gdb (reply
, strlen (reply
));
981 write_to_gdb ("#", 1);
982 return write_checksum (reply
);
985 /* Creates a packet from a string message, caller needs to free. */
987 create_packet(const char *msg
)
989 unsigned char csum
= 0;
991 char *p
= vmalloc (strlen (msg
) + 5); /* $ + msg + # + hexhex + 0 */
997 p
[i
++] = tohex ((csum
>> 4) & 0x0f);
998 p
[i
++] = tohex (csum
& 0x0f);
1003 static ssize_t
read_one_char (char *c
)
1007 i
= read (from_gdb
, c
, 1);
1008 while (i
< 0 && (errno
== EINTR
|| errno
== EAGAIN
));
1014 send_packet(const char *reply
, int noackmode
)
1020 if (!write_reply(reply
))
1023 // Look for '+' or '-'.
1024 // We must wait for "+" if !noackmode.
1026 ret
= read_one_char(&c
);
1029 // And if in !noackmode if we get "-" we should resent the packet.
1031 goto send_packet_start
;
1033 DEBUG(1, "sent packet to gdb got: %c\n",c
);
1038 // Reads one packet from_gdb starting with $ into buf.
1039 // Skipping any other characters.
1040 // Returns the size of the packet, 0 for end of input,
1041 // or -1 if no packet could be read.
1042 static ssize_t
receive_packet(char *buf
, int noackmode
)
1049 unsigned char csum
= 0;
1051 // Look for first '$' (start of packet) or error.
1052 receive_packet_start
:
1054 ret
= read_one_char(&c
);
1059 // Found start of packet ('$')
1060 while (bufcnt
< (PBUFSIZ
+1)) {
1061 ret
= read_one_char(&c
);
1065 if ((ret
= read_one_char(&c1
)) <= 0
1066 || (ret
= read_one_char(&c2
)) <= 0) {
1074 csum
+= buf
[bufcnt
];
1078 // Packet complete, add terminator.
1081 if (!(csum
== (c1
<< 4) + c2
)) {
1082 TSFPRINTF(stderr
, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1083 (c1
<< 4) + c2
, csum
, buf
);
1085 if (!write_to_gdb ("-", 1))
1087 /* Try again, gdb should resend the packet. */
1090 goto receive_packet_start
;
1094 if (!write_to_gdb ("+", 1))
1099 // Returns a pointer to the char after the next delim char.
1100 static const char *next_delim_string (const char *buf
, char delim
)
1103 if (*buf
++ == delim
)
1109 /* buf starts with the packet name followed by the delimiter, for example
1110 * vRun;2f62696e2f6c73, ";" is the delimiter here, or
1111 * qXfer:features:read:target.xml:0,1000, where the delimiter is ":".
1112 * The packet name is thrown away and the hex string is decoded and
1113 * is placed in decoded_string (the caller owns this and is responsible
1114 * for freeing it). */
1115 static int split_hexdecode(const char *buf
, const char *string
,
1116 const char *delim
, char **decoded_string
)
1118 const char *next_str
= next_delim_string(buf
, *delim
);
1120 *decoded_string
= decode_hexstring (next_str
, 0, 0);
1121 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string
);
1124 TSFPRINTF(stderr
, "%s decoding error: finding the hex string in %s failed!\n", string
, buf
);
1129 static size_t count_delims(char delim
, char *buf
)
1135 count
+= *ptr
++ == delim
;
1139 // Determine the length of the arguments.
1140 // This depends on the len array being initialized to -1 for each element.
1141 // We first skip the command (e.g. vRun;arg0;arg1)
1142 static void count_len(char delim
, char *buf
, size_t *len
)
1148 while (*ptr
&& *ptr
!= delim
)
1151 // Delimiter counts towards the first arg0
1152 if (*ptr
== delim
) {
1157 // For each arg0... count chars (delim counts towards next arg)
1159 i
+= *ptr
++ == delim
;
1164 /* early_exit guesses if vgdb speaks with GDB by checking from_gdb is a FIFO
1165 (as GDB is likely the only program that would write data to vgdb stdin).
1166 If not speaking with GDB, early_exit will just call exit(exit_code).
1167 If speaking with GDB, early_exit will ensure the GDB user sees
1168 the error messages produced by vgdb:
1169 early_exit should be used when vgdb exits due to an early error i.e.
1170 error during arg processing, before it could successfully process the
1171 first packet from GDB.
1172 early_exit will then read the first packet send by GDB (i.e.
1173 the qSupported packet) and will reply to it with an error and then exit.
1174 This should ensure the vgdb error messages are made visible to the user. */
1175 static void early_exit (int exit_code
, const char* exit_info
)
1177 char buf
[PBUFSIZ
+1];
1181 if (fstat(from_gdb
, &fdstat
) != 0)
1182 XERROR(errno
, "fstat\n");
1184 DEBUG(1, "early_exit %s ISFIFO %d\n", exit_info
, S_ISFIFO(fdstat
.st_mode
));
1186 if (S_ISFIFO(fdstat
.st_mode
)) {
1187 /* We assume that we speak with GDB when stdin is a FIFO, so we expect
1188 to get a first packet from GDB. This should ensure the vgdb messages
1189 are made visible. In case the whole stuff is blocked for any reason or
1190 GDB does not send a package or ..., schedule an alarm to exit in max 5
1193 pkt_size
= receive_packet(buf
, 0);
1195 DEBUG(1, "early_exit receive_packet: %zd\n", pkt_size
);
1197 DEBUG(1, "packet received: '%s'\n", buf
);
1198 sprintf(buf
, "E.%s", exit_info
);
1199 send_packet(buf
, 0);
1204 DEBUG(1, "early_exit exiting %d\n", exit_code
);
1208 /* Declare here, will be used early, implementation follows later. */
1209 static void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
);
1211 /* Returns zero on success (and the pid of the valgrind process),
1212 or the errno from the child on failure. */
1214 int fork_and_exec_valgrind (int argc
, char **argv
, const char *working_dir
,
1215 int in_port
, pid_t
*pid
)
1218 // We will use a pipe to track what the child does,
1219 // so we can report failure.
1222 if (pipe2 (pipefd
, O_CLOEXEC
) == -1) {
1224 perror ("pipe2 failed");
1228 if (pipe (pipefd
) == -1) {
1230 perror ("pipe failed");
1233 if (fcntl (pipefd
[0], F_SETFD
, FD_CLOEXEC
) == -1
1234 || fcntl (pipefd
[1], F_SETFD
, FD_CLOEXEC
) == -1) {
1236 perror ("fcntl failed");
1247 perror ("fork failed");
1250 // I am the parent (vgdb), p is the pid of the child (valgrind)
1251 // We only read from the child to see if everything is OK.
1252 // If the pipe closes, we get zero back, which is good.
1253 // An error reading the pipe is bad (and really shouldn't happen).
1254 // Otherwise the child sent us an errno code about what went wrong.
1259 ssize_t r
= read (pipefd
[0], ((char *)&err
) + nr_read
,
1260 sizeof (int) - nr_read
);
1261 if (r
== 0) // end of file, good pipe closed after execve
1264 if (errno
== EINTR
|| errno
== EAGAIN
)
1268 perror ("pipe read");
1281 // p == 0, I am the child (will start valgrind)
1282 // We write success to the pipe, no need to read from it.
1285 if (working_dir
!= NULL
&& working_dir
[0] != '\0') {
1286 if (chdir (working_dir
) != 0) {
1289 // We try to write the result to the parent, but always exit.
1291 while (written
< sizeof (int)) {
1292 int nrw
= write (pipefd
[1], ((char *)&err
) + written
,
1293 sizeof (int) - written
);
1295 if (errno
== EINTR
|| errno
== EAGAIN
)
1305 /* When in stdio mode (talking to gdb through stdin/stdout, not
1306 through a socket), redirect stdout to stderr and close stdin
1307 for the inferior. That way at least some output can be seen,
1308 but there will be no input. */
1312 /* open /dev/null as new stdin */
1313 (void)open ("/dev/null", O_RDONLY
);
1314 /* redirect stdout as stderr */
1318 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1319 can attach and --launched-with-multi to let valgrind know it doesn't
1320 need to show a banner how to connect to gdb, we will do that
1321 automagically. And add --vgdb-shadow-registers=yes to make shadow
1322 registers available by default. Add any other valgrind arguments the
1323 user gave with --vargs. Then the rest of the arguments to valgrind are
1324 the program to exec plus its arguments. */
1325 const int extra_vargs
= 3;
1326 /* vargv[0] == "valgrind",
1327 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1328 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1329 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1330 vargs[arguments - 1] = NULL */
1331 int arguments
= 1 + extra_vargs
+ cvargs
+ argc
+ 1;
1332 // We combine const and non-const char[]. This is mildly annoying
1333 // since we then need a char *const * for execvp. So we strdup the
1334 // const char*. Not pretty :{
1335 char **vargv
= vmalloc (arguments
* sizeof (char *));
1336 vargv
[0] = strdup ("valgrind");
1337 vargv
[1] = strdup ("--vgdb-error=0");
1338 vargv
[2] = strdup ("--launched-with-multi=yes");
1339 vargv
[3] = strdup ("--vgdb-shadow-registers=yes");
1341 for (int i
= 0; i
< cvargs
; i
++) {
1342 vargv
[i
+ extra_vargs
+ 1] = vargs
[i
];
1344 // Add command and args
1345 for (int i
= 0; i
< argc
; i
++) {
1346 vargv
[i
+ extra_vargs
+ 1 + cvargs
] = argv
[i
];
1348 vargv
[arguments
- 1] = NULL
;
1350 if (!valgrind_path
) {
1351 // TODO use execvpe (or something else if not on GNU/Linux
1352 /* We want to make a copy of the environ on start. When we
1353 get a QEnvironmentReset we copy that back. If we get an
1354 EvironSet/Add/Remove we update the copy. */
1355 execvp ("valgrind", vargv
);
1358 vargv
[0] = valgrind_path
;
1359 execvp (vargv
[0], vargv
);
1362 // We really shouldn't get here...
1364 /* Note we are after fork and exec failed, we cannot really call
1365 perror or printf in this situation since they aren't async-safe. */
1366 // perror ("execvp valgrind");
1367 // printf ("execve returned??? confusing: %d\n", res);
1368 // We try to write the result to the parent, but always exit.
1370 while (written
< sizeof (int)) {
1371 ssize_t nrw
= write (pipefd
[1], ((char *) &err
) + written
,
1372 sizeof (int) - written
);
1374 if (errno
== EINTR
|| errno
== EAGAIN
)
1383 abort (); // Impossible
1386 /* Do multi stuff. */
1388 void do_multi_mode(int check_trials
, int in_port
)
1390 char *buf
= vmalloc(PBUFSIZ
+1);
1391 char *q_buf
= vmalloc(PBUFSIZ
+1); //save the qSupported packet sent by gdb
1392 //to send it to the valgrind gdbserver later
1394 int noackmode
= 0, bad_unknown_packets
= 0;
1395 ssize_t pkt_size
= 0;
1396 char *string
= NULL
;
1397 char *working_dir
= NULL
;
1398 DEBUG(1, "doing multi stuff...\n");
1400 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1402 pkt_size
= receive_packet(buf
, noackmode
);
1403 if (pkt_size
<= 0) {
1404 DEBUG(1, "receive_packet: %zd\n", pkt_size
);
1408 DEBUG(1, "packet received: '%s'\n", buf
);
1410 #define QSUPPORTED "qSupported:"
1411 #define STARTNOACKMODE "QStartNoAckMode"
1412 #define QRCMD "qRcmd" // This is the monitor command in gdb
1414 #define XFER "qXfer"
1415 #define QATTACHED "qAttached"
1416 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1417 #define QENVIRONMENTRESET "QEnvironmentReset"
1418 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1419 #define QSETWORKINGDIR "QSetWorkingDir"
1420 #define QTSTATUS "qTStatus"
1422 if (strncmp(QSUPPORTED
, buf
, strlen(QSUPPORTED
)) == 0) {
1423 DEBUG(1, "CASE %s\n", QSUPPORTED
);
1424 // And here is our reply.
1425 // XXX error handling? We don't check the arguments.
1428 // Keep this in sync with coregrind/m_gdbserver/server.c
1429 if (asprintf (&reply
,
1434 /* Just report support always. */
1436 /* We'll force --vgdb-shadow-registers=yes */
1437 "qXfer:features:read+;"
1438 "qXfer:exec-file:read+;"
1439 "qXfer:siginfo:read+;"
1440 /* Extra vgdb support before valgrind starts up. */
1441 "QEnvironmentHexEncoded+;"
1442 "QEnvironmentReset+;"
1443 "QEnvironmentUnset+;"
1444 "QSetWorkingDir+", (UInt
)PBUFSIZ
- 1) != -1) {
1445 send_packet(reply
, noackmode
);
1448 XERROR(errno
, "asprintf failed\n");
1451 else if (strncmp(STARTNOACKMODE
, buf
, strlen(STARTNOACKMODE
)) == 0) {
1452 // We have to ack this one
1453 send_packet("OK", 0);
1456 else if (buf
[0] == '!') {
1457 send_packet("OK", noackmode
);
1459 else if (buf
[0] == '?') {
1460 send_packet("W00", noackmode
);
1462 else if (strncmp("H", buf
, strlen("H")) == 0) {
1463 // Set thread packet, but we are not running yet.
1464 send_packet("E01", noackmode
);
1466 else if (strncmp("vMustReplyEmpty", buf
, strlen("vMustReplyEmpty")) == 0) {
1467 send_packet ("", noackmode
);
1469 else if (strncmp(QRCMD
, buf
, strlen(QRCMD
)) == 0) {
1470 static const char *no_running_str
=
1471 "No running target, monitor commands not available yet.\n";
1472 int str_count
= strlen (no_running_str
);
1473 char hex
[2 * str_count
+ 1];
1474 hexify(hex
, no_running_str
, str_count
);
1475 send_packet(hex
, noackmode
);
1477 char *decoded_string
= decode_hexstring (buf
, strlen (QRCMD
) + 1, 0);
1478 DEBUG(1, "qRcmd decoded: %s\n", decoded_string
);
1479 free (decoded_string
);
1481 else if (strncmp(VRUN
, buf
, strlen(VRUN
)) == 0) {
1482 // vRun;filename[;argument]*
1483 // vRun, filename and arguments are split on ';',
1484 // no ';' at the end.
1485 // If there are no arguments count is one (just the filename).
1486 // Otherwise it is the number of arguments plus one (the filename).
1487 // The filename must be there and starts after the first ';'.
1488 // TODO: Handle vRun;[;argument]*
1489 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1490 // If filename is an empty string, the stub may use a default program
1491 // (e.g. the last program run).
1492 size_t count
= count_delims(';', buf
);
1493 size_t *len
= vmalloc(count
* sizeof(count
));
1494 const char *delim
= ";";
1495 const char *next_str
= next_delim_string(buf
, *delim
);
1496 char **decoded_string
= vmalloc(count
* sizeof (char *));
1498 // Count the lenghts of each substring, init to -1 to compensate for
1499 // each substring starting with a delim char.
1500 for (size_t i
= 0; i
< count
; i
++)
1502 count_len(';', buf
, len
);
1504 DEBUG(1, "vRun: next_str %s\n", next_str
);
1505 for (size_t i
= 0; i
< count
; i
++) {
1506 /* Handle the case when the arguments
1507 * was specified to gdb's run command
1508 * but no remote exec-file was set,
1509 * so the first vRun argument is missing.
1510 * For example vRun;;6c. */
1511 if (*next_str
== *delim
) {
1513 /* empty string that can be freed. */
1514 decoded_string
[i
] = strdup("");
1517 decoded_string
[i
] = decode_hexstring (next_str
, 0, len
[i
]);
1519 next_str
= next_delim_string(next_str
, *delim
);
1521 DEBUG(1, "vRun decoded: %s, next_str %s, len[%zu] %zu\n",
1522 decoded_string
[i
], next_str
, i
, len
[i
]);
1525 /* If we didn't get any arguments or the filename is an empty
1526 string, valgrind won't know which program to run. */
1527 DEBUG (1, "count: %zu, len[0]: %zu\n", count
, len
[0]);
1528 if (! count
|| len
[0] == 0) {
1530 for (size_t i
= 0; i
< count
; i
++)
1531 free (decoded_string
[i
]);
1532 free (decoded_string
);
1533 send_packet ("E01", noackmode
);
1537 /* We have collected the decoded strings so we can use them to
1538 launch valgrind with the correct arguments... We then use the
1539 valgrind pid to start relaying packets. */
1540 pid_t valgrind_pid
= -1;
1541 int res
= fork_and_exec_valgrind ((int)count
,
1548 // Lets report we Stopped with SIGTRAP (05).
1549 send_packet ("S05", noackmode
);
1550 prepare_fifos_and_shared_mem(valgrind_pid
, check_trials
);
1551 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n",
1552 from_gdb_to_pid
, to_gdb_from_pid
);
1553 // gdb_relay is an endless loop till valgrind quits.
1554 shutting_down
= False
;
1556 gdb_relay (valgrind_pid
, 1, q_buf
);
1557 cleanup_fifos_and_shared_mem();
1558 DEBUG(1, "valgrind relay done\n");
1560 pid_t p
= waitpid (valgrind_pid
, &status
, 0);
1561 DEBUG(2, "waitpid: %d\n", (int) p
);
1563 DEBUG(1, "waitpid error %s\n", strerror (errno
));
1565 if (WIFEXITED(status
))
1566 DEBUG(1, "valgrind exited with %d\n",
1567 WEXITSTATUS(status
));
1568 else if (WIFSIGNALED(status
))
1569 DEBUG(1, "valgrind kill by signal %d\n",
1572 DEBUG(1, "valgrind unexpectedly stopped or continued");
1575 send_packet ("E01", noackmode
);
1576 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1581 for (size_t i
= 0; i
< count
; i
++)
1582 free (decoded_string
[i
]);
1583 free (decoded_string
);
1586 send_packet ("E01", noackmode
);
1587 DEBUG(1, "vRun decoding error: no next_string!\n");
1590 } else if (strncmp(QATTACHED
, buf
, strlen(QATTACHED
)) == 0) {
1591 send_packet ("1", noackmode
);
1592 DEBUG(1, "qAttached sent: '1'\n");
1593 const char *next_str
= next_delim_string(buf
, ':');
1595 char *decoded_string
= decode_hexstring (next_str
, 0, 0);
1596 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string
, next_str
);
1597 free (decoded_string
);
1599 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf
);
1602 } /* Reset the state of environment variables in the remote target
1603 before starting the inferior. In this context, reset means
1604 unsetting all environment variables that were previously set
1605 by the user (i.e., were not initially present in the environment). */
1606 else if (strncmp(QENVIRONMENTRESET
, buf
,
1607 strlen(QENVIRONMENTRESET
)) == 0) {
1608 send_packet ("OK", noackmode
);
1609 // TODO clear all environment strings. We're not using
1610 // environment strings now. But we should.
1611 } else if (strncmp(QENVIRONMENTHEXENCODED
, buf
,
1612 strlen(QENVIRONMENTHEXENCODED
)) == 0) {
1613 send_packet ("OK", noackmode
);
1614 if (!split_hexdecode(buf
, QENVIRONMENTHEXENCODED
, ":", &string
))
1616 // TODO Collect all environment strings and add them to environ
1617 // before launching valgrind.
1620 } else if (strncmp(QENVIRONMENTUNSET
, buf
,
1621 strlen(QENVIRONMENTUNSET
)) == 0) {
1622 send_packet ("OK", noackmode
);
1623 if (!split_hexdecode(buf
, QENVIRONMENTUNSET
, ":", &string
))
1625 // TODO Remove this environment string from the collection.
1628 } else if (strncmp(QSETWORKINGDIR
, buf
,
1629 strlen(QSETWORKINGDIR
)) == 0) {
1630 // Silly, but we can only reply OK, even if the working directory is
1631 // bad. Errors will be reported when we try to execute the actual
1633 send_packet ("OK", noackmode
);
1634 // Free any previously set working_dir
1637 if (!split_hexdecode(buf
, QSETWORKINGDIR
, ":", &working_dir
)) {
1638 continue; // We cannot report the error to gdb...
1640 DEBUG(1, "set working dir to: %s\n", working_dir
);
1641 } else if (strncmp(XFER
, buf
, strlen(XFER
)) == 0) {
1642 char *buf_dup
= strdup(buf
);
1643 DEBUG(1, "strdup: buf_dup %s\n", buf_dup
);
1645 const char *delim
= ":";
1646 size_t count
= count_delims(delim
[0], buf
);
1648 strsep(&buf_dup
, delim
);
1649 strsep(&buf_dup
, delim
);
1650 strsep(&buf_dup
, delim
);
1651 char *decoded_string
= decode_hexstring (buf_dup
, 0, 0);
1652 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string
, buf_dup
);
1653 free (decoded_string
);
1657 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf
);
1661 // Whether we could decode it or not, we cannot handle it now. We
1662 // need valgrind gdbserver to properly reply. So error out here.
1663 send_packet ("E00", noackmode
);
1664 } else if (strncmp(QTSTATUS
, buf
, strlen(QTSTATUS
)) == 0) {
1665 // We don't support trace experiments
1666 DEBUG(1, "Got QTSTATUS\n");
1667 send_packet ("", noackmode
);
1668 } else if (strcmp("qfThreadInfo", buf
) == 0) {
1669 DEBUG(1, "Got qfThreadInfo\n");
1670 /* There are no threads yet, reply 'l' end of list. */
1671 send_packet ("l", noackmode
);
1672 } else if (buf
[0] != '\0') {
1673 // We didn't understand.
1674 DEBUG(1, "Unknown packet received: '%s'\n", buf
);
1675 bad_unknown_packets
++;
1676 if (bad_unknown_packets
> 10) {
1677 DEBUG(1, "Too many bad/unknown packets received\n");
1680 send_packet ("", noackmode
);
1683 DEBUG(1, "done doing multi stuff...\n");
1688 shutting_down
= True
;
1693 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1694 encountered. q_buf is the qSupported packet received from gdb. */
1696 void gdb_relay(int pid
, int send_noack_mode
, char *q_buf
)
1698 int from_pid
= -1; /* fd to read from pid */
1699 int to_pid
= -1; /* fd to write to pid */
1701 int shutdown_loop
= 0;
1702 TSFPRINTF(stderr
, "relaying data between gdb and process %d\n", pid
);
1704 if (max_invoke_ms
> 0)
1705 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1706 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1707 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1708 acquire_lock(shared_mem_fd
, pid
);
1710 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
|O_NONBLOCK
,
1711 "read mode from pid");
1713 sigusr1_fd
= to_pid
; /* allow simulating user typing control-c */
1715 Bool waiting_for_noack_mode
= False
;
1716 Bool waiting_for_qsupported
= False
;
1717 if(send_noack_mode
) {
1718 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid
, from_pid
);
1719 write_buf(to_pid
, "$QStartNoAckMode#b0", 19,
1720 "write start no ack mode",
1722 waiting_for_noack_mode
= True
;
1728 struct pollfd pollfds
[NumConnectionKind
];
1730 /* watch data written by gdb, watch POLLERR on both gdb fd */
1731 pollfds
[FROM_GDB
].fd
= from_gdb
;
1732 pollfds
[FROM_GDB
].events
= POLLIN
;
1733 pollfds
[FROM_GDB
].revents
= 0;
1734 pollfds
[TO_GDB
].fd
= to_gdb
;
1735 pollfds
[TO_GDB
].events
= 0;
1736 pollfds
[TO_GDB
].revents
= 0;
1738 /* watch data written by pid, watch POLLERR on both pid fd */
1739 pollfds
[FROM_PID
].fd
= from_pid
;
1740 pollfds
[FROM_PID
].events
= POLLIN
;
1741 pollfds
[FROM_PID
].revents
= 0;
1742 pollfds
[TO_PID
].fd
= to_pid
;
1743 pollfds
[TO_PID
].events
= 0;
1744 pollfds
[TO_PID
].revents
= 0;
1750 : -1 /* infinite */));
1751 DEBUG(2, "poll ret %d errno %d\n", ret
, errno
);
1753 /* check for unexpected error */
1754 if (ret
<= 0 && errno
!= EINTR
) {
1755 ERROR(errno
, "unexpected poll ret %d\n", ret
);
1756 shutting_down
= True
;
1760 /* check for data to read */
1761 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1762 if (pollfds
[ck
].revents
& POLLIN
) {
1765 if (waiting_for_noack_mode
|| waiting_for_qsupported
)
1766 break; /* Don't add any messages while vgdb is talking. */
1767 if (!read_from_gdb_write_to_pid(to_pid
))
1768 shutting_down
= True
;
1771 // First handle any messages from vgdb
1772 if (waiting_for_noack_mode
) {
1773 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1775 buflen
= getpkt(buf
, from_pid
, to_pid
);
1776 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1778 ERROR(0, "no ack mode: unexpected buflen %zu, buf %s\n",
1781 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1783 waiting_for_noack_mode
= False
;
1785 /* Propagate qSupported to valgrind, we already replied. */
1786 if (q_buf
!= NULL
&& q_buf
[0] != '\0') {
1787 char *pkt
= create_packet (q_buf
);
1788 write_buf(to_pid
, pkt
, strlen(pkt
),
1789 "write qSupported", /* notify */ True
);
1791 waiting_for_qsupported
= True
;
1793 } else if (waiting_for_qsupported
) {
1794 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1796 buflen
= getpkt(buf
, from_pid
, to_pid
);
1797 /* Should we sanity check the result? */
1799 waiting_for_qsupported
= False
;
1801 ERROR(0, "Unexpected getpkt for qSupported reply: %zu\n",
1804 } else if (!read_from_pid_write_to_gdb(from_pid
))
1805 shutting_down
= True
;
1807 default: XERROR(0, "unexpected POLLIN on %s\n",
1808 ppConnectionKind(ck
));
1813 /* check for an fd being in error condition */
1814 for (ck
= 0; ck
< NumConnectionKind
; ck
++) {
1815 if (pollfds
[ck
].revents
& POLLERR
) {
1816 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1817 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1818 invoker_valgrind_dying();
1819 shutting_down
= True
;
1821 if (pollfds
[ck
].revents
& POLLHUP
) {
1822 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1823 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1824 invoker_valgrind_dying();
1825 shutting_down
= True
;
1827 if (pollfds
[ck
].revents
& POLLNVAL
) {
1828 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1829 ppConnectionKind(ck
), pollfds
[ck
].fd
);
1830 invoker_valgrind_dying();
1831 shutting_down
= True
;
1835 if (shutting_down
) {
1836 /* we let some time to the final packets to be transferred */
1838 if (shutdown_loop
> 3)
1842 close_connection(to_pid
, from_pid
);
1845 static int packet_len_for_command(char *cmd
)
1847 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1848 return 7+ 2*strlen(cmd
) +3 + 1;
1851 /* hyper-minimal protocol implementation that
1852 sends the provided commands (using qRcmd packets)
1853 and read and display their replies. */
1855 void standalone_send_commands(int pid
,
1859 int from_pid
= -1; /* fd to read from pid */
1860 int to_pid
= -1; /* fd to write to pid */
1865 unsigned char cksum
;
1867 char buf
[PBUFSIZ
+1]; // +1 for trailing \0
1872 if (max_invoke_ms
> 0 || cmd_time_out
!= NEVER
)
1873 pthread_create(&invoke_gdbserver_in_valgrind_thread
, NULL
,
1874 invoke_gdbserver_in_valgrind
, (void *) &pid
);
1876 to_pid
= open_fifo(from_gdb_to_pid
, O_WRONLY
, "write to pid");
1877 acquire_lock(shared_mem_fd
, pid
);
1879 /* first send a C-c \003 to pid, so that it wakes up the process
1880 After that, we can open the fifo from the pid in read mode
1881 We then start to wait for packets (normally first a resume reply)
1882 At that point, we send our command and expect replies */
1885 while (!write_buf(to_pid
, buf
, 1,
1886 "write \\003 to wake up", /* notify */ True
)) {
1887 /* If write fails, retries up to 10 times every 0.5 seconds
1888 This aims at solving the race condition described in
1889 remote-utils.c remote_finish function. */
1893 XERROR(errno
, "failed to send wake up char after 10 trials\n");
1895 from_pid
= open_fifo(to_gdb_from_pid
, O_RDONLY
,
1896 "read cmd result from pid");
1898 /* Enable no ack mode. */
1899 write_buf(to_pid
, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1901 buflen
= getpkt(buf
, from_pid
, to_pid
);
1902 if (buflen
!= 2 || strcmp(buf
, "OK") != 0) {
1904 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen
);
1906 ERROR(0, "no ack mode: unexpected packet %s\n", buf
);
1909 for (nc
= 0; nc
<= last_command
; nc
++) {
1910 TSFPRINTF(stderr
, "sending command %s to pid %d\n", commands
[nc
], pid
);
1912 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1913 hexcommand
= vmalloc(packet_len_for_command(commands
[nc
]));
1915 strcat(hexcommand
, "$qRcmd,");
1916 for (size_t nci
= 0; nci
< strlen(commands
[nc
]); nci
++) {
1917 sprintf(hex
, "%02x", (unsigned char) commands
[nc
][nci
]);
1918 // Need to use unsigned char, to avoid sign extension.
1919 strcat(hexcommand
, hex
);
1921 /* checksum (but without the $) */
1923 for (hi
= 1; hi
< strlen(hexcommand
); hi
++)
1924 cksum
+=hexcommand
[hi
];
1925 strcat(hexcommand
, "#");
1926 sprintf(hex
, "%02x", cksum
);
1927 strcat(hexcommand
, hex
);
1928 write_buf(to_pid
, hexcommand
, strlen(hexcommand
),
1929 "writing hex command to pid", /* notify */ True
);
1931 /* we exit of the below loop explicitly when the command has
1932 been handled or because a signal handler will set
1934 while (!shutting_down
) {
1935 buflen
= getpkt(buf
, from_pid
, to_pid
);
1937 ERROR(0, "error reading packet\n");
1939 invoker_valgrind_dying();
1942 if (strlen(buf
) == 0) {
1943 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1946 if (strcmp(buf
, "OK") == 0) {
1947 DEBUG(1, "OK packet rcvd\n");
1950 if (buf
[0] == 'E') {
1952 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1956 if (buf
[0] == 'W') {
1957 DEBUG(0, "W stopped packet rcvd: %s\n", buf
);
1960 if (buf
[0] == 'T') {
1961 DEBUG(1, "T resume reply packet received: %s\n", buf
);
1965 /* must be here an O packet with hex encoded string reply
1966 => decode and print it */
1967 if (buf
[0] != 'O') {
1968 DEBUG(0, "expecting O packet, received: %s\n", buf
);
1972 char buf_print
[buflen
/2 + 1];
1973 for (i
= 1; i
< buflen
; i
= i
+ 2)
1974 buf_print
[i
/2] = (fromhex(*(buf
+i
)) << 4)
1975 + fromhex(*(buf
+i
+1));
1976 buf_print
[buflen
/2] = 0;
1977 printf("%s", buf_print
);
1983 shutting_down
= True
;
1985 close_connection(to_pid
, from_pid
);
1988 /* report to user the existence of a vgdb-able valgrind process
1990 Note: this function does not use XERROR if an error is encountered
1991 while producing the command line for pid, as this is not critical
1992 and at least on MacOS, reading cmdline is not available. */
1994 void report_pid(int pid
, Bool on_stdout
)
1996 char cmdline_file
[50]; // large enough
1999 FILE *out
= on_stdout
? stdout
: stderr
;
2001 TSFPRINTF(out
, "use --pid=%d for ", pid
);
2003 sprintf(cmdline_file
, "/proc/%d/cmdline", pid
);
2004 fd
= open(cmdline_file
, O_RDONLY
| O_CLOEXEC
);
2006 DEBUG(1, "error opening cmdline file %s %s\n",
2007 cmdline_file
, strerror(errno
));
2008 fprintf(out
, "(could not open process command line)\n");
2010 #define MAX_CMDLINE 4096
2011 char cmdline
[MAX_CMDLINE
];
2013 while (nr_read
< MAX_CMDLINE
- 1) {
2014 ssize_t sz
= read(fd
, cmdline
, MAX_CMDLINE
- nr_read
- 1);
2018 if (errno
== EINTR
|| errno
== EAGAIN
)
2021 DEBUG(1, "error reading cmdline file %s %s\n",
2022 cmdline_file
, strerror(errno
));
2023 fprintf(out
, "(error reading process command line)\n");
2031 for (i
= 0; i
< nr_read
; i
++)
2032 if (cmdline
[i
] == 0)
2034 cmdline
[nr_read
] = 0;
2036 fprintf(out
, "%s", cmdline
);
2047 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
2048 "vgdb (valgrind gdb) has two usages\n"
2049 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
2050 " The OPTION(s) must be followed by the command to send\n"
2051 " To send more than one command, separate the commands with -c\n"
2052 " 2. relay application between gdb and a Valgrind gdbserver.\n"
2053 " Only OPTION(s) can be given.\n"
2055 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
2056 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
2057 " [--port=<portnr>\n"
2058 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
2059 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
2061 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
2062 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
2063 " if you want to change the prefix (default %s) for the FIFOs communication\n"
2064 " between the Valgrind gdbserver and vgdb.\n"
2065 " --wait (default 0) tells vgdb to check during the specified number\n"
2066 " of seconds if a Valgrind gdbserver can be found.\n"
2067 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
2068 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
2069 " process is blocked in a system call).\n"
2070 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
2071 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
2072 " gdbserver has not processed a command after number seconds\n"
2073 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
2074 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
2075 " --vargs everything that follows is an argument for valgrind.\n"
2076 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
2077 " -T arg tells to add timestamps to vgdb information messages.\n"
2078 " -D arg tells to show shared mem status and then exit.\n"
2079 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
2081 " -h --help shows this message\n"
2082 #ifdef VG_GDBSCRIPTS_DIR
2083 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
2085 " To get help from the Valgrind gdbserver, use vgdb help\n"
2086 "\n", vgdb_prefix_default()
2087 #ifdef VG_GDBSCRIPTS_DIR
2088 , VG_GDBSCRIPTS_DIR
"/valgrind-monitor.py"
2091 invoker_restrictions_msg();
2094 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
2097 else if arg_pid == -1, waits maximum check_trials seconds to discover
2098 a valgrind pid appearing.
2100 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2101 with gdbserver activated.
2103 Returns the pid to work with
2104 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2107 int search_arg_pid(int arg_pid
, int check_trials
, Bool show_list
)
2112 if (arg_pid
== 0 || arg_pid
< -1) {
2113 TSFPRINTF(stderr
, "vgdb error: invalid pid %d given\n", arg_pid
);
2114 early_exit(1, "vgdb error: invalid pid given");
2116 /* search for a matching named fifo.
2117 If we have been given a pid, we will check that the matching FIFO is
2118 there (or wait the nr of check_trials for this to appear).
2119 If no pid has been given, then if we find only one FIFO,
2120 we will use this to build the pid to use.
2121 If we find multiple processes with valid FIFO, we report them and will
2122 exit with an error. */
2124 char *vgdb_dir_name
= vmalloc(strlen (vgdb_prefix
) + 3);
2127 int nr_valid_pid
= 0;
2128 const char *suffix
= "-from-vgdb-to-"; /* followed by pid */
2129 char *vgdb_format
= vmalloc(strlen(vgdb_prefix
) + strlen(suffix
) + 1);
2131 strcpy(vgdb_format
, vgdb_prefix
);
2132 strcat(vgdb_format
, suffix
);
2134 if (strchr(vgdb_prefix
, '/') != NULL
) {
2135 strcpy(vgdb_dir_name
, vgdb_prefix
);
2136 for (is
= strlen(vgdb_prefix
) - 1; is
>= 0; is
--)
2137 if (vgdb_dir_name
[is
] == '/') {
2138 vgdb_dir_name
[is
+1] = '\0';
2142 strcpy(vgdb_dir_name
, "");
2145 DEBUG(1, "searching pid in directory %s format %s\n",
2146 vgdb_dir_name
, vgdb_format
);
2148 /* try to find FIFOs with valid pid.
2149 On exit of the loop, pid is set to:
2150 the last pid found if show_list (or -1 if no process was listed)
2151 -1 if no FIFOs matching a running process is found
2152 -2 if multiple FIFOs of running processes are found
2153 otherwise it is set to the (only) pid found that can be debugged
2155 for (i
= 0; i
< check_trials
; i
++) {
2156 DEBUG(1, "check_trial %d \n", i
);
2158 /* wait one second before checking again */
2161 vgdb_dir
= opendir(strlen(vgdb_dir_name
) ? vgdb_dir_name
: "./");
2162 if (vgdb_dir
== NULL
)
2164 "vgdb error: opening directory %s searching vgdb fifo\n",
2167 errno
= 0; /* avoid complain if vgdb_dir is empty */
2168 while ((f
= readdir(vgdb_dir
))) {
2170 char pathname
[strlen(vgdb_dir_name
) + strlen(f
->d_name
) + 1];
2174 strcpy(pathname
, vgdb_dir_name
);
2175 strcat(pathname
, f
->d_name
);
2176 DEBUG(3, "checking pathname is FIFO %s\n", pathname
);
2177 if (stat(pathname
, &st
) != 0) {
2178 if (debuglevel
>= 3)
2179 ERROR(errno
, "vgdb error: stat %s searching vgdb fifo\n",
2181 } else if (S_ISFIFO(st
.st_mode
)) {
2182 DEBUG(3, "trying FIFO %s\n", pathname
);
2183 if (strncmp(pathname
, vgdb_format
,
2184 strlen(vgdb_format
)) == 0) {
2185 newpid
= strtol(pathname
+ strlen(vgdb_format
),
2187 if (*wrongpid
== '-' && newpid
> 0
2188 && kill(newpid
, 0) == 0) {
2191 report_pid(newpid
, /*on_stdout*/ True
);
2193 } else if (arg_pid
!= -1) {
2194 if (arg_pid
== newpid
) {
2197 } else if (nr_valid_pid
> 1) {
2198 if (nr_valid_pid
== 2) {
2201 "no --pid= arg given"
2202 " and multiple valgrind pids found:\n");
2203 report_pid(pid
, /*on_stdout*/ False
);
2206 report_pid(newpid
, /*on_stdout*/ False
);
2213 errno
= 0; /* avoid complain if at the end of vgdb_dir */
2215 if (f
== NULL
&& errno
!= 0) {
2216 ERROR(errno
, "vgdb error: reading directory %s for vgdb fifo\n",
2218 early_exit(1, "vgdb error reading vgdb fifo directory");
2226 free(vgdb_dir_name
);
2232 } else if (pid
== -1) {
2233 if (arg_pid
== -1) {
2234 TSFPRINTF(stderr
, "vgdb error: no FIFO found and no pid given\n");
2235 early_exit(1, "vgdb error: no FIFO found and no pid given");
2237 TSFPRINTF(stderr
, "vgdb error: no FIFO found matching pid %d\n",
2239 early_exit(1, "vgdb error: no FIFO found matching the give pid");
2242 else if (pid
== -2) {
2243 early_exit(1, "no --pid= arg_pid given and multiple valgrind pids found.");
2249 abort (); // Impossible
2252 /* return true if the numeric value of an option of the
2253 form --xxxxxxxxx=<number> could properly be extracted
2254 from arg. If True is returned, *value contains the
2257 Bool
numeric_val(char* arg
, int *value
)
2259 const char *eq_pos
= strchr(arg
, '=');
2261 long long int long_value
;
2266 long_value
= strtoll(eq_pos
+1, &wrong
, 10);
2267 if (long_value
< 0 || long_value
> INT_MAX
)
2272 *value
= (int) long_value
;
2276 /* true if arg matches the provided option */
2278 Bool
is_opt(char* arg
, const char *option
)
2280 int option_len
= strlen(option
);
2281 if (option
[option_len
-1] == '=')
2282 return (0 == strncmp(option
, arg
, option_len
));
2284 return (0 == strcmp(option
, arg
));
2287 /* Parse command lines options. If error(s), exits.
2288 Otherwise returns the options in *p_... args.
2289 commands must be big enough for the commands extracted from argv.
2290 On return, *p_last_command gives the position in commands where
2291 the last command has been allocated (using vmalloc). */
2293 void parse_options(int argc
, char** argv
,
2294 Bool
*p_show_shared_mem
,
2298 int *p_check_trials
,
2300 int *p_last_command
,
2303 Bool show_shared_mem
= False
;
2304 Bool show_list
= False
;
2305 Bool multi_mode
= False
;
2307 int check_trials
= 1;
2308 int last_command
= -1;
2314 for (i
= 1; i
< argc
; i
++) {
2315 if (is_opt(argv
[i
], "--help") || is_opt(argv
[i
], "-h")) {
2317 early_exit(0, "--help requested");
2318 } else if (is_opt(argv
[i
], "-d")) {
2320 } else if (is_opt(argv
[i
], "-D")) {
2321 show_shared_mem
= True
;
2322 } else if (is_opt(argv
[i
], "-l")) {
2324 } else if (is_opt(argv
[i
], "--multi")) {
2326 } else if (is_opt(argv
[i
], "-T")) {
2328 } else if (is_opt(argv
[i
], "--pid=")) {
2330 if (!numeric_val(argv
[i
], &newpid
)) {
2331 TSFPRINTF(stderr
, "invalid --pid argument %s\n", argv
[i
]);
2333 } else if (arg_pid
!= -1) {
2334 TSFPRINTF(stderr
, "multiple --pid arguments given\n");
2339 } else if (is_opt(argv
[i
], "--wait=")) {
2340 if (!numeric_val(argv
[i
], &check_trials
)) {
2341 TSFPRINTF(stderr
, "invalid --wait argument %s\n", argv
[i
]);
2344 } else if (is_opt(argv
[i
], "--max-invoke-ms=")) {
2345 if (!numeric_val(argv
[i
], &max_invoke_ms
)) {
2346 TSFPRINTF(stderr
, "invalid --max-invoke-ms argument %s\n", argv
[i
]);
2349 } else if (is_opt(argv
[i
], "--cmd-time-out=")) {
2350 if (!numeric_val(argv
[i
], &cmd_time_out
)) {
2351 TSFPRINTF(stderr
, "invalid --cmd-time-out argument %s\n", argv
[i
]);
2354 } else if (is_opt(argv
[i
], "--port=")) {
2355 if (!numeric_val(argv
[i
], &int_port
)) {
2356 TSFPRINTF(stderr
, "invalid --port argument %s\n", argv
[i
]);
2359 } else if (is_opt(argv
[i
], "--vgdb-prefix=")) {
2361 // was specified more than once on the command line
2362 // ignore earlier uses
2365 vgdb_prefix
= strdup (argv
[i
] + 14);
2366 } else if (is_opt(argv
[i
], "--valgrind=")) {
2367 char *path
= argv
[i
] + 11;
2368 /* Compute the absolute path. */
2369 valgrind_path
= realpath(path
, NULL
);
2370 if (!valgrind_path
) {
2371 TSFPRINTF(stderr
, "%s is not a correct path. %s, exiting.\n",
2372 path
, strerror (errno
));
2373 early_exit(1, "incorrect valgrind path");
2375 DEBUG(2, "valgrind's real path: %s\n", valgrind_path
);
2376 } else if (is_opt(argv
[i
], "--vargs")) {
2377 // Everything that follows now is an argument for valgrind
2378 // No other options (or commands) can follow
2379 // argc - i is the number of left over arguments
2380 // allocate enough space, put all args in it.
2381 cvargs
= argc
- i
- 1;
2382 vargs
= vmalloc (cvargs
* sizeof(*vargs
));
2384 for (int j
= 0; i
< argc
; i
++) {
2388 } else if (is_opt(argv
[i
], "-c")) {
2390 commands
[last_command
] = vmalloc(1);
2391 commands
[last_command
][0] = '\0';
2392 } else if (0 == strncmp(argv
[i
], "-", 1)) {
2393 TSFPRINTF(stderr
, "unknown or invalid argument %s\n", argv
[i
]);
2397 if (last_command
== -1) {
2398 /* only one command, no -c command indicator */
2400 commands
[last_command
] = vmalloc(1);
2401 commands
[last_command
][0] = '\0';
2403 len
= strlen(commands
[last_command
]);
2404 commands
[last_command
] = vrealloc(commands
[last_command
],
2405 len
+ 1 + strlen(argv
[i
]) + 1);
2407 strcat(commands
[last_command
], " ");
2408 strcat(commands
[last_command
], argv
[i
]);
2409 if (packet_len_for_command(commands
[last_command
]) > PBUFSIZ
) {
2410 TSFPRINTF(stderr
, "command %s too long\n", commands
[last_command
]);
2417 if (vgdb_prefix
== NULL
)
2418 vgdb_prefix
= vgdb_prefix_default();
2423 || last_command
!= -1)) {
2426 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2429 if (isatty(from_gdb
)
2433 && last_command
== -1) {
2436 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2439 if (show_shared_mem
&& show_list
) {
2442 "Can't use both -D and -l options\n");
2445 if (max_invoke_ms
> 0
2446 && cmd_time_out
!= NEVER
2447 && (cmd_time_out
* 1000) <= max_invoke_ms
) {
2450 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2453 if (show_list
&& arg_pid
!= -1) {
2456 "Can't use both --pid and -l options\n");
2459 if (int_port
> 0 && last_command
!= -1) {
2462 "Can't use --port to send commands\n");
2465 if (arg_errors
> 0) {
2466 TSFPRINTF(stderr
, "args error. Try `vgdb --help` for more information\n");
2467 early_exit(1, "invalid args given to vgdb");
2470 *p_show_shared_mem
= show_shared_mem
;
2471 *p_show_list
= show_list
;
2472 *p_multi_mode
= multi_mode
;
2473 *p_arg_pid
= arg_pid
;
2474 *p_check_trials
= check_trials
;
2476 *p_last_command
= last_command
;
2479 int main(int argc
, char** argv
)
2484 Bool show_shared_mem
;
2491 char *commands
[argc
]; // we will never have more commands than args.
2493 parse_options(argc
, argv
,
2503 /* when we are working as a relay for gdb, handle some signals by
2504 only reporting them (according to debug level). Also handle these
2505 when ptrace will be used: vgdb must clean up the ptrace effect before
2507 if (max_invoke_ms
> 0 || last_command
== -1)
2511 pid
= search_arg_pid(arg_pid
, check_trials
, show_list
);
2513 /* We pass 1 for check_trials here, because search_arg_pid already waited. */
2514 prepare_fifos_and_shared_mem(pid
, 1);
2520 wait_for_gdb_connect(in_port
);
2522 if (show_shared_mem
) {
2525 "written_by_vgdb %d "
2526 "seen_by_valgrind %d\n",
2529 VS_seen_by_valgrind
);
2530 TSFPRINTF(stderr
, "vgdb pid %d\n", VS_vgdb_pid
);
2531 early_exit(0, "-D arg to show shared memory and exit given.");
2535 /* check_trials is the --wait argument in seconds, defaulting to 1
2537 do_multi_mode (check_trials
, in_port
);
2538 } else if (last_command
>= 0) {
2539 standalone_send_commands(pid
, last_command
, commands
);
2541 gdb_relay(pid
, 0, NULL
);
2545 free(valgrind_path
);
2547 cleanup_fifos_and_shared_mem();
2549 for (i
= 0; i
<= last_command
; i
++)