Remove source file added to EXTRA_DIST in error
[valgrind.git] / coregrind / vgdb.c
blob9a9b90e5859dfdcaf8420aecb66c2c98a032d247
1 /*--------------------------------------------------------------------*/
2 /*--- Relay between gdb and gdbserver embedded in valgrind vgdb.c ---*/
3 /*--------------------------------------------------------------------*/
5 /*
6 This file is part of Valgrind, a dynamic binary instrumentation
7 framework.
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.
27 #include "vgdb.h"
29 #include "config.h"
31 #include <assert.h>
32 #include <dirent.h>
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <limits.h>
36 #include <poll.h>
37 #include <pthread.h>
38 #include <signal.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <netinet/in.h>
44 #include <sys/mman.h>
45 #include <sys/socket.h>
46 #include <sys/stat.h>
47 #include <sys/time.h>
49 /* vgdb has two usages:
50 1. relay application between gdb and the gdbserver embedded in valgrind.
51 2. standalone to send monitor commands to a running valgrind-ified process
53 It is made of a main program which reads arguments. If no
54 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
55 assumed.
57 As relay application, vgdb reads bytes from gdb on stdin and
58 writes these bytes to valgrind. Bytes read from valgrind are
59 written to gdb on stdout. Read/Write from/to valgrind is done
60 using FIFOs. There is one thread reading from stdin, writing to
61 valgrind on a FIFO. There is one thread reading from valgrind on a
62 FIFO, writing to gdb on stdout
64 As a standalone utility, vgdb builds command packets to write to valgrind,
65 sends it and reads the reply. The same two threads are used to write/read.
66 Once all the commands are sent and their replies received, vgdb will exit.
69 int debuglevel;
70 Bool timestamp = False;
71 char timestamp_out[20];
72 static char *vgdb_prefix = NULL;
74 char *timestamp_str (Bool produce)
76 static char out[50];
77 char *ptr;
78 struct timeval dbgtv;
79 struct tm *ts_tm;
81 if (produce) {
82 gettimeofday(&dbgtv, NULL);
83 ts_tm = localtime(&dbgtv.tv_sec);
84 ptr = out + strftime(out, sizeof(out), "%H:%M:%S", ts_tm);
85 sprintf(ptr, ".%6.6ld ", dbgtv.tv_usec);
86 } else {
87 out[0] = 0;
89 return out;
92 /* Will be set to True when any condition indicating we have to shutdown
93 is encountered. */
94 Bool shutting_down = False;
96 VgdbShared32 *shared32;
97 VgdbShared64 *shared64;
98 #define VS_written_by_vgdb (shared32 != NULL ? \
99 shared32->written_by_vgdb \
100 : shared64->written_by_vgdb)
101 #define VS_seen_by_valgrind (shared32 != NULL ? \
102 shared32->seen_by_valgrind \
103 : shared64->seen_by_valgrind)
105 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
107 void *vmalloc(size_t size)
109 void * mem = malloc(size);
110 if (mem == NULL)
111 XERROR(errno, "can't allocate memory\n");
112 return mem;
115 void *vrealloc(void *ptr,size_t size)
117 void * mem = realloc(ptr, size);
118 if (mem == NULL)
119 XERROR(errno, "can't reallocate memory\n");
120 return mem;
123 /* Return the name of a directory for temporary files. */
124 static
125 const char *vgdb_tmpdir(void)
127 const char *tmpdir;
129 tmpdir = getenv("TMPDIR");
130 if (tmpdir == NULL || *tmpdir == '\0')
131 tmpdir = VG_TMPDIR;
132 if (tmpdir == NULL || *tmpdir == '\0')
133 tmpdir = "/tmp"; /* fallback */
135 return tmpdir;
138 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
139 to communicate with valgrind */
140 static
141 char *vgdb_prefix_default(void)
143 static HChar *prefix;
145 if (prefix == NULL) {
146 const char *tmpdir = vgdb_tmpdir();
147 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
148 strcpy(prefix, tmpdir);
149 strcat(prefix, "/vgdb-pipe");
151 return prefix;
154 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
155 static
156 void add_written(int nrw)
158 if (shared32 != NULL)
159 shared32->written_by_vgdb += nrw;
160 else if (shared64 != NULL)
161 shared64->written_by_vgdb += nrw;
162 else
163 assert(0);
166 static int shared_mem_fd = -1;
167 static
168 void map_vgdbshared(char* shared_mem)
170 struct stat fdstat;
171 void **s;
172 shared_mem_fd = open(shared_mem, O_RDWR);
173 /* shared_mem_fd will not be closed till vgdb exits. */
175 if (shared_mem_fd == -1)
176 XERROR(errno, "error opening %s shared memory file\n", shared_mem);
178 if (fstat(shared_mem_fd, &fdstat) != 0)
179 XERROR(errno, "fstat\n");
181 if (fdstat.st_size == sizeof(VgdbShared64))
182 s = (void*) &shared64;
183 else if (fdstat.st_size == sizeof(VgdbShared32))
184 s = (void*) &shared32;
185 else
186 #if VEX_HOST_WORDSIZE == 8
187 XERROR(0,
188 "error size shared memory file %s.\n"
189 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
190 shared_mem,
191 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
192 (long int)fdstat.st_size);
193 #elif VEX_HOST_WORDSIZE == 4
194 XERROR(0,
195 "error size shared memory file %s.\n"
196 "expecting size %d (32bits) got %ld.\n",
197 shared_mem,
198 (int) sizeof(VgdbShared32),
199 fdstat.st_size);
200 #else
201 # error "unexpected wordsize"
202 #endif
204 #if VEX_HOST_WORDSIZE == 4
205 if (shared64 != NULL)
206 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
207 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
208 #endif
210 *s = (void*) mmap(NULL, fdstat.st_size,
211 PROT_READ|PROT_WRITE, MAP_SHARED,
212 shared_mem_fd, 0);
214 if (*s == (void *) -1)
215 XERROR(errno, "error mmap shared memory file %s\n", shared_mem);
219 /* This function loops till shutting_down becomes true. In this loop,
220 it verifies if valgrind process is reading the characters written
221 by vgdb. The verification is done every max_invoke_ms ms. If
222 valgrind is not reading characters, it will use invoker_invoke_gdbserver
223 to ensure that the gdbserver code is called soon by valgrind. */
224 static int max_invoke_ms = 100;
225 #define NEVER 99999999
226 static int cmd_time_out = NEVER;
227 static
228 void *invoke_gdbserver_in_valgrind(void *v_pid)
230 struct timeval cmd_max_end_time;
231 Bool cmd_started = False;
232 struct timeval invoke_time;
234 int pid = *(int *)v_pid;
235 int written_by_vgdb_before_sleep;
236 int seen_by_valgrind_before_sleep;
238 int invoked_written = -1;
239 unsigned int usecs;
241 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
243 while (!shutting_down) {
244 written_by_vgdb_before_sleep = VS_written_by_vgdb;
245 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
246 DEBUG(3,
247 "written_by_vgdb_before_sleep %d "
248 "seen_by_valgrind_before_sleep %d\n",
249 written_by_vgdb_before_sleep,
250 seen_by_valgrind_before_sleep);
251 if (cmd_time_out != NEVER
252 && !cmd_started
253 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
254 /* A command was started. Record the time at which it was started. */
255 DEBUG(1, "IO for command started\n");
256 gettimeofday(&cmd_max_end_time, NULL);
257 cmd_max_end_time.tv_sec += cmd_time_out;
258 cmd_started = True;
260 if (max_invoke_ms > 0) {
261 usecs = 1000 * max_invoke_ms;
262 gettimeofday(&invoke_time, NULL);
263 invoke_time.tv_sec += max_invoke_ms / 1000;
264 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
265 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
266 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
267 } else {
268 usecs = 0;
270 if (cmd_started) {
271 // 0 usecs here means the thread just has to check gdbserver eats
272 // the characters in <= cmd_time_out seconds.
273 // We will just wait by 1 second max at a time.
274 if (usecs == 0 || usecs > 1000 * 1000)
275 usecs = 1000 * 1000;
277 usleep(usecs);
279 /* If nothing happened during our sleep, let's try to wake up valgrind
280 or check for cmd time out. */
281 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
282 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
283 && VS_written_by_vgdb > VS_seen_by_valgrind) {
284 struct timeval now;
285 gettimeofday(&now, NULL);
286 DEBUG(2,
287 "after sleep "
288 "written_by_vgdb %d "
289 "seen_by_valgrind %d "
290 "invoked_written %d\n",
291 VS_written_by_vgdb,
292 VS_seen_by_valgrind,
293 invoked_written);
294 /* if the pid does not exist anymore, we better stop */
295 if (kill(pid, 0) != 0)
296 XERROR(errno,
297 "invoke_gdbserver_in_valgrind: "
298 "check for pid %d existence failed\n", pid);
299 if (cmd_started) {
300 if (timercmp(&now, &cmd_max_end_time, >))
301 XERROR(0,
302 "pid %d did not handle a command in %d seconds\n",
303 pid, cmd_time_out);
305 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
306 /* only need to wake up if the nr written has changed since
307 last invoke. */
308 if (invoked_written != written_by_vgdb_before_sleep) {
309 if (invoker_invoke_gdbserver(pid)) {
310 /* If invoke successful, no need to invoke again
311 for the same value of written_by_vgdb_before_sleep. */
312 invoked_written = written_by_vgdb_before_sleep;
316 } else {
317 // Something happened => restart timer check.
318 if (cmd_time_out != NEVER) {
319 DEBUG(2, "some IO was done => restart command\n");
320 cmd_started = False;
324 pthread_cleanup_pop(0);
325 return NULL;
328 static
329 int open_fifo(const char* name, int flags, const char* desc)
331 int fd;
332 DEBUG(1, "opening %s %s\n", name, desc);
333 fd = open(name, flags);
334 if (fd == -1)
335 XERROR(errno, "error opening %s %s\n", name, desc);
337 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
338 return fd;
341 /* acquire a lock on the first byte of the given fd. If not successful,
342 exits with error.
343 This allows to avoid having two vgdb speaking with the same Valgrind
344 gdbserver as this causes serious headaches to the protocol. */
345 static
346 void acquire_lock(int fd, int valgrind_pid)
348 struct flock fl;
349 fl.l_type = F_WRLCK;
350 fl.l_whence = SEEK_SET;
351 fl.l_start = 0;
352 fl.l_len = 1;
353 if (fcntl(fd, F_SETLK, &fl) < 0) {
354 if (errno == EAGAIN || errno == EACCES) {
355 XERROR(errno,
356 "Cannot acquire lock.\n"
357 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
358 VS_vgdb_pid,
359 valgrind_pid);
360 } else {
361 XERROR(errno, "cannot acquire lock.\n");
365 /* Here, we have the lock. It will be released when fd will be closed. */
366 /* We indicate our pid to Valgrind gdbserver */
367 if (shared32 != NULL)
368 shared32->vgdb_pid = getpid();
369 else if (shared64 != NULL)
370 shared64->vgdb_pid = getpid();
371 else
372 assert(0);
375 #define PBUFSIZ 16384 /* keep in sync with server.h */
377 /* read some characters from fd.
378 Returns the nr of characters read, -1 if error.
379 desc is a string used in tracing */
380 static
381 int read_buf(int fd, char* buf, const char* desc)
383 int nrread;
384 DEBUG(2, "reading %s\n", desc);
385 nrread = read(fd, buf, PBUFSIZ);
386 if (nrread == -1) {
387 ERROR(errno, "error reading %s\n", desc);
388 return -1;
390 buf[nrread] = '\0';
391 DEBUG(2, "read %s %s\n", desc, buf);
392 return nrread;
395 /* write size bytes from buf to fd.
396 desc is a description of the action for which the write is done.
397 If notify, then add size to the shared cntr indicating to the
398 valgrind process that there is new data.
399 Returns True if write is ok, False if there was a problem. */
400 static
401 Bool write_buf(int fd, const char* buf, int size, const char* desc, Bool notify)
403 int nrwritten;
404 int nrw;
405 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
406 size, buf, notify);
407 nrwritten = 0;
408 while (nrwritten < size) {
409 nrw = write(fd, buf+nrwritten, size - nrwritten);
410 if (nrw == -1) {
411 ERROR(errno, "error write %s\n", desc);
412 return False;
414 nrwritten = nrwritten + nrw;
415 if (notify)
416 add_written(nrw);
418 return True;
421 typedef enum {
422 FROM_GDB,
423 TO_GDB,
424 FROM_PID,
425 TO_PID } ConnectionKind;
426 static const int NumConnectionKind = TO_PID+1;
427 static
428 const char *ppConnectionKind(ConnectionKind con)
430 switch (con) {
431 case FROM_GDB: return "FROM_GDB";
432 case TO_GDB: return "TO_GDB";
433 case FROM_PID: return "FROM_PID";
434 case TO_PID: return "TO_PID";
435 default: return "invalid connection kind";
439 static char *shared_mem;
441 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
442 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
443 /* Returns True in case read/write operations were done properly.
444 Returns False in case of error.
445 to_pid is the file descriptor to write to the process pid. */
446 static
447 Bool read_from_gdb_write_to_pid(int to_pid)
449 char buf[PBUFSIZ+1]; // +1 for trailing \0
450 int nrread;
452 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
453 if (nrread <= 0) {
454 if (nrread == 0)
455 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
456 else
457 DEBUG(1, "error reading bytes from gdb\n");
458 close(from_gdb);
459 shutting_down = True;
460 return False;
462 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
465 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
466 static char *to_gdb_from_pid; /* fifo name to read pid replies */
467 /* Returns True in case read/write operations were done properly.
468 Returns False in case of error.
469 from_pid is the file descriptor to read data from the process pid. */
470 static
471 Bool read_from_pid_write_to_gdb(int from_pid)
473 char buf[PBUFSIZ+1]; // +1 for trailing \0
474 int nrread;
476 nrread = read_buf(from_pid, buf, "from pid");
477 if (nrread <= 0) {
478 if (nrread == 0)
479 DEBUG(1, "read 0 bytes from pid => assume exit\n");
480 else
481 DEBUG(1, "error reading bytes from pid\n");
482 close(from_pid);
483 shutting_down = True;
484 return False;
486 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
489 static
490 void wait_for_gdb_connect(int in_port)
492 struct sockaddr_in addr;
494 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
495 int gdb_connect;
497 if (-1 == listen_gdb) {
498 XERROR(errno, "cannot create socket\n");
501 /* allow address reuse to avoid "address already in use" errors */
503 int one = 1;
504 if (setsockopt(listen_gdb, SOL_SOCKET, SO_REUSEADDR,
505 &one, sizeof(one)) < 0) {
506 XERROR(errno, "cannot enable address reuse\n");
509 memset(&addr, 0, sizeof(addr));
511 addr.sin_family = AF_INET;
512 addr.sin_port = htons((unsigned short int)in_port);
513 addr.sin_addr.s_addr = INADDR_ANY;
515 if (-1 == bind(listen_gdb, (struct sockaddr *)&addr, sizeof(addr))) {
516 XERROR(errno, "bind failed\n");
518 TSFPRINTF(stderr, "listening on port %d ...", in_port);
519 if (-1 == listen(listen_gdb, 1)) {
520 XERROR(errno, "error listen failed\n");
523 gdb_connect = accept(listen_gdb, NULL, NULL);
524 if (gdb_connect < 0) {
525 XERROR(errno, "accept failed\n");
527 fprintf(stderr, "connected.\n");
528 fflush(stderr);
529 close(listen_gdb);
530 from_gdb = gdb_connect;
531 to_gdb = gdb_connect;
534 /* prepares the FIFOs filenames, map the shared memory. */
535 static
536 void prepare_fifos_and_shared_mem(int pid)
538 const HChar *user, *host;
539 unsigned len;
541 user = getenv("LOGNAME");
542 if (user == NULL) user = getenv("USER");
543 if (user == NULL) user = "???";
544 if (strchr(user, '/')) user = "???";
546 host = getenv("HOST");
547 if (host == NULL) host = getenv("HOSTNAME");
548 if (host == NULL) host = "???";
549 if (strchr(host, '/')) host = "???";
551 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
552 from_gdb_to_pid = vmalloc(len);
553 to_gdb_from_pid = vmalloc(len);
554 shared_mem = vmalloc(len);
555 /* below 3 lines must match the equivalent in remote-utils.c */
556 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
557 pid, user, host);
558 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
559 pid, user, host);
560 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
561 pid, user, host);
562 DEBUG(1, "vgdb: using %s %s %s\n",
563 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
565 map_vgdbshared(shared_mem);
568 /* Convert hex digit A to a number. */
570 static int
571 fromhex(int a)
573 if (a >= '0' && a <= '9')
574 return a - '0';
575 else if (a >= 'a' && a <= 'f')
576 return a - 'a' + 10;
577 else
578 XERROR(0, "Reply contains invalid hex digit %c\n", a);
579 return 0;
582 /* Returns next char from fd. -1 if error, -2 if EOF.
583 NB: must always call it with the same fd */
584 static int
585 readchar(int fd)
587 static char buf[PBUFSIZ+1]; // +1 for trailing \0
588 static int bufcnt = 0;
589 static unsigned char *bufp;
590 // unsigned bufp to e.g. avoid having 255 converted to int -1
592 if (bufcnt-- > 0)
593 return *bufp++;
595 bufcnt = read_buf(fd, buf, "static buf readchar");
597 if (bufcnt <= 0) {
598 if (bufcnt == 0) {
599 TSFPRINTF(stderr, "readchar: Got EOF\n");
600 return -2;
601 } else {
602 ERROR(errno, "readchar\n");
603 return -1;
607 bufp = (unsigned char *)buf;
608 bufcnt--;
609 return *bufp++;
612 /* Read a packet from fromfd, with error checking,
613 and store it in BUF.
614 If checksum incorrect, writes a - on ackfd.
615 Returns length of packet, or -1 if error or -2 if EOF. */
616 static int
617 getpkt(char *buf, int fromfd, int ackfd)
619 char *bp;
620 unsigned char csum, c1, c2;
621 int c;
623 while (1) {
624 csum = 0;
626 while (1) {
627 c = readchar(fromfd);
628 if (c == '$')
629 break;
630 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
631 if (c < 0)
632 return c;
635 bp = buf;
636 while (1) {
637 c = readchar(fromfd);
638 if (c < 0)
639 return c;
640 if (c == '#')
641 break;
642 if (c == '*') {
643 int repeat;
644 int r;
645 int prev;
646 prev = *(bp-1);
647 csum += c;
648 repeat = readchar(fromfd);
649 csum += repeat;
650 for (r = 0; r < repeat - 29; r ++)
651 *bp++ = prev;
652 } else {
653 *bp++ = c;
654 csum += c;
657 *bp = 0;
659 c1 = fromhex(readchar (fromfd));
660 c2 = fromhex(readchar (fromfd));
662 if (csum == (c1 << 4) + c2)
663 break;
665 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
666 (c1 << 4) + c2, csum, buf);
667 if (write(ackfd, "-", 1) != 1)
668 ERROR(0, "error when writing - (nack)\n");
669 else
670 add_written(1);
673 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
674 return bp - buf;
677 static int sigint = 0;
678 static int sigterm = 0;
679 static int sigpipe = 0;
680 static int sighup = 0;
681 static int sigusr1 = 0;
682 static int sigalrm = 0;
683 static int sigusr1_fd = -1;
684 static pthread_t invoke_gdbserver_in_valgrind_thread;
686 static
687 void received_signal(int signum)
689 if (signum == SIGINT)
690 sigint++;
691 else if (signum == SIGUSR1) {
692 sigusr1++;
693 if (sigusr1_fd >= 0) {
694 char control_c = '\003';
695 write_buf(sigusr1_fd, &control_c, 1,
696 "write \\003 on SIGUSR1", /* notify */ True);
699 else if (signum == SIGTERM) {
700 shutting_down = True;
701 sigterm++;
702 } else if (signum == SIGHUP) {
703 shutting_down = True;
704 sighup++;
705 } else if (signum == SIGPIPE) {
706 sigpipe++;
707 } else if (signum == SIGALRM) {
708 sigalrm++;
709 #if defined(VGPV_arm_linux_android) \
710 || defined(VGPV_x86_linux_android) \
711 || defined(VGPV_mips32_linux_android) \
712 || defined(VGPV_arm64_linux_android)
713 /* Android has no pthread_cancel. As it also does not have
714 an invoker implementation, there is no need for cleanup action.
715 So, we just do nothing. */
716 DEBUG(1, "sigalrm received, no action on android\n");
717 #else
718 /* Note: we cannot directly invoke restore_and_detach : this must
719 be done by the thread that has attached.
720 We have in this thread pushed a cleanup handler that will
721 cleanup what is needed. */
722 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
723 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
724 #endif
725 } else {
726 ERROR(0, "unexpected signal %d\n", signum);
730 /* install the signal handlers allowing e.g. vgdb to cleanup in
731 case of termination. */
732 static
733 void install_handlers(void)
735 struct sigaction action, oldaction;
737 action.sa_handler = received_signal;
738 sigemptyset(&action.sa_mask);
739 action.sa_flags = 0;
741 /* SIGINT: when user types C-c in gdb, this sends
742 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
743 The later is enough to wakeup the valgrind process. */
744 if (sigaction(SIGINT, &action, &oldaction) != 0)
745 XERROR(errno, "vgdb error sigaction SIGINT\n");
746 /* We might do something more intelligent than just
747 reporting this SIGINT E.g. behave similarly to the gdb: two
748 control-C without feedback from the debugged process would
749 mean to stop debugging it. */
751 /* SIGUSR1: this is used to facilitate automatic testing. When
752 vgdb receives this signal, it will simulate the user typing C-c. */
753 if (sigaction(SIGUSR1, &action, &oldaction) != 0)
754 XERROR(errno, "vgdb error sigaction SIGUSR1\n");
757 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
758 when detaching or similar. A clean shutdown will be done as both
759 the read and write side will detect an end of file. */
760 if (sigaction(SIGTERM, &action, &oldaction) != 0)
761 XERROR(errno, "vgdb error sigaction SIGTERM\n");
763 /* SIGPIPE: can receive this signal when gdb detaches or kill the
764 process debugged: gdb will close its pipes to vgdb. vgdb
765 must resist to this signal to allow a clean shutdown. */
766 if (sigaction(SIGPIPE, &action, &oldaction) != 0)
767 XERROR(errno, "vgdb error sigaction SIGPIPE\n");
769 /* SIGALRM: in case invoke thread is blocked, alarm is used
770 to cleanup. */
771 if (sigaction(SIGALRM, &action, &oldaction) != 0)
772 XERROR(errno, "vgdb error sigaction SIGALRM\n");
774 /* unmask all signals, in case the process that launched vgdb
775 masked some. */
776 if (sigprocmask(SIG_SETMASK, &action.sa_mask, NULL) != 0)
777 XERROR(errno, "vgdb error sigprocmask\n");
780 /* close the FIFOs provided connections, terminate the invoker thread. */
781 static
782 void close_connection(int to_pid, int from_pid)
784 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
785 sigint, sigterm, sighup, sigpipe);
786 /* Note that we do not forward sigterm to the valgrind process:
787 a sigterm signal is (probably) received from gdb if the user wants to
788 kill the debugged process. The kill instruction has been given to
789 the valgrind process, which should execute a clean exit. */
791 /* We first close the connection to pid. The pid will then
792 terminates its gdbserver work. We keep the from pid
793 fifo opened till the invoker thread is finished.
794 This allows the gdbserver to finish sending its last reply. */
795 if (close(to_pid) != 0)
796 ERROR(errno, "close to_pid\n");
798 /* if there is a task that was busy trying to wake up valgrind
799 process, we wait for it to be terminated otherwise threads
800 in the valgrind process can stay stopped if vgdb main
801 exits before the invoke thread had time to detach from
802 all valgrind threads. */
803 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
804 int join;
806 /* It is surprisingly complex to properly shutdown or exit the
807 valgrind process in which gdbserver has been invoked through
808 ptrace. In the normal case (gdb detaches from the process,
809 or process is continued), the valgrind process will reach the
810 breakpoint place. Using ptrace, vgdb will ensure the
811 previous activity of the process is resumed (e.g. restart a
812 blocking system call). The special case is when gdb asks the
813 valgrind process to exit (using either the "kill" command or
814 "monitor exit"). In such a case, the valgrind process will
815 call exit. But a ptraced process will be blocked in exit,
816 waiting for the ptracing process to detach or die. vgdb
817 cannot detach unconditionally as otherwise, in the normal
818 case, the valgrind process would stop abnormally with SIGSTOP
819 (as vgdb would not be there to catch it). vgdb can also not
820 die unconditionally otherwise again, similar problem. So, we
821 assume that most of the time, we arrive here in the normal
822 case, and so, the breakpoint has been encountered by the
823 valgrind process, so the invoker thread will exit and the
824 join will succeed. For the "kill" case, we cause an alarm
825 signal to be sent after a few seconds. This means that in the
826 normal case, the gdbserver code in valgrind process must have
827 returned the control in less than the alarm nr of seconds,
828 otherwise, valgrind will stop abnormally with SIGSTOP. */
829 (void) alarm(3);
831 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
832 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
833 if (join != 0)
834 XERROR
835 (join,
836 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
838 #if !defined(VGO_freebsd)
839 if (close(from_pid) != 0)
840 ERROR(errno, "close from_pid\n");
841 #endif
844 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
845 error is encountered. */
846 static
847 void gdb_relay(int pid)
849 int from_pid = -1; /* fd to read from pid */
850 int to_pid = -1; /* fd to write to pid */
852 int shutdown_loop = 0;
853 TSFPRINTF(stderr, "relaying data between gdb and process %d\n", pid);
855 if (max_invoke_ms > 0)
856 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
857 invoke_gdbserver_in_valgrind, (void *) &pid);
858 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
859 acquire_lock(shared_mem_fd, pid);
861 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
862 "read mode from pid");
864 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
866 while (1) {
867 ConnectionKind ck;
868 int ret;
869 struct pollfd pollfds[NumConnectionKind];
871 /* watch data written by gdb, watch POLLERR on both gdb fd */
872 pollfds[FROM_GDB].fd = from_gdb;
873 pollfds[FROM_GDB].events = POLLIN;
874 pollfds[FROM_GDB].revents = 0;
875 pollfds[TO_GDB].fd = to_gdb;
876 pollfds[TO_GDB].events = 0;
877 pollfds[TO_GDB].revents = 0;
879 /* watch data written by pid, watch POLLERR on both pid fd */
880 pollfds[FROM_PID].fd = from_pid;
881 pollfds[FROM_PID].events = POLLIN;
882 pollfds[FROM_PID].revents = 0;
883 pollfds[TO_PID].fd = to_pid;
884 pollfds[TO_PID].events = 0;
885 pollfds[TO_PID].revents = 0;
887 ret = poll(pollfds,
888 NumConnectionKind,
889 (shutting_down ?
890 1 /* one second */
891 : -1 /* infinite */));
892 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
894 /* check for unexpected error */
895 if (ret <= 0 && errno != EINTR) {
896 ERROR(errno, "unexpected poll ret %d\n", ret);
897 shutting_down = True;
898 break;
901 /* check for data to read */
902 for (ck = 0; ck < NumConnectionKind; ck ++) {
903 if (pollfds[ck].revents & POLLIN) {
904 switch (ck) {
905 case FROM_GDB:
906 if (!read_from_gdb_write_to_pid(to_pid))
907 shutting_down = True;
908 break;
909 case FROM_PID:
910 if (!read_from_pid_write_to_gdb(from_pid))
911 shutting_down = True;
912 break;
913 default: XERROR(0, "unexpected POLLIN on %s\n",
914 ppConnectionKind(ck));
919 /* check for an fd being in error condition */
920 for (ck = 0; ck < NumConnectionKind; ck ++) {
921 if (pollfds[ck].revents & POLLERR) {
922 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
923 ppConnectionKind(ck), pollfds[ck].fd);
924 invoker_valgrind_dying();
925 shutting_down = True;
927 if (pollfds[ck].revents & POLLHUP) {
928 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
929 ppConnectionKind(ck), pollfds[ck].fd);
930 invoker_valgrind_dying();
931 shutting_down = True;
933 if (pollfds[ck].revents & POLLNVAL) {
934 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
935 ppConnectionKind(ck), pollfds[ck].fd);
936 invoker_valgrind_dying();
937 shutting_down = True;
941 if (shutting_down) {
942 /* we let some time to the final packets to be transferred */
943 shutdown_loop++;
944 if (shutdown_loop > 3)
945 break;
948 close_connection(to_pid, from_pid);
951 static int packet_len_for_command(char *cmd)
953 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
954 return 7+ 2*strlen(cmd) +3 + 1;
957 /* hyper-minimal protocol implementation that
958 sends the provided commands (using qRcmd packets)
959 and read and display their replies. */
960 static
961 void standalone_send_commands(int pid,
962 int last_command,
963 char *commands[] )
965 int from_pid = -1; /* fd to read from pid */
966 int to_pid = -1; /* fd to write to pid */
968 int i;
969 int hi;
970 char hex[3];
971 unsigned char cksum;
972 char *hexcommand;
973 char buf[PBUFSIZ+1]; // +1 for trailing \0
974 int buflen;
975 int nc;
978 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
979 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
980 invoke_gdbserver_in_valgrind, (void *) &pid);
982 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
983 acquire_lock(shared_mem_fd, pid);
985 /* first send a C-c \003 to pid, so that it wakes up the process
986 After that, we can open the fifo from the pid in read mode
987 We then start to wait for packets (normally first a resume reply)
988 At that point, we send our command and expect replies */
989 buf[0] = '\003';
990 i = 0;
991 while (!write_buf(to_pid, buf, 1,
992 "write \\003 to wake up", /* notify */ True)) {
993 /* If write fails, retries up to 10 times every 0.5 seconds
994 This aims at solving the race condition described in
995 remote-utils.c remote_finish function. */
996 usleep(500*1000);
997 i++;
998 if (i >= 10)
999 XERROR(errno, "failed to send wake up char after 10 trials\n");
1001 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1002 "read cmd result from pid");
1004 /* Enable no ack mode. */
1005 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1006 /* notify */ True);
1007 buflen = getpkt(buf, from_pid, to_pid);
1008 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1009 if (buflen != 2)
1010 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen);
1011 else
1012 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1015 for (nc = 0; nc <= last_command; nc++) {
1016 TSFPRINTF(stderr, "sending command %s to pid %d\n", commands[nc], pid);
1018 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1019 hexcommand = vmalloc(packet_len_for_command(commands[nc]));
1020 hexcommand[0] = 0;
1021 strcat(hexcommand, "$qRcmd,");
1022 for (i = 0; i < strlen(commands[nc]); i++) {
1023 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
1024 // Need to use unsigned char, to avoid sign extension.
1025 strcat(hexcommand, hex);
1027 /* checksum (but without the $) */
1028 cksum = 0;
1029 for (hi = 1; hi < strlen(hexcommand); hi++)
1030 cksum+=hexcommand[hi];
1031 strcat(hexcommand, "#");
1032 sprintf(hex, "%02x", cksum);
1033 strcat(hexcommand, hex);
1034 write_buf(to_pid, hexcommand, strlen(hexcommand),
1035 "writing hex command to pid", /* notify */ True);
1037 /* we exit of the below loop explicitly when the command has
1038 been handled or because a signal handler will set
1039 shutting_down. */
1040 while (!shutting_down) {
1041 buflen = getpkt(buf, from_pid, to_pid);
1042 if (buflen < 0) {
1043 ERROR(0, "error reading packet\n");
1044 if (buflen == -2)
1045 invoker_valgrind_dying();
1046 break;
1048 if (strlen(buf) == 0) {
1049 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1050 break;
1052 if (strcmp(buf, "OK") == 0) {
1053 DEBUG(1, "OK packet rcvd\n");
1054 break;
1056 if (buf[0] == 'E') {
1057 DEBUG(0,
1058 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1059 buf);
1060 break;
1062 if (buf[0] == 'W') {
1063 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1064 break;
1066 if (buf[0] == 'T') {
1067 DEBUG(1, "T resume reply packet received: %s\n", buf);
1068 continue;
1071 /* must be here an O packet with hex encoded string reply
1072 => decode and print it */
1073 if (buf[0] != 'O') {
1074 DEBUG(0, "expecting O packet, received: %s\n", buf);
1075 continue;
1078 char buf_print[buflen/2 + 1];
1079 for (i = 1; i < buflen; i = i + 2)
1080 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1081 + fromhex(*(buf+i+1));
1082 buf_print[buflen/2] = 0;
1083 printf("%s", buf_print);
1084 fflush(stdout);
1087 free(hexcommand);
1089 shutting_down = True;
1091 close_connection(to_pid, from_pid);
1094 /* report to user the existence of a vgdb-able valgrind process
1095 with given pid.
1096 Note: this function does not use XERROR if an error is encountered
1097 while producing the command line for pid, as this is not critical
1098 and at least on MacOS, reading cmdline is not available. */
1099 static
1100 void report_pid(int pid, Bool on_stdout)
1102 char cmdline_file[50]; // large enough
1103 int fd, i;
1104 FILE *out = on_stdout ? stdout : stderr;
1106 TSFPRINTF(out, "use --pid=%d for ", pid);
1108 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1109 fd = open(cmdline_file, O_RDONLY);
1110 if (fd == -1) {
1111 DEBUG(1, "error opening cmdline file %s %s\n",
1112 cmdline_file, strerror(errno));
1113 fprintf(out, "(could not open process command line)\n");
1114 } else {
1115 char cmdline[100];
1116 ssize_t sz;
1117 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) > 0) {
1118 for (i = 0; i < sz; i++)
1119 if (cmdline[i] == 0)
1120 cmdline[i] = ' ';
1121 cmdline[sz] = 0;
1122 fprintf(out, "%s", cmdline);
1124 if (sz == -1) {
1125 DEBUG(1, "error reading cmdline file %s %s\n",
1126 cmdline_file, strerror(errno));
1127 fprintf(out, "(error reading process command line)");
1129 fprintf(out, "\n");
1130 close(fd);
1132 fflush(out);
1135 static
1136 void usage(void)
1138 fprintf(stderr,
1139 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1140 "vgdb (valgrind gdb) has two usages\n"
1141 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1142 " The OPTION(s) must be followed by the command to send\n"
1143 " To send more than one command, separate the commands with -c\n"
1144 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1145 " Only OPTION(s) can be given.\n"
1146 "\n"
1147 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1148 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1149 " [--port=<portnr>\n"
1150 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1151 " \n"
1152 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1153 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1154 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1155 " between the Valgrind gdbserver and vgdb.\n"
1156 " --wait (default 0) tells vgdb to check during the specified number\n"
1157 " of seconds if a Valgrind gdbserver can be found.\n"
1158 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1159 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1160 " process is blocked in a system call).\n"
1161 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1162 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1163 " gdbserver has not processed a command after number seconds\n"
1164 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1165 " -T arg tells to add timestamps to vgdb information messages.\n"
1166 " -D arg tells to show shared mem status and then exit.\n"
1167 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1168 "\n"
1169 " -h --help shows this message\n"
1170 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
1171 " To get help from the Valgrind gdbserver, use vgdb help\n"
1172 "\n", vgdb_prefix_default(), VG_LIBDIR "/valgrind-monitor.py"
1174 invoker_restrictions_msg();
1177 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1178 and then exits.
1180 else if arg_pid == -1, waits maximum check_trials seconds to discover
1181 a valgrind pid appearing.
1183 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1184 with gdbserver activated.
1186 Returns the pid to work with
1187 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1189 static
1190 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1192 int i;
1193 int pid = -1;
1195 if (arg_pid == 0 || arg_pid < -1) {
1196 TSFPRINTF(stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1197 exit(1);
1198 } else {
1199 /* search for a matching named fifo.
1200 If we have been given a pid, we will check that the matching FIFO is
1201 there (or wait the nr of check_trials for this to appear).
1202 If no pid has been given, then if we find only one FIFO,
1203 we will use this to build the pid to use.
1204 If we find multiple processes with valid FIFO, we report them and will
1205 exit with an error. */
1206 DIR *vgdb_dir;
1207 char *vgdb_dir_name = vmalloc(strlen (vgdb_prefix) + 3);
1208 struct dirent *f;
1209 int is;
1210 int nr_valid_pid = 0;
1211 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1212 char *vgdb_format = vmalloc(strlen(vgdb_prefix) + strlen(suffix) + 1);
1214 strcpy(vgdb_format, vgdb_prefix);
1215 strcat(vgdb_format, suffix);
1217 if (strchr(vgdb_prefix, '/') != NULL) {
1218 strcpy(vgdb_dir_name, vgdb_prefix);
1219 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1220 if (vgdb_dir_name[is] == '/') {
1221 vgdb_dir_name[is+1] = '\0';
1222 break;
1224 } else {
1225 strcpy(vgdb_dir_name, "");
1228 DEBUG(1, "searching pid in directory %s format %s\n",
1229 vgdb_dir_name, vgdb_format);
1231 /* try to find FIFOs with valid pid.
1232 On exit of the loop, pid is set to:
1233 the last pid found if show_list (or -1 if no process was listed)
1234 -1 if no FIFOs matching a running process is found
1235 -2 if multiple FIFOs of running processes are found
1236 otherwise it is set to the (only) pid found that can be debugged
1238 for (i = 0; i < check_trials; i++) {
1239 DEBUG(1, "check_trial %d \n", i);
1240 if (i > 0)
1241 /* wait one second before checking again */
1242 sleep(1);
1244 vgdb_dir = opendir(strlen(vgdb_dir_name) ? vgdb_dir_name : "./");
1245 if (vgdb_dir == NULL)
1246 XERROR(errno,
1247 "vgdb error: opening directory %s searching vgdb fifo\n",
1248 vgdb_dir_name);
1250 errno = 0; /* avoid complain if vgdb_dir is empty */
1251 while ((f = readdir(vgdb_dir))) {
1252 struct stat st;
1253 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
1254 char *wrongpid;
1255 int newpid;
1257 strcpy(pathname, vgdb_dir_name);
1258 strcat(pathname, f->d_name);
1259 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
1260 if (stat(pathname, &st) != 0) {
1261 if (debuglevel >= 3)
1262 ERROR(errno, "vgdb error: stat %s searching vgdb fifo\n",
1263 pathname);
1264 } else if (S_ISFIFO(st.st_mode)) {
1265 DEBUG(3, "trying FIFO %s\n", pathname);
1266 if (strncmp(pathname, vgdb_format,
1267 strlen(vgdb_format)) == 0) {
1268 newpid = strtol(pathname + strlen(vgdb_format),
1269 &wrongpid, 10);
1270 if (*wrongpid == '-' && newpid > 0
1271 && kill(newpid, 0) == 0) {
1272 nr_valid_pid++;
1273 if (show_list) {
1274 report_pid(newpid, /*on_stdout*/ True);
1275 pid = newpid;
1276 } else if (arg_pid != -1) {
1277 if (arg_pid == newpid) {
1278 pid = newpid;
1280 } else if (nr_valid_pid > 1) {
1281 if (nr_valid_pid == 2) {
1282 TSFPRINTF
1283 (stderr,
1284 "no --pid= arg given"
1285 " and multiple valgrind pids found:\n");
1286 report_pid(pid, /*on_stdout*/ False);
1288 pid = -2;
1289 report_pid(newpid, /*on_stdout*/ False);
1290 } else {
1291 pid = newpid;
1296 errno = 0; /* avoid complain if at the end of vgdb_dir */
1298 if (f == NULL && errno != 0)
1299 XERROR(errno, "vgdb error: reading directory %s for vgdb fifo\n",
1300 vgdb_dir_name);
1302 closedir(vgdb_dir);
1303 if (pid != -1)
1304 break;
1307 free(vgdb_dir_name);
1308 free(vgdb_format);
1311 if (show_list) {
1312 exit(1);
1313 } else if (pid == -1) {
1314 if (arg_pid == -1)
1315 TSFPRINTF(stderr, "vgdb error: no FIFO found and no pid given\n");
1316 else
1317 TSFPRINTF(stderr, "vgdb error: no FIFO found matching pid %d\n",
1318 arg_pid);
1319 exit(1);
1321 else if (pid == -2) {
1322 /* no arg_pid given, multiple FIFOs found */
1323 exit(1);
1325 else {
1326 return pid;
1330 /* return true if the numeric value of an option of the
1331 form --xxxxxxxxx=<number> could properly be extracted
1332 from arg. If True is returned, *value contains the
1333 extracted value.*/
1334 static
1335 Bool numeric_val(char* arg, int *value)
1337 const char *eq_pos = strchr(arg, '=');
1338 char *wrong;
1339 long long int long_value;
1341 if (eq_pos == NULL)
1342 return False;
1344 long_value = strtoll(eq_pos+1, &wrong, 10);
1345 if (long_value < 0 || long_value > INT_MAX)
1346 return False;
1347 if (*wrong)
1348 return False;
1350 *value = (int) long_value;
1351 return True;
1354 /* true if arg matches the provided option */
1355 static
1356 Bool is_opt(char* arg, const char *option)
1358 int option_len = strlen(option);
1359 if (option[option_len-1] == '=')
1360 return (0 == strncmp(option, arg, option_len));
1361 else
1362 return (0 == strcmp(option, arg));
1365 /* Parse command lines options. If error(s), exits.
1366 Otherwise returns the options in *p_... args.
1367 commands must be big enough for the commands extracted from argv.
1368 On return, *p_last_command gives the position in commands where
1369 the last command has been allocated (using vmalloc). */
1370 static
1371 void parse_options(int argc, char** argv,
1372 Bool *p_show_shared_mem,
1373 Bool *p_show_list,
1374 int *p_arg_pid,
1375 int *p_check_trials,
1376 int *p_port,
1377 int *p_last_command,
1378 char *commands[])
1380 Bool show_shared_mem = False;
1381 Bool show_list = False;
1382 int arg_pid = -1;
1383 int check_trials = 1;
1384 int last_command = -1;
1385 int int_port = 0;
1387 int i;
1388 int arg_errors = 0;
1390 for (i = 1; i < argc; i++) {
1391 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
1392 usage();
1393 exit(0);
1394 } else if (is_opt(argv[i], "-d")) {
1395 debuglevel++;
1396 } else if (is_opt(argv[i], "-D")) {
1397 show_shared_mem = True;
1398 } else if (is_opt(argv[i], "-l")) {
1399 show_list = True;
1400 } else if (is_opt(argv[i], "-T")) {
1401 timestamp = True;
1402 } else if (is_opt(argv[i], "--pid=")) {
1403 int newpid;
1404 if (!numeric_val(argv[i], &newpid)) {
1405 TSFPRINTF(stderr, "invalid --pid argument %s\n", argv[i]);
1406 arg_errors++;
1407 } else if (arg_pid != -1) {
1408 TSFPRINTF(stderr, "multiple --pid arguments given\n");
1409 arg_errors++;
1410 } else {
1411 arg_pid = newpid;
1413 } else if (is_opt(argv[i], "--wait=")) {
1414 if (!numeric_val(argv[i], &check_trials)) {
1415 TSFPRINTF(stderr, "invalid --wait argument %s\n", argv[i]);
1416 arg_errors++;
1418 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
1419 if (!numeric_val(argv[i], &max_invoke_ms)) {
1420 TSFPRINTF(stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
1421 arg_errors++;
1423 } else if (is_opt(argv[i], "--cmd-time-out=")) {
1424 if (!numeric_val(argv[i], &cmd_time_out)) {
1425 TSFPRINTF(stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
1426 arg_errors++;
1428 } else if (is_opt(argv[i], "--port=")) {
1429 if (!numeric_val(argv[i], &int_port)) {
1430 TSFPRINTF(stderr, "invalid --port argument %s\n", argv[i]);
1431 arg_errors++;
1433 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
1434 vgdb_prefix = argv[i] + 14;
1435 } else if (is_opt(argv[i], "-c")) {
1436 last_command++;
1437 commands[last_command] = vmalloc(1);
1438 commands[last_command][0] = '\0';
1439 } else if (0 == strncmp(argv[i], "-", 1)) {
1440 TSFPRINTF(stderr, "unknown or invalid argument %s\n", argv[i]);
1441 arg_errors++;
1442 } else {
1443 int len;
1444 if (last_command == -1) {
1445 /* only one command, no -c command indicator */
1446 last_command++;
1447 commands[last_command] = vmalloc(1);
1448 commands[last_command][0] = '\0';
1450 len = strlen(commands[last_command]);
1451 commands[last_command] = vrealloc(commands[last_command],
1452 len + 1 + strlen(argv[i]) + 1);
1453 if (len > 0)
1454 strcat(commands[last_command], " ");
1455 strcat(commands[last_command], argv[i]);
1456 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
1457 TSFPRINTF(stderr, "command %s too long\n", commands[last_command]);
1458 arg_errors++;
1464 if (vgdb_prefix == NULL)
1465 vgdb_prefix = vgdb_prefix_default();
1467 if (isatty(0)
1468 && !show_shared_mem
1469 && !show_list
1470 && int_port == 0
1471 && last_command == -1) {
1472 arg_errors++;
1473 TSFPRINTF(stderr,
1474 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1477 if (show_shared_mem && show_list) {
1478 arg_errors++;
1479 TSFPRINTF(stderr,
1480 "Can't use both -D and -l options\n");
1483 if (max_invoke_ms > 0
1484 && cmd_time_out != NEVER
1485 && (cmd_time_out * 1000) <= max_invoke_ms) {
1486 arg_errors++;
1487 TSFPRINTF(stderr,
1488 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1491 if (show_list && arg_pid != -1) {
1492 arg_errors++;
1493 TSFPRINTF(stderr,
1494 "Can't use both --pid and -l options\n");
1497 if (int_port > 0 && last_command != -1) {
1498 arg_errors++;
1499 TSFPRINTF(stderr,
1500 "Can't use --port to send commands\n");
1503 if (arg_errors > 0) {
1504 TSFPRINTF(stderr, "args error. Try `vgdb --help` for more information\n");
1505 exit(1);
1508 *p_show_shared_mem = show_shared_mem;
1509 *p_show_list = show_list;
1510 *p_arg_pid = arg_pid;
1511 *p_check_trials = check_trials;
1512 *p_port = int_port;
1513 *p_last_command = last_command;
1516 int main(int argc, char** argv)
1518 int i;
1519 int pid;
1521 Bool show_shared_mem;
1522 Bool show_list;
1523 int arg_pid;
1524 int check_trials;
1525 int in_port;
1526 int last_command;
1527 char *commands[argc]; // we will never have more commands than args.
1529 parse_options(argc, argv,
1530 &show_shared_mem,
1531 &show_list,
1532 &arg_pid,
1533 &check_trials,
1534 &in_port,
1535 &last_command,
1536 commands);
1538 /* when we are working as a relay for gdb, handle some signals by
1539 only reporting them (according to debug level). Also handle these
1540 when ptrace will be used: vgdb must clean up the ptrace effect before
1541 dying. */
1542 if (max_invoke_ms > 0 || last_command == -1)
1543 install_handlers();
1545 pid = search_arg_pid(arg_pid, check_trials, show_list);
1547 prepare_fifos_and_shared_mem(pid);
1549 if (in_port > 0)
1550 wait_for_gdb_connect(in_port);
1552 if (show_shared_mem) {
1553 TSFPRINTF(stderr,
1554 "vgdb %d "
1555 "written_by_vgdb %d "
1556 "seen_by_valgrind %d\n",
1557 VS_vgdb_pid,
1558 VS_written_by_vgdb,
1559 VS_seen_by_valgrind);
1560 TSFPRINTF(stderr, "vgdb pid %d\n", VS_vgdb_pid);
1561 exit(0);
1564 if (last_command >= 0) {
1565 standalone_send_commands(pid, last_command, commands);
1566 } else {
1567 gdb_relay(pid);
1571 free(from_gdb_to_pid);
1572 free(to_gdb_from_pid);
1573 free(shared_mem);
1575 for (i = 0; i <= last_command; i++)
1576 free(commands[i]);
1577 return 0;