tests/vg_regtest: Always evaluate prerequisite expressions with sh
[valgrind.git] / coregrind / vgdb.c
bloba85f26b96310ba4e5053c59474219221ff79db9c
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-2013 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, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
24 02111-1307, USA.
26 The GNU General Public License is contained in the file COPYING.
29 #include "vgdb.h"
31 #include "config.h"
33 #include <assert.h>
34 #include <dirent.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <limits.h>
38 #include <poll.h>
39 #include <pthread.h>
40 #include <signal.h>
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <netinet/in.h>
46 #include <sys/mman.h>
47 #include <sys/socket.h>
48 #include <sys/stat.h>
49 #include <sys/time.h>
51 /* vgdb has two usages:
52 1. relay application between gdb and the gdbserver embedded in valgrind.
53 2. standalone to send monitor commands to a running valgrind-ified process
55 It is made of a main program which reads arguments. If no
56 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
57 assumed.
59 As relay application, vgdb reads bytes from gdb on stdin and
60 writes these bytes to valgrind. Bytes read from valgrind are
61 written to gdb on stdout. Read/Write from/to valgrind is done
62 using FIFOs. There is one thread reading from stdin, writing to
63 valgrind on a FIFO. There is one thread reading from valgrind on a
64 FIFO, writing to gdb on stdout
66 As a standalone utility, vgdb builds command packets to write to valgrind,
67 sends it and reads the reply. The same two threads are used to write/read.
68 Once all the commands are sent and their replies received, vgdb will exit.
71 int debuglevel;
72 struct timeval dbgtv;
73 static char *vgdb_prefix = NULL;
75 /* Will be set to True when any condition indicating we have to shutdown
76 is encountered. */
77 Bool shutting_down = False;
79 VgdbShared32 *shared32;
80 VgdbShared64 *shared64;
81 #define VS_written_by_vgdb (shared32 != NULL ? \
82 shared32->written_by_vgdb \
83 : shared64->written_by_vgdb)
84 #define VS_seen_by_valgrind (shared32 != NULL ? \
85 shared32->seen_by_valgrind \
86 : shared64->seen_by_valgrind)
88 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
90 void *vmalloc(size_t size)
92 void * mem = malloc(size);
93 if (mem == NULL)
94 XERROR (errno, "can't allocate memory\n");
95 return mem;
98 void *vrealloc(void *ptr,size_t size)
100 void * mem = realloc(ptr, size);
101 if (mem == NULL)
102 XERROR (errno, "can't reallocate memory\n");
103 return mem;
106 /* Return the name of a directory for temporary files. */
107 static
108 const char *vgdb_tmpdir(void)
110 const char *tmpdir;
112 tmpdir = getenv("TMPDIR");
113 if (tmpdir == NULL || *tmpdir == '\0')
114 tmpdir = VG_TMPDIR;
115 if (tmpdir == NULL || *tmpdir == '\0')
116 tmpdir = "/tmp"; /* fallback */
118 return tmpdir;
121 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
122 to communicate with valgrind */
123 static
124 char *vgdb_prefix_default(void)
126 static HChar *prefix;
128 if (prefix == NULL) {
129 const char *tmpdir = vgdb_tmpdir();
130 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
131 strcpy(prefix, tmpdir);
132 strcat(prefix, "/vgdb-pipe");
134 return prefix;
137 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
138 static
139 void add_written(int nrw)
141 if (shared32 != NULL)
142 shared32->written_by_vgdb += nrw;
143 else if (shared64 != NULL)
144 shared64->written_by_vgdb += nrw;
145 else
146 assert(0);
149 static int shared_mem_fd = -1;
150 static
151 void map_vgdbshared (char* shared_mem)
153 struct stat fdstat;
154 void **s;
155 shared_mem_fd = open(shared_mem, O_RDWR);
156 /* shared_mem_fd will not be closed till vgdb exits. */
158 if (shared_mem_fd == -1)
159 XERROR (errno, "error opening %s shared memory file\n", shared_mem);
161 if (fstat(shared_mem_fd, &fdstat) != 0)
162 XERROR (errno, "fstat");
164 if (fdstat.st_size == sizeof(VgdbShared64))
165 s = (void*) &shared64;
166 else if (fdstat.st_size == sizeof(VgdbShared32))
167 s = (void*) &shared32;
168 else
169 #if VEX_HOST_WORDSIZE == 8
170 XERROR (0,
171 "error size shared memory file %s.\n"
172 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
173 shared_mem,
174 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
175 (long int)fdstat.st_size);
176 #elif VEX_HOST_WORDSIZE == 4
177 XERROR (0,
178 "error size shared memory file %s.\n"
179 "expecting size %d (32bits) got %ld.\n",
180 shared_mem,
181 (int) sizeof(VgdbShared32),
182 fdstat.st_size);
183 #else
184 # error "unexpected wordsize"
185 #endif
187 #if VEX_HOST_WORDSIZE == 4
188 if (shared64 != NULL)
189 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
190 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
191 #endif
193 *s = (void*) mmap (NULL, fdstat.st_size,
194 PROT_READ|PROT_WRITE, MAP_SHARED,
195 shared_mem_fd, 0);
197 if (*s == (void *) -1)
198 XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
202 /* This function loops till shutting_down becomes true. In this loop,
203 it verifies if valgrind process is reading the characters written
204 by vgdb. The verification is done every max_invoke_ms ms. If
205 valgrind is not reading characters, it will use invoker_invoke_gdbserver
206 to ensure that the gdbserver code is called soon by valgrind. */
207 static int max_invoke_ms = 100;
208 #define NEVER 99999999
209 static int cmd_time_out = NEVER;
210 static
211 void *invoke_gdbserver_in_valgrind(void *v_pid)
213 struct timeval cmd_max_end_time;
214 Bool cmd_started = False;
215 struct timeval invoke_time;
217 int pid = *(int *)v_pid;
218 int written_by_vgdb_before_sleep;
219 int seen_by_valgrind_before_sleep;
221 int invoked_written = -1;
222 unsigned int usecs;
224 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
226 while (!shutting_down) {
227 written_by_vgdb_before_sleep = VS_written_by_vgdb;
228 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
229 DEBUG(3,
230 "written_by_vgdb_before_sleep %d "
231 "seen_by_valgrind_before_sleep %d\n",
232 written_by_vgdb_before_sleep,
233 seen_by_valgrind_before_sleep);
234 if (cmd_time_out != NEVER
235 && !cmd_started
236 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
237 /* A command was started. Record the time at which it was started. */
238 DEBUG(1, "IO for command started\n");
239 gettimeofday(&cmd_max_end_time, NULL);
240 cmd_max_end_time.tv_sec += cmd_time_out;
241 cmd_started = True;
243 if (max_invoke_ms > 0) {
244 usecs = 1000 * max_invoke_ms;
245 gettimeofday(&invoke_time, NULL);
246 invoke_time.tv_sec += max_invoke_ms / 1000;
247 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
248 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
249 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
250 } else {
251 usecs = 0;
253 if (cmd_started) {
254 // 0 usecs here means the thread just has to check gdbserver eats
255 // the characters in <= cmd_time_out seconds.
256 // We will just wait by 1 second max at a time.
257 if (usecs == 0 || usecs > 1000 * 1000)
258 usecs = 1000 * 1000;
260 usleep(usecs);
262 /* If nothing happened during our sleep, let's try to wake up valgrind
263 or check for cmd time out. */
264 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
265 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
266 && VS_written_by_vgdb > VS_seen_by_valgrind) {
267 struct timeval now;
268 gettimeofday(&now, NULL);
269 DEBUG(2,
270 "after sleep "
271 "written_by_vgdb %d "
272 "seen_by_valgrind %d "
273 "invoked_written %d\n",
274 VS_written_by_vgdb,
275 VS_seen_by_valgrind,
276 invoked_written);
277 /* if the pid does not exist anymore, we better stop */
278 if (kill(pid, 0) != 0)
279 XERROR (errno,
280 "invoke_gdbserver_in_valgrind: "
281 "check for pid %d existence failed\n", pid);
282 if (cmd_started) {
283 if (timercmp (&now, &cmd_max_end_time, >))
284 XERROR (0,
285 "pid %d did not handle a command in %d seconds\n",
286 pid, cmd_time_out);
288 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
289 /* only need to wake up if the nr written has changed since
290 last invoke. */
291 if (invoked_written != written_by_vgdb_before_sleep) {
292 if (invoker_invoke_gdbserver(pid)) {
293 /* If invoke successful, no need to invoke again
294 for the same value of written_by_vgdb_before_sleep. */
295 invoked_written = written_by_vgdb_before_sleep;
299 } else {
300 // Something happened => restart timer check.
301 if (cmd_time_out != NEVER) {
302 DEBUG(2, "some IO was done => restart command\n");
303 cmd_started = False;
307 pthread_cleanup_pop(0);
308 return NULL;
311 static
312 int open_fifo (const char* name, int flags, const char* desc)
314 int fd;
315 DEBUG(1, "opening %s %s\n", name, desc);
316 fd = open(name, flags);
317 if (fd == -1)
318 XERROR (errno, "error opening %s %s\n", name, desc);
320 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
321 return fd;
324 /* acquire a lock on the first byte of the given fd. If not successful,
325 exits with error.
326 This allows to avoid having two vgdb speaking with the same Valgrind
327 gdbserver as this causes serious headaches to the protocol. */
328 static
329 void acquire_lock (int fd, int valgrind_pid)
331 struct flock fl;
332 fl.l_type = F_WRLCK;
333 fl.l_whence = SEEK_SET;
334 fl.l_start = 0;
335 fl.l_len = 1;
336 if (fcntl(fd, F_SETLK, &fl) < 0) {
337 if (errno == EAGAIN || errno == EACCES) {
338 XERROR(errno,
339 "Cannot acquire lock.\n"
340 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
341 VS_vgdb_pid,
342 valgrind_pid);
343 } else {
344 XERROR(errno, "cannot acquire lock.\n");
348 /* Here, we have the lock. It will be released when fd will be closed. */
349 /* We indicate our pid to Valgrind gdbserver */
350 if (shared32 != NULL)
351 shared32->vgdb_pid = getpid();
352 else if (shared64 != NULL)
353 shared64->vgdb_pid = getpid();
354 else
355 assert(0);
358 #define PBUFSIZ 16384 /* keep in sync with server.h */
360 /* read some characters from fd.
361 Returns the nr of characters read, -1 if error.
362 desc is a string used in tracing */
363 static
364 int read_buf (int fd, char* buf, const char* desc)
366 int nrread;
367 DEBUG(2, "reading %s\n", desc);
368 nrread = read(fd, buf, PBUFSIZ);
369 if (nrread == -1) {
370 ERROR (errno, "error reading %s\n", desc);
371 return -1;
373 buf[nrread] = '\0';
374 DEBUG(2, "read %s %s\n", desc, buf);
375 return nrread;
378 /* write size bytes from buf to fd.
379 desc is a description of the action for which the write is done.
380 If notify, then add size to the shared cntr indicating to the
381 valgrind process that there is new data.
382 Returns True if write is ok, False if there was a problem. */
383 static
384 Bool write_buf(int fd, char* buf, int size, const char* desc, Bool notify)
386 int nrwritten;
387 int nrw;
388 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
389 size, buf, notify);
390 nrwritten = 0;
391 while (nrwritten < size) {
392 nrw = write (fd, buf+nrwritten, size - nrwritten);
393 if (nrw == -1) {
394 ERROR(errno, "error write %s\n", desc);
395 return False;
397 nrwritten = nrwritten + nrw;
398 if (notify)
399 add_written(nrw);
401 return True;
404 typedef enum {
405 FROM_GDB,
406 TO_GDB,
407 FROM_PID,
408 TO_PID } ConnectionKind;
409 static const int NumConnectionKind = TO_PID+1;
410 static
411 const char *ppConnectionKind (ConnectionKind con)
413 switch (con) {
414 case FROM_GDB: return "FROM_GDB";
415 case TO_GDB: return "TO_GDB";
416 case FROM_PID: return "FROM_PID";
417 case TO_PID: return "TO_PID";
418 default: return "invalid connection kind";
422 static char *shared_mem;
424 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
425 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
426 /* Returns True in case read/write operations were done properly.
427 Returns False in case of error.
428 to_pid is the file descriptor to write to the process pid. */
429 static
430 Bool read_from_gdb_write_to_pid(int to_pid)
432 char buf[PBUFSIZ+1]; // +1 for trailing \0
433 int nrread;
435 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
436 if (nrread <= 0) {
437 if (nrread == 0)
438 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
439 else
440 DEBUG(1, "error reading bytes from gdb\n");
441 close (from_gdb);
442 shutting_down = True;
443 return False;
445 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
448 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
449 static char *to_gdb_from_pid; /* fifo name to read pid replies */
450 /* Returns True in case read/write operations were done properly.
451 Returns False in case of error.
452 from_pid is the file descriptor to read data from the process pid. */
453 static
454 Bool read_from_pid_write_to_gdb(int from_pid)
456 char buf[PBUFSIZ+1]; // +1 for trailing \0
457 int nrread;
459 nrread = read_buf(from_pid, buf, "from pid");
460 if (nrread <= 0) {
461 if (nrread == 0)
462 DEBUG(1, "read 0 bytes from pid => assume exit\n");
463 else
464 DEBUG(1, "error reading bytes from pid\n");
465 close (from_pid);
466 shutting_down = True;
467 return False;
469 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
472 static
473 void wait_for_gdb_connect (int in_port)
475 struct sockaddr_in addr;
477 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
478 int gdb_connect;
480 if (-1 == listen_gdb) {
481 XERROR(errno, "cannot create socket");
484 memset(&addr, 0, sizeof(addr));
486 addr.sin_family = AF_INET;
487 addr.sin_port = htons((unsigned short int)in_port);
488 addr.sin_addr.s_addr = INADDR_ANY;
490 if (-1 == bind(listen_gdb,(struct sockaddr *)&addr, sizeof(addr))) {
491 XERROR(errno, "bind failed");
493 fprintf(stderr, "listening on port %d ...", in_port);
494 fflush(stderr);
495 if (-1 == listen(listen_gdb, 1)) {
496 XERROR(errno, "error listen failed");
499 gdb_connect = accept(listen_gdb, NULL, NULL);
500 if (gdb_connect < 0) {
501 XERROR(errno, "accept failed");
503 fprintf(stderr, "connected.\n");
504 fflush(stderr);
505 close(listen_gdb);
506 from_gdb = gdb_connect;
507 to_gdb = gdb_connect;
510 /* prepares the FIFOs filenames, map the shared memory. */
511 static
512 void prepare_fifos_and_shared_mem(int pid)
514 const HChar *user, *host;
515 unsigned len;
517 user = getenv("LOGNAME");
518 if (user == NULL) user = getenv("USER");
519 if (user == NULL) user = "???";
520 if (strchr(user, '/')) user = "???";
522 host = getenv("HOST");
523 if (host == NULL) host = getenv("HOSTNAME");
524 if (host == NULL) host = "???";
525 if (strchr(host, '/')) host = "???";
527 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
528 from_gdb_to_pid = vmalloc (len);
529 to_gdb_from_pid = vmalloc (len);
530 shared_mem = vmalloc (len);
531 /* below 3 lines must match the equivalent in remote-utils.c */
532 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
533 pid, user, host);
534 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
535 pid, user, host);
536 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
537 pid, user, host);
538 DEBUG (1, "vgdb: using %s %s %s\n",
539 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
541 map_vgdbshared(shared_mem);
544 /* Convert hex digit A to a number. */
546 static int
547 fromhex (int a)
549 if (a >= '0' && a <= '9')
550 return a - '0';
551 else if (a >= 'a' && a <= 'f')
552 return a - 'a' + 10;
553 else
554 XERROR(0, "Reply contains invalid hex digit %c\n", a);
555 return 0;
558 /* Returns next char from fd. -1 if error, -2 if EOF.
559 NB: must always call it with the same fd */
560 static int
561 readchar (int fd)
563 static char buf[PBUFSIZ+1]; // +1 for trailing \0
564 static int bufcnt = 0;
565 static unsigned char *bufp;
566 // unsigned bufp to e.g. avoid having 255 converted to int -1
568 if (bufcnt-- > 0)
569 return *bufp++;
571 bufcnt = read_buf (fd, buf, "static buf readchar");
573 if (bufcnt <= 0) {
574 if (bufcnt == 0) {
575 fprintf (stderr, "readchar: Got EOF\n");
576 return -2;
577 } else {
578 ERROR (errno, "readchar\n");
579 return -1;
583 bufp = (unsigned char *)buf;
584 bufcnt--;
585 return *bufp++;
588 /* Read a packet from fromfd, with error checking,
589 and store it in BUF.
590 Returns length of packet, or -1 if error or -2 if EOF.
591 Writes ack on ackfd */
593 static int
594 getpkt (char *buf, int fromfd, int ackfd)
596 char *bp;
597 unsigned char csum, c1, c2;
598 int c;
600 while (1) {
601 csum = 0;
603 while (1) {
604 c = readchar (fromfd);
605 if (c == '$')
606 break;
607 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
608 if (c < 0)
609 return c;
612 bp = buf;
613 while (1) {
614 c = readchar (fromfd);
615 if (c < 0)
616 return c;
617 if (c == '#')
618 break;
619 if (c == '*') {
620 int repeat;
621 int r;
622 int prev;
623 prev = *(bp-1);
624 csum += c;
625 repeat = readchar (fromfd);
626 csum += repeat;
627 for (r = 0; r < repeat - 29; r ++)
628 *bp++ = prev;
629 } else {
630 *bp++ = c;
631 csum += c;
634 *bp = 0;
636 c1 = fromhex (readchar (fromfd));
637 c2 = fromhex (readchar (fromfd));
639 if (csum == (c1 << 4) + c2)
640 break;
642 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
643 (c1 << 4) + c2, csum, buf);
644 if (write (ackfd, "-", 1) != 1)
645 ERROR(0, "error when writing - (nack)\n");
646 else
647 add_written(1);
650 DEBUG(2, "getpkt (\"%s\"); [sending ack] \n", buf);
651 if (write (ackfd, "+", 1) != 1)
652 ERROR(0, "error when writing + (ack)\n");
653 else
654 add_written(1);
655 return bp - buf;
658 static int sigint = 0;
659 static int sigterm = 0;
660 static int sigpipe = 0;
661 static int sighup = 0;
662 static int sigusr1 = 0;
663 static int sigalrm = 0;
664 static int sigusr1_fd = -1;
665 static pthread_t invoke_gdbserver_in_valgrind_thread;
667 static
668 void received_signal (int signum)
670 if (signum == SIGINT)
671 sigint++;
672 else if (signum == SIGUSR1) {
673 sigusr1++;
674 if (sigusr1_fd >= 0) {
675 char control_c = '\003';
676 write_buf(sigusr1_fd, &control_c, 1,
677 "write \\003 on SIGUSR1", /* notify */ True);
680 else if (signum == SIGTERM) {
681 shutting_down = True;
682 sigterm++;
683 } else if (signum == SIGHUP) {
684 shutting_down = True;
685 sighup++;
686 } else if (signum == SIGPIPE) {
687 sigpipe++;
688 } else if (signum == SIGALRM) {
689 sigalrm++;
690 #if defined(VGPV_arm_linux_android) \
691 || defined(VGPV_x86_linux_android) \
692 || defined(VGPV_mips32_linux_android) \
693 || defined(VGPV_arm64_linux_android)
694 /* Android has no pthread_cancel. As it also does not have
695 an invoker implementation, there is no need for cleanup action.
696 So, we just do nothing. */
697 DEBUG(1, "sigalrm received, no action on android\n");
698 #else
699 /* Note: we cannot directly invoke restore_and_detach : this must
700 be done by the thread that has attached.
701 We have in this thread pushed a cleanup handler that will
702 cleanup what is needed. */
703 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
704 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
705 #endif
706 } else {
707 ERROR(0, "unexpected signal %d\n", signum);
711 /* install the signal handlers allowing e.g. vgdb to cleanup in
712 case of termination. */
713 static
714 void install_handlers(void)
716 struct sigaction action, oldaction;
718 action.sa_handler = received_signal;
719 sigemptyset (&action.sa_mask);
720 action.sa_flags = 0;
722 /* SIGINT: when user types C-c in gdb, this sends
723 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
724 The later is enough to wakeup the valgrind process. */
725 if (sigaction (SIGINT, &action, &oldaction) != 0)
726 XERROR (errno, "vgdb error sigaction SIGINT\n");
727 /* We might do something more intelligent than just
728 reporting this SIGINT E.g. behave similarly to the gdb: two
729 control-C without feedback from the debugged process would
730 mean to stop debugging it. */
732 /* SIGUSR1: this is used to facilitate automatic testing. When
733 vgdb receives this signal, it will simulate the user typing C-c. */
734 if (sigaction (SIGUSR1, &action, &oldaction) != 0)
735 XERROR (errno, "vgdb error sigaction SIGUSR1\n");
738 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
739 when detaching or similar. A clean shutdown will be done as both
740 the read and write side will detect an end of file. */
741 if (sigaction (SIGTERM, &action, &oldaction) != 0)
742 XERROR (errno, "vgdb error sigaction SIGTERM\n");
744 /* SIGPIPE: can receive this signal when gdb detaches or kill the
745 process debugged: gdb will close its pipes to vgdb. vgdb
746 must resist to this signal to allow a clean shutdown. */
747 if (sigaction (SIGPIPE, &action, &oldaction) != 0)
748 XERROR (errno, "vgdb error sigaction SIGPIPE\n");
750 /* SIGALRM: in case invoke thread is blocked, alarm is used
751 to cleanup. */
752 if (sigaction (SIGALRM, &action, &oldaction) != 0)
753 XERROR (errno, "vgdb error sigaction SIGALRM\n");
755 /* unmask all signals, in case the process that launched vgdb
756 masked some. */
757 if (sigprocmask (SIG_SETMASK, &action.sa_mask, NULL) != 0)
758 XERROR (errno, "vgdb error sigprocmask");
761 /* close the FIFOs provided connections, terminate the invoker thread. */
762 static
763 void close_connection(int to_pid, int from_pid)
765 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
766 sigint, sigterm, sighup, sigpipe);
767 /* Note that we do not forward sigterm to the valgrind process:
768 a sigterm signal is (probably) received from gdb if the user wants to
769 kill the debugged process. The kill instruction has been given to
770 the valgrind process, which should execute a clean exit. */
772 /* We first close the connection to pid. The pid will then
773 terminates its gdbserver work. We keep the from pid
774 fifo opened till the invoker thread is finished.
775 This allows the gdbserver to finish sending its last reply. */
776 if (close(to_pid) != 0)
777 ERROR(errno, "close to_pid\n");
779 /* if there is a task that was busy trying to wake up valgrind
780 process, we wait for it to be terminated otherwise threads
781 in the valgrind process can stay stopped if vgdb main
782 exits before the invoke thread had time to detach from
783 all valgrind threads. */
784 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
785 int join;
787 /* It is surprisingly complex to properly shutdown or exit the
788 valgrind process in which gdbserver has been invoked through
789 ptrace. In the normal case (gdb detaches from the process,
790 or process is continued), the valgrind process will reach the
791 breakpoint place. Using ptrace, vgdb will ensure the
792 previous activity of the process is resumed (e.g. restart a
793 blocking system call). The special case is when gdb asks the
794 valgrind process to exit (using either the "kill" command or
795 "monitor exit"). In such a case, the valgrind process will
796 call exit. But a ptraced process will be blocked in exit,
797 waiting for the ptracing process to detach or die. vgdb
798 cannot detach unconditionally as otherwise, in the normal
799 case, the valgrind process would stop abnormally with SIGSTOP
800 (as vgdb would not be there to catch it). vgdb can also not
801 die unconditionally otherwise again, similar problem. So, we
802 assume that most of the time, we arrive here in the normal
803 case, and so, the breakpoint has been encountered by the
804 valgrind process, so the invoker thread will exit and the
805 join will succeed. For the "kill" case, we cause an alarm
806 signal to be sent after a few seconds. This means that in the
807 normal case, the gdbserver code in valgrind process must have
808 returned the control in less than the alarm nr of seconds,
809 otherwise, valgrind will stop abnormally with SIGSTOP. */
810 (void) alarm (3);
812 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
813 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
814 if (join != 0)
815 XERROR
816 (join,
817 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
819 if (close(from_pid) != 0)
820 ERROR(errno, "close from_pid\n");
823 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
824 error is encountered. */
825 static
826 void gdb_relay (int pid)
828 int from_pid = -1; /* fd to read from pid */
829 int to_pid = -1; /* fd to write to pid */
831 int shutdown_loop = 0;
832 fprintf (stderr, "relaying data between gdb and process %d\n", pid);
833 fflush (stderr);
835 if (max_invoke_ms > 0)
836 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
837 invoke_gdbserver_in_valgrind, (void *) &pid);
838 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
839 acquire_lock (shared_mem_fd, pid);
841 from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
842 "read mode from pid");
844 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
846 while (1) {
847 ConnectionKind ck;
848 int ret;
849 struct pollfd pollfds[NumConnectionKind];
851 /* watch data written by gdb, watch POLLERR on both gdb fd */
852 pollfds[FROM_GDB].fd = from_gdb;
853 pollfds[FROM_GDB].events = POLLIN;
854 pollfds[FROM_GDB].revents = 0;
855 pollfds[TO_GDB].fd = to_gdb;
856 pollfds[TO_GDB].events = 0;
857 pollfds[TO_GDB].revents = 0;
859 /* watch data written by pid, watch POLLERR on both pid fd */
860 pollfds[FROM_PID].fd = from_pid;
861 pollfds[FROM_PID].events = POLLIN;
862 pollfds[FROM_PID].revents = 0;
863 pollfds[TO_PID].fd = to_pid;
864 pollfds[TO_PID].events = 0;
865 pollfds[TO_PID].revents = 0;
867 ret = poll(pollfds,
868 NumConnectionKind,
869 (shutting_down ?
870 1 /* one second */
871 : -1 /* infinite */));
872 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
874 /* check for unexpected error */
875 if (ret <= 0 && errno != EINTR) {
876 ERROR (errno, "unexpected poll ret %d\n", ret);
877 shutting_down = True;
878 break;
881 /* check for data to read */
882 for (ck = 0; ck < NumConnectionKind; ck ++) {
883 if (pollfds[ck].revents & POLLIN) {
884 switch (ck) {
885 case FROM_GDB:
886 if (!read_from_gdb_write_to_pid(to_pid))
887 shutting_down = True;
888 break;
889 case FROM_PID:
890 if (!read_from_pid_write_to_gdb(from_pid))
891 shutting_down = True;
892 break;
893 default: XERROR(0, "unexpected POLLIN on %s\n",
894 ppConnectionKind(ck));
899 /* check for an fd being in error condition */
900 for (ck = 0; ck < NumConnectionKind; ck ++) {
901 if (pollfds[ck].revents & POLLERR) {
902 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
903 ppConnectionKind(ck), pollfds[ck].fd);
904 invoker_valgrind_dying();
905 shutting_down = True;
907 if (pollfds[ck].revents & POLLHUP) {
908 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
909 ppConnectionKind(ck), pollfds[ck].fd);
910 invoker_valgrind_dying();
911 shutting_down = True;
913 if (pollfds[ck].revents & POLLNVAL) {
914 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
915 ppConnectionKind(ck), pollfds[ck].fd);
916 invoker_valgrind_dying();
917 shutting_down = True;
921 if (shutting_down) {
922 /* we let some time to the final packets to be transferred */
923 shutdown_loop++;
924 if (shutdown_loop > 3)
925 break;
928 close_connection(to_pid, from_pid);
931 static int packet_len_for_command(char *cmd)
933 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
934 return 7+ 2*strlen(cmd) +3 + 1;
937 /* hyper-minimal protocol implementation that
938 sends the provided commands (using qRcmd packets)
939 and read and display their replies. */
940 static
941 void standalone_send_commands(int pid,
942 int last_command,
943 char *commands[] )
945 int from_pid = -1; /* fd to read from pid */
946 int to_pid = -1; /* fd to write to pid */
948 int i;
949 int hi;
950 char hex[3];
951 unsigned char cksum;
952 char *hexcommand;
953 char buf[PBUFSIZ+1]; // +1 for trailing \0
954 int buflen;
955 int nc;
958 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
959 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
960 invoke_gdbserver_in_valgrind, (void *) &pid);
962 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
963 acquire_lock (shared_mem_fd, pid);
965 /* first send a C-c \003 to pid, so that it wakes up the process
966 After that, we can open the fifo from the pid in read mode
967 We then start to wait for packets (normally first a resume reply)
968 At that point, we send our command and expect replies */
969 buf[0] = '\003';
970 i = 0;
971 while (!write_buf(to_pid, buf, 1,
972 "write \\003 to wake up", /* notify */ True)) {
973 /* If write fails, retries up to 10 times every 0.5 seconds
974 This aims at solving the race condition described in
975 remote-utils.c remote_finish function. */
976 usleep(500*1000);
977 i++;
978 if (i >= 10)
979 XERROR (errno, "failed to send wake up char after 10 trials\n");
981 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
982 "read cmd result from pid");
984 for (nc = 0; nc <= last_command; nc++) {
985 fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
986 fflush (stderr);
988 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
989 hexcommand = vmalloc (packet_len_for_command(commands[nc]));
990 hexcommand[0] = 0;
991 strcat (hexcommand, "$qRcmd,");
992 for (i = 0; i < strlen(commands[nc]); i++) {
993 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
994 // Need to use unsigned char, to avoid sign extension.
995 strcat (hexcommand, hex);
997 /* checksum (but without the $) */
998 cksum = 0;
999 for (hi = 1; hi < strlen(hexcommand); hi++)
1000 cksum+=hexcommand[hi];
1001 strcat(hexcommand, "#");
1002 sprintf(hex, "%02x", cksum);
1003 strcat(hexcommand, hex);
1004 write_buf(to_pid, hexcommand, strlen(hexcommand),
1005 "writing hex command to pid", /* notify */ True);
1007 /* we exit of the below loop explicitely when the command has
1008 been handled or because a signal handler will set
1009 shutting_down. */
1010 while (!shutting_down) {
1011 buflen = getpkt(buf, from_pid, to_pid);
1012 if (buflen < 0) {
1013 ERROR (0, "error reading packet\n");
1014 if (buflen == -2)
1015 invoker_valgrind_dying();
1016 break;
1018 if (strlen(buf) == 0) {
1019 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1020 break;
1022 if (strcmp(buf, "OK") == 0) {
1023 DEBUG(1, "OK packet rcvd\n");
1024 break;
1026 if (buf[0] == 'E') {
1027 DEBUG(0,
1028 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1029 buf);
1030 break;
1032 if (buf[0] == 'W') {
1033 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1034 break;
1036 if (buf[0] == 'T') {
1037 DEBUG(1, "T resume reply packet received: %s\n", buf);
1038 continue;
1041 /* must be here an O packet with hex encoded string reply
1042 => decode and print it */
1043 if (buf[0] != 'O') {
1044 DEBUG(0, "expecting O packet, received: %s\n", buf);
1045 continue;
1048 char buf_print[buflen/2 + 1];
1049 for (i = 1; i < buflen; i = i + 2)
1050 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1051 + fromhex(*(buf+i+1));
1052 buf_print[buflen/2] = 0;
1053 printf("%s", buf_print);
1054 fflush(stdout);
1057 free (hexcommand);
1059 shutting_down = True;
1061 close_connection(to_pid, from_pid);
1064 /* report to user the existence of a vgdb-able valgrind process
1065 with given pid.
1066 Note: this function does not use XERROR if an error is encountered
1067 while producing the command line for pid, as this is not critical
1068 and at least on MacOS, reading cmdline is not available. */
1069 static
1070 void report_pid (int pid, Bool on_stdout)
1072 char cmdline_file[50]; // large enough
1073 int fd, i;
1074 FILE *out = on_stdout ? stdout : stderr;
1076 fprintf(out, "use --pid=%d for ", pid);
1078 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1079 fd = open (cmdline_file, O_RDONLY);
1080 if (fd == -1) {
1081 DEBUG(1, "error opening cmdline file %s %s\n",
1082 cmdline_file, strerror(errno));
1083 fprintf(out, "(could not open process command line)\n");
1084 } else {
1085 char cmdline[100];
1086 ssize_t sz;
1087 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) != 0) {
1088 for (i = 0; i < sz; i++)
1089 if (cmdline[i] == 0)
1090 cmdline[i] = ' ';
1091 cmdline[sz] = 0;
1092 fprintf(out, "%s", cmdline);
1094 if (sz == -1) {
1095 DEBUG(1, "error reading cmdline file %s %s\n",
1096 cmdline_file, strerror(errno));
1097 fprintf(out, "(error reading process command line)");
1099 fprintf(out, "\n");
1100 close (fd);
1102 fflush(out);
1105 static
1106 void usage(void)
1108 fprintf(stderr,
1109 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1110 "vgdb (valgrind gdb) has two usages\n"
1111 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1112 " The OPTION(s) must be followed by the command to send\n"
1113 " To send more than one command, separate the commands with -c\n"
1114 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1115 " Only OPTION(s) can be given.\n"
1116 "\n"
1117 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1118 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1119 " [--port=<portnr>\n"
1120 " [--cmd-time-out=<number>] [-l] [-D] [-d]\n"
1121 " \n"
1122 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1123 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1124 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1125 " between the Valgrind gdbserver and vgdb.\n"
1126 " --wait (default 0) tells vgdb to check during the specified number\n"
1127 " of seconds if a Valgrind gdbserver can be found.\n"
1128 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1129 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1130 " process is blocked in a system call).\n"
1131 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1132 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1133 " gdbserver has not processed a command after number seconds\n"
1134 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1135 " -D arg tells to show shared mem status and then exit.\n"
1136 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1137 "\n"
1138 " -h --help shows this message\n"
1139 " To get help from the Valgrind gdbserver, use vgdb help\n"
1140 "\n", vgdb_prefix_default()
1142 invoker_restrictions_msg();
1145 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1146 and then exits.
1148 else if arg_pid == -1, waits maximum check_trials seconds to discover
1149 a valgrind pid appearing.
1151 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1152 with gdbserver activated.
1154 Returns the pid to work with
1155 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1157 static
1158 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1160 int i;
1161 int pid = -1;
1163 if (arg_pid == 0 || arg_pid < -1) {
1164 fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1165 exit (1);
1166 } else {
1167 /* search for a matching named fifo.
1168 If we have been given a pid, we will check that the matching FIFO is
1169 there (or wait the nr of check_trials for this to appear).
1170 If no pid has been given, then if we find only one FIFO,
1171 we will use this to build the pid to use.
1172 If we find multiple processes with valid FIFO, we report them and will
1173 exit with an error. */
1174 DIR *vgdb_dir;
1175 char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
1176 struct dirent *f;
1177 int is;
1178 int nr_valid_pid = 0;
1179 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1180 char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
1182 strcpy (vgdb_format, vgdb_prefix);
1183 strcat (vgdb_format, suffix);
1185 if (strchr(vgdb_prefix, '/') != NULL) {
1186 strcpy (vgdb_dir_name, vgdb_prefix);
1187 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1188 if (vgdb_dir_name[is] == '/') {
1189 vgdb_dir_name[is+1] = '\0';
1190 break;
1192 } else {
1193 strcpy (vgdb_dir_name, "");
1196 DEBUG(1, "searching pid in directory %s format %s\n",
1197 vgdb_dir_name, vgdb_format);
1199 /* try to find FIFOs with valid pid.
1200 On exit of the loop, pid is set to:
1201 the last pid found if show_list (or -1 if no process was listed)
1202 -1 if no FIFOs matching a running process is found
1203 -2 if multiple FIFOs of running processes are found
1204 otherwise it is set to the (only) pid found that can be debugged
1206 for (i = 0; i < check_trials; i++) {
1207 DEBUG(1, "check_trial %d \n", i);
1208 if (i > 0)
1209 /* wait one second before checking again */
1210 sleep(1);
1212 vgdb_dir = opendir (strlen (vgdb_dir_name) ? vgdb_dir_name : "./");
1213 if (vgdb_dir == NULL)
1214 XERROR (errno,
1215 "vgdb error: opening directory %s searching vgdb fifo\n",
1216 vgdb_dir_name);
1218 errno = 0; /* avoid complain if vgdb_dir is empty */
1219 while ((f = readdir (vgdb_dir))) {
1220 struct stat st;
1221 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
1222 char *wrongpid;
1223 int newpid;
1225 strcpy (pathname, vgdb_dir_name);
1226 strcat (pathname, f->d_name);
1227 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
1228 if (stat (pathname, &st) != 0) {
1229 if (debuglevel >= 3)
1230 ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n",
1231 pathname);
1232 } else if (S_ISFIFO (st.st_mode)) {
1233 DEBUG(3, "trying FIFO %s\n", pathname);
1234 if (strncmp (pathname, vgdb_format,
1235 strlen (vgdb_format)) == 0) {
1236 newpid = strtol(pathname + strlen (vgdb_format),
1237 &wrongpid, 10);
1238 if (*wrongpid == '-' && newpid > 0
1239 && kill (newpid, 0) == 0) {
1240 nr_valid_pid++;
1241 if (show_list) {
1242 report_pid (newpid, /*on_stdout*/ True);
1243 pid = newpid;
1244 } else if (arg_pid != -1) {
1245 if (arg_pid == newpid) {
1246 pid = newpid;
1248 } else if (nr_valid_pid > 1) {
1249 if (nr_valid_pid == 2) {
1250 fprintf
1251 (stderr,
1252 "no --pid= arg given"
1253 " and multiple valgrind pids found:\n");
1254 report_pid (pid, /*on_stdout*/ False);
1256 pid = -2;
1257 report_pid (newpid, /*on_stdout*/ False);
1258 } else {
1259 pid = newpid;
1264 errno = 0; /* avoid complain if at the end of vgdb_dir */
1266 if (f == NULL && errno != 0)
1267 XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n",
1268 vgdb_dir_name);
1270 closedir (vgdb_dir);
1271 if (pid != -1)
1272 break;
1275 free (vgdb_dir_name);
1276 free (vgdb_format);
1279 if (show_list) {
1280 exit (1);
1281 } else if (pid == -1) {
1282 if (arg_pid == -1)
1283 fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
1284 else
1285 fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n",
1286 arg_pid);
1287 exit (1);
1289 else if (pid == -2) {
1290 /* no arg_pid given, multiple FIFOs found */
1291 exit (1);
1293 else {
1294 return pid;
1298 /* return true if the numeric value of an option of the
1299 form --xxxxxxxxx=<number> could properly be extracted
1300 from arg. If True is returned, *value contains the
1301 extracted value.*/
1302 static
1303 Bool numeric_val(char* arg, int *value)
1305 const char *eq_pos = strchr(arg, '=');
1306 char *wrong;
1307 long long int long_value;
1309 if (eq_pos == NULL)
1310 return False;
1312 long_value = strtoll(eq_pos+1, &wrong, 10);
1313 if (long_value < 0 || long_value > INT_MAX)
1314 return False;
1315 if (*wrong)
1316 return False;
1318 *value = (int) long_value;
1319 return True;
1322 /* true if arg matches the provided option */
1323 static
1324 Bool is_opt(char* arg, const char *option)
1326 int option_len = strlen(option);
1327 if (option[option_len-1] == '=')
1328 return (0 == strncmp(option, arg, option_len));
1329 else
1330 return (0 == strcmp(option, arg));
1333 /* Parse command lines options. If error(s), exits.
1334 Otherwise returns the options in *p_... args.
1335 commands must be big enough for the commands extracted from argv.
1336 On return, *p_last_command gives the position in commands where
1337 the last command has been allocated (using vmalloc). */
1338 static
1339 void parse_options(int argc, char** argv,
1340 Bool *p_show_shared_mem,
1341 Bool *p_show_list,
1342 int *p_arg_pid,
1343 int *p_check_trials,
1344 int *p_port,
1345 int *p_last_command,
1346 char *commands[])
1348 Bool show_shared_mem = False;
1349 Bool show_list = False;
1350 int arg_pid = -1;
1351 int check_trials = 1;
1352 int last_command = -1;
1353 int int_port = 0;
1355 int i;
1356 int arg_errors = 0;
1358 for (i = 1; i < argc; i++) {
1359 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
1360 usage();
1361 exit(0);
1362 } else if (is_opt(argv[i], "-d")) {
1363 debuglevel++;
1364 } else if (is_opt(argv[i], "-D")) {
1365 show_shared_mem = True;
1366 } else if (is_opt(argv[i], "-l")) {
1367 show_list = True;
1368 } else if (is_opt(argv[i], "--pid=")) {
1369 int newpid;
1370 if (!numeric_val(argv[i], &newpid)) {
1371 fprintf (stderr, "invalid --pid argument %s\n", argv[i]);
1372 arg_errors++;
1373 } else if (arg_pid != -1) {
1374 fprintf (stderr, "multiple --pid arguments given\n");
1375 arg_errors++;
1376 } else {
1377 arg_pid = newpid;
1379 } else if (is_opt(argv[i], "--wait=")) {
1380 if (!numeric_val(argv[i], &check_trials)) {
1381 fprintf (stderr, "invalid --wait argument %s\n", argv[i]);
1382 arg_errors++;
1384 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
1385 if (!numeric_val(argv[i], &max_invoke_ms)) {
1386 fprintf (stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
1387 arg_errors++;
1389 } else if (is_opt(argv[i], "--cmd-time-out=")) {
1390 if (!numeric_val(argv[i], &cmd_time_out)) {
1391 fprintf (stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
1392 arg_errors++;
1394 } else if (is_opt(argv[i], "--port=")) {
1395 if (!numeric_val(argv[i], &int_port)) {
1396 fprintf (stderr, "invalid --port argument %s\n", argv[i]);
1397 arg_errors++;
1399 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
1400 vgdb_prefix = argv[i] + 14;
1401 } else if (is_opt(argv[i], "-c")) {
1402 last_command++;
1403 commands[last_command] = vmalloc (1);
1404 commands[last_command][0] = '\0';
1405 } else if (0 == strncmp(argv[i], "-", 1)) {
1406 fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
1407 arg_errors++;
1408 } else {
1409 int len;
1410 if (last_command == -1) {
1411 /* only one command, no -c command indicator */
1412 last_command++;
1413 commands[last_command] = vmalloc (1);
1414 commands[last_command][0] = '\0';
1416 len = strlen(commands[last_command]);
1417 commands[last_command] = vrealloc (commands[last_command],
1418 len + 1 + strlen(argv[i]) + 1);
1419 if (len > 0)
1420 strcat (commands[last_command], " ");
1421 strcat (commands[last_command], argv[i]);
1422 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
1423 fprintf (stderr, "command %s too long\n", commands[last_command]);
1424 arg_errors++;
1430 if (vgdb_prefix == NULL)
1431 vgdb_prefix = vgdb_prefix_default();
1433 if (isatty(0)
1434 && !show_shared_mem
1435 && !show_list
1436 && int_port == 0
1437 && last_command == -1) {
1438 arg_errors++;
1439 fprintf (stderr,
1440 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1443 if (show_shared_mem && show_list) {
1444 arg_errors++;
1445 fprintf (stderr,
1446 "Can't use both -D and -l options\n");
1449 if (max_invoke_ms > 0
1450 && cmd_time_out != NEVER
1451 && (cmd_time_out * 1000) <= max_invoke_ms) {
1452 arg_errors++;
1453 fprintf (stderr,
1454 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1457 if (show_list && arg_pid != -1) {
1458 arg_errors++;
1459 fprintf (stderr,
1460 "Can't use both --pid and -l options\n");
1463 if (int_port > 0 && last_command != -1) {
1464 arg_errors++;
1465 fprintf (stderr,
1466 "Can't use --port to send commands\n");
1469 if (arg_errors > 0) {
1470 fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
1471 exit(1);
1474 *p_show_shared_mem = show_shared_mem;
1475 *p_show_list = show_list;
1476 *p_arg_pid = arg_pid;
1477 *p_check_trials = check_trials;
1478 *p_port = int_port;
1479 *p_last_command = last_command;
1482 int main(int argc, char** argv)
1484 int i;
1485 int pid;
1487 Bool show_shared_mem;
1488 Bool show_list;
1489 int arg_pid;
1490 int check_trials;
1491 int in_port;
1492 int last_command;
1493 char *commands[argc]; // we will never have more commands than args.
1495 parse_options(argc, argv,
1496 &show_shared_mem,
1497 &show_list,
1498 &arg_pid,
1499 &check_trials,
1500 &in_port,
1501 &last_command,
1502 commands);
1504 /* when we are working as a relay for gdb, handle some signals by
1505 only reporting them (according to debug level). Also handle these
1506 when ptrace will be used: vgdb must clean up the ptrace effect before
1507 dying. */
1508 if (max_invoke_ms > 0 || last_command == -1)
1509 install_handlers();
1511 pid = search_arg_pid (arg_pid, check_trials, show_list);
1513 prepare_fifos_and_shared_mem(pid);
1515 if (in_port > 0)
1516 wait_for_gdb_connect(in_port);
1518 if (show_shared_mem) {
1519 fprintf(stderr,
1520 "vgdb %d "
1521 "written_by_vgdb %d "
1522 "seen_by_valgrind %d\n"
1523 "vgdb pid %d\n",
1524 VS_vgdb_pid,
1525 VS_written_by_vgdb,
1526 VS_seen_by_valgrind,
1527 VS_vgdb_pid);
1528 exit (0);
1531 if (last_command >= 0) {
1532 standalone_send_commands(pid, last_command, commands);
1533 } else {
1534 gdb_relay(pid);
1538 free (from_gdb_to_pid);
1539 free (to_gdb_from_pid);
1540 free (shared_mem);
1542 for (i = 0; i <= last_command; i++)
1543 free (commands[i]);
1544 return 0;