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