Add support for the Linux io_uring system calls
[valgrind.git] / coregrind / vgdb.c
blob8d213598cbc3bf4a86e415b9387fabb328819560
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 struct timeval dbgtv;
71 static char *vgdb_prefix = NULL;
73 /* Will be set to True when any condition indicating we have to shutdown
74 is encountered. */
75 Bool shutting_down = False;
77 VgdbShared32 *shared32;
78 VgdbShared64 *shared64;
79 #define VS_written_by_vgdb (shared32 != NULL ? \
80 shared32->written_by_vgdb \
81 : shared64->written_by_vgdb)
82 #define VS_seen_by_valgrind (shared32 != NULL ? \
83 shared32->seen_by_valgrind \
84 : shared64->seen_by_valgrind)
86 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
88 void *vmalloc(size_t size)
90 void * mem = malloc(size);
91 if (mem == NULL)
92 XERROR(errno, "can't allocate memory\n");
93 return mem;
96 void *vrealloc(void *ptr,size_t size)
98 void * mem = realloc(ptr, size);
99 if (mem == NULL)
100 XERROR(errno, "can't reallocate memory\n");
101 return mem;
104 /* Return the name of a directory for temporary files. */
105 static
106 const char *vgdb_tmpdir(void)
108 const char *tmpdir;
110 tmpdir = getenv("TMPDIR");
111 if (tmpdir == NULL || *tmpdir == '\0')
112 tmpdir = VG_TMPDIR;
113 if (tmpdir == NULL || *tmpdir == '\0')
114 tmpdir = "/tmp"; /* fallback */
116 return tmpdir;
119 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
120 to communicate with valgrind */
121 static
122 char *vgdb_prefix_default(void)
124 static HChar *prefix;
126 if (prefix == NULL) {
127 const char *tmpdir = vgdb_tmpdir();
128 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
129 strcpy(prefix, tmpdir);
130 strcat(prefix, "/vgdb-pipe");
132 return prefix;
135 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
136 static
137 void add_written(int nrw)
139 if (shared32 != NULL)
140 shared32->written_by_vgdb += nrw;
141 else if (shared64 != NULL)
142 shared64->written_by_vgdb += nrw;
143 else
144 assert(0);
147 static int shared_mem_fd = -1;
148 static
149 void map_vgdbshared(char* shared_mem)
151 struct stat fdstat;
152 void **s;
153 shared_mem_fd = open(shared_mem, O_RDWR);
154 /* shared_mem_fd will not be closed till vgdb exits. */
156 if (shared_mem_fd == -1)
157 XERROR(errno, "error opening %s shared memory file\n", shared_mem);
159 if (fstat(shared_mem_fd, &fdstat) != 0)
160 XERROR(errno, "fstat");
162 if (fdstat.st_size == sizeof(VgdbShared64))
163 s = (void*) &shared64;
164 else if (fdstat.st_size == sizeof(VgdbShared32))
165 s = (void*) &shared32;
166 else
167 #if VEX_HOST_WORDSIZE == 8
168 XERROR(0,
169 "error size shared memory file %s.\n"
170 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
171 shared_mem,
172 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
173 (long int)fdstat.st_size);
174 #elif VEX_HOST_WORDSIZE == 4
175 XERROR(0,
176 "error size shared memory file %s.\n"
177 "expecting size %d (32bits) got %ld.\n",
178 shared_mem,
179 (int) sizeof(VgdbShared32),
180 fdstat.st_size);
181 #else
182 # error "unexpected wordsize"
183 #endif
185 #if VEX_HOST_WORDSIZE == 4
186 if (shared64 != NULL)
187 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
188 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
189 #endif
191 *s = (void*) mmap(NULL, fdstat.st_size,
192 PROT_READ|PROT_WRITE, MAP_SHARED,
193 shared_mem_fd, 0);
195 if (*s == (void *) -1)
196 XERROR(errno, "error mmap shared memory file %s\n", shared_mem);
200 /* This function loops till shutting_down becomes true. In this loop,
201 it verifies if valgrind process is reading the characters written
202 by vgdb. The verification is done every max_invoke_ms ms. If
203 valgrind is not reading characters, it will use invoker_invoke_gdbserver
204 to ensure that the gdbserver code is called soon by valgrind. */
205 static int max_invoke_ms = 100;
206 #define NEVER 99999999
207 static int cmd_time_out = NEVER;
208 static
209 void *invoke_gdbserver_in_valgrind(void *v_pid)
211 struct timeval cmd_max_end_time;
212 Bool cmd_started = False;
213 struct timeval invoke_time;
215 int pid = *(int *)v_pid;
216 int written_by_vgdb_before_sleep;
217 int seen_by_valgrind_before_sleep;
219 int invoked_written = -1;
220 unsigned int usecs;
222 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
224 while (!shutting_down) {
225 written_by_vgdb_before_sleep = VS_written_by_vgdb;
226 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
227 DEBUG(3,
228 "written_by_vgdb_before_sleep %d "
229 "seen_by_valgrind_before_sleep %d\n",
230 written_by_vgdb_before_sleep,
231 seen_by_valgrind_before_sleep);
232 if (cmd_time_out != NEVER
233 && !cmd_started
234 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
235 /* A command was started. Record the time at which it was started. */
236 DEBUG(1, "IO for command started\n");
237 gettimeofday(&cmd_max_end_time, NULL);
238 cmd_max_end_time.tv_sec += cmd_time_out;
239 cmd_started = True;
241 if (max_invoke_ms > 0) {
242 usecs = 1000 * max_invoke_ms;
243 gettimeofday(&invoke_time, NULL);
244 invoke_time.tv_sec += max_invoke_ms / 1000;
245 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
246 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
247 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
248 } else {
249 usecs = 0;
251 if (cmd_started) {
252 // 0 usecs here means the thread just has to check gdbserver eats
253 // the characters in <= cmd_time_out seconds.
254 // We will just wait by 1 second max at a time.
255 if (usecs == 0 || usecs > 1000 * 1000)
256 usecs = 1000 * 1000;
258 usleep(usecs);
260 /* If nothing happened during our sleep, let's try to wake up valgrind
261 or check for cmd time out. */
262 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
263 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
264 && VS_written_by_vgdb > VS_seen_by_valgrind) {
265 struct timeval now;
266 gettimeofday(&now, NULL);
267 DEBUG(2,
268 "after sleep "
269 "written_by_vgdb %d "
270 "seen_by_valgrind %d "
271 "invoked_written %d\n",
272 VS_written_by_vgdb,
273 VS_seen_by_valgrind,
274 invoked_written);
275 /* if the pid does not exist anymore, we better stop */
276 if (kill(pid, 0) != 0)
277 XERROR(errno,
278 "invoke_gdbserver_in_valgrind: "
279 "check for pid %d existence failed\n", pid);
280 if (cmd_started) {
281 if (timercmp(&now, &cmd_max_end_time, >))
282 XERROR(0,
283 "pid %d did not handle a command in %d seconds\n",
284 pid, cmd_time_out);
286 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
287 /* only need to wake up if the nr written has changed since
288 last invoke. */
289 if (invoked_written != written_by_vgdb_before_sleep) {
290 if (invoker_invoke_gdbserver(pid)) {
291 /* If invoke successful, no need to invoke again
292 for the same value of written_by_vgdb_before_sleep. */
293 invoked_written = written_by_vgdb_before_sleep;
297 } else {
298 // Something happened => restart timer check.
299 if (cmd_time_out != NEVER) {
300 DEBUG(2, "some IO was done => restart command\n");
301 cmd_started = False;
305 pthread_cleanup_pop(0);
306 return NULL;
309 static
310 int open_fifo(const char* name, int flags, const char* desc)
312 int fd;
313 DEBUG(1, "opening %s %s\n", name, desc);
314 fd = open(name, flags);
315 if (fd == -1)
316 XERROR(errno, "error opening %s %s\n", name, desc);
318 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
319 return fd;
322 /* acquire a lock on the first byte of the given fd. If not successful,
323 exits with error.
324 This allows to avoid having two vgdb speaking with the same Valgrind
325 gdbserver as this causes serious headaches to the protocol. */
326 static
327 void acquire_lock(int fd, int valgrind_pid)
329 struct flock fl;
330 fl.l_type = F_WRLCK;
331 fl.l_whence = SEEK_SET;
332 fl.l_start = 0;
333 fl.l_len = 1;
334 if (fcntl(fd, F_SETLK, &fl) < 0) {
335 if (errno == EAGAIN || errno == EACCES) {
336 XERROR(errno,
337 "Cannot acquire lock.\n"
338 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
339 VS_vgdb_pid,
340 valgrind_pid);
341 } else {
342 XERROR(errno, "cannot acquire lock.\n");
346 /* Here, we have the lock. It will be released when fd will be closed. */
347 /* We indicate our pid to Valgrind gdbserver */
348 if (shared32 != NULL)
349 shared32->vgdb_pid = getpid();
350 else if (shared64 != NULL)
351 shared64->vgdb_pid = getpid();
352 else
353 assert(0);
356 #define PBUFSIZ 16384 /* keep in sync with server.h */
358 /* read some characters from fd.
359 Returns the nr of characters read, -1 if error.
360 desc is a string used in tracing */
361 static
362 int read_buf(int fd, char* buf, const char* desc)
364 int nrread;
365 DEBUG(2, "reading %s\n", desc);
366 nrread = read(fd, buf, PBUFSIZ);
367 if (nrread == -1) {
368 ERROR(errno, "error reading %s\n", desc);
369 return -1;
371 buf[nrread] = '\0';
372 DEBUG(2, "read %s %s\n", desc, buf);
373 return nrread;
376 /* write size bytes from buf to fd.
377 desc is a description of the action for which the write is done.
378 If notify, then add size to the shared cntr indicating to the
379 valgrind process that there is new data.
380 Returns True if write is ok, False if there was a problem. */
381 static
382 Bool write_buf(int fd, const char* buf, int size, const char* desc, Bool notify)
384 int nrwritten;
385 int nrw;
386 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
387 size, buf, notify);
388 nrwritten = 0;
389 while (nrwritten < size) {
390 nrw = write(fd, buf+nrwritten, size - nrwritten);
391 if (nrw == -1) {
392 ERROR(errno, "error write %s\n", desc);
393 return False;
395 nrwritten = nrwritten + nrw;
396 if (notify)
397 add_written(nrw);
399 return True;
402 typedef enum {
403 FROM_GDB,
404 TO_GDB,
405 FROM_PID,
406 TO_PID } ConnectionKind;
407 static const int NumConnectionKind = TO_PID+1;
408 static
409 const char *ppConnectionKind(ConnectionKind con)
411 switch (con) {
412 case FROM_GDB: return "FROM_GDB";
413 case TO_GDB: return "TO_GDB";
414 case FROM_PID: return "FROM_PID";
415 case TO_PID: return "TO_PID";
416 default: return "invalid connection kind";
420 static char *shared_mem;
422 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
423 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
424 /* Returns True in case read/write operations were done properly.
425 Returns False in case of error.
426 to_pid is the file descriptor to write to the process pid. */
427 static
428 Bool read_from_gdb_write_to_pid(int to_pid)
430 char buf[PBUFSIZ+1]; // +1 for trailing \0
431 int nrread;
433 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
434 if (nrread <= 0) {
435 if (nrread == 0)
436 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
437 else
438 DEBUG(1, "error reading bytes from gdb\n");
439 close(from_gdb);
440 shutting_down = True;
441 return False;
443 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
446 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
447 static char *to_gdb_from_pid; /* fifo name to read pid replies */
448 /* Returns True in case read/write operations were done properly.
449 Returns False in case of error.
450 from_pid is the file descriptor to read data from the process pid. */
451 static
452 Bool read_from_pid_write_to_gdb(int from_pid)
454 char buf[PBUFSIZ+1]; // +1 for trailing \0
455 int nrread;
457 nrread = read_buf(from_pid, buf, "from pid");
458 if (nrread <= 0) {
459 if (nrread == 0)
460 DEBUG(1, "read 0 bytes from pid => assume exit\n");
461 else
462 DEBUG(1, "error reading bytes from pid\n");
463 close(from_pid);
464 shutting_down = True;
465 return False;
467 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
470 static
471 void wait_for_gdb_connect(int in_port)
473 struct sockaddr_in addr;
475 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
476 int gdb_connect;
478 if (-1 == listen_gdb) {
479 XERROR(errno, "cannot create socket");
482 memset(&addr, 0, sizeof(addr));
484 addr.sin_family = AF_INET;
485 addr.sin_port = htons((unsigned short int)in_port);
486 addr.sin_addr.s_addr = INADDR_ANY;
488 if (-1 == bind(listen_gdb, (struct sockaddr *)&addr, sizeof(addr))) {
489 XERROR(errno, "bind failed");
491 fprintf(stderr, "listening on port %d ...", in_port);
492 fflush(stderr);
493 if (-1 == listen(listen_gdb, 1)) {
494 XERROR(errno, "error listen failed");
497 gdb_connect = accept(listen_gdb, NULL, NULL);
498 if (gdb_connect < 0) {
499 XERROR(errno, "accept failed");
501 fprintf(stderr, "connected.\n");
502 fflush(stderr);
503 close(listen_gdb);
504 from_gdb = gdb_connect;
505 to_gdb = gdb_connect;
508 /* prepares the FIFOs filenames, map the shared memory. */
509 static
510 void prepare_fifos_and_shared_mem(int pid)
512 const HChar *user, *host;
513 unsigned len;
515 user = getenv("LOGNAME");
516 if (user == NULL) user = getenv("USER");
517 if (user == NULL) user = "???";
518 if (strchr(user, '/')) user = "???";
520 host = getenv("HOST");
521 if (host == NULL) host = getenv("HOSTNAME");
522 if (host == NULL) host = "???";
523 if (strchr(host, '/')) host = "???";
525 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
526 from_gdb_to_pid = vmalloc(len);
527 to_gdb_from_pid = vmalloc(len);
528 shared_mem = vmalloc(len);
529 /* below 3 lines must match the equivalent in remote-utils.c */
530 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
531 pid, user, host);
532 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
533 pid, user, host);
534 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
535 pid, user, host);
536 DEBUG(1, "vgdb: using %s %s %s\n",
537 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
539 map_vgdbshared(shared_mem);
542 /* Convert hex digit A to a number. */
544 static int
545 fromhex(int a)
547 if (a >= '0' && a <= '9')
548 return a - '0';
549 else if (a >= 'a' && a <= 'f')
550 return a - 'a' + 10;
551 else
552 XERROR(0, "Reply contains invalid hex digit %c\n", a);
553 return 0;
556 /* Returns next char from fd. -1 if error, -2 if EOF.
557 NB: must always call it with the same fd */
558 static int
559 readchar(int fd)
561 static char buf[PBUFSIZ+1]; // +1 for trailing \0
562 static int bufcnt = 0;
563 static unsigned char *bufp;
564 // unsigned bufp to e.g. avoid having 255 converted to int -1
566 if (bufcnt-- > 0)
567 return *bufp++;
569 bufcnt = read_buf(fd, buf, "static buf readchar");
571 if (bufcnt <= 0) {
572 if (bufcnt == 0) {
573 fprintf(stderr, "readchar: Got EOF\n");
574 return -2;
575 } else {
576 ERROR(errno, "readchar\n");
577 return -1;
581 bufp = (unsigned char *)buf;
582 bufcnt--;
583 return *bufp++;
586 /* Read a packet from fromfd, with error checking,
587 and store it in BUF.
588 If checksum incorrect, writes a - on ackfd.
589 Returns length of packet, or -1 if error or -2 if EOF. */
590 static int
591 getpkt(char *buf, int fromfd, int ackfd)
593 char *bp;
594 unsigned char csum, c1, c2;
595 int c;
597 while (1) {
598 csum = 0;
600 while (1) {
601 c = readchar(fromfd);
602 if (c == '$')
603 break;
604 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
605 if (c < 0)
606 return c;
609 bp = buf;
610 while (1) {
611 c = readchar(fromfd);
612 if (c < 0)
613 return c;
614 if (c == '#')
615 break;
616 if (c == '*') {
617 int repeat;
618 int r;
619 int prev;
620 prev = *(bp-1);
621 csum += c;
622 repeat = readchar(fromfd);
623 csum += repeat;
624 for (r = 0; r < repeat - 29; r ++)
625 *bp++ = prev;
626 } else {
627 *bp++ = c;
628 csum += c;
631 *bp = 0;
633 c1 = fromhex(readchar (fromfd));
634 c2 = fromhex(readchar (fromfd));
636 if (csum == (c1 << 4) + c2)
637 break;
639 fprintf(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
640 (c1 << 4) + c2, csum, buf);
641 if (write(ackfd, "-", 1) != 1)
642 ERROR(0, "error when writing - (nack)\n");
643 else
644 add_written(1);
647 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
648 return bp - buf;
651 static int sigint = 0;
652 static int sigterm = 0;
653 static int sigpipe = 0;
654 static int sighup = 0;
655 static int sigusr1 = 0;
656 static int sigalrm = 0;
657 static int sigusr1_fd = -1;
658 static pthread_t invoke_gdbserver_in_valgrind_thread;
660 static
661 void received_signal(int signum)
663 if (signum == SIGINT)
664 sigint++;
665 else if (signum == SIGUSR1) {
666 sigusr1++;
667 if (sigusr1_fd >= 0) {
668 char control_c = '\003';
669 write_buf(sigusr1_fd, &control_c, 1,
670 "write \\003 on SIGUSR1", /* notify */ True);
673 else if (signum == SIGTERM) {
674 shutting_down = True;
675 sigterm++;
676 } else if (signum == SIGHUP) {
677 shutting_down = True;
678 sighup++;
679 } else if (signum == SIGPIPE) {
680 sigpipe++;
681 } else if (signum == SIGALRM) {
682 sigalrm++;
683 #if defined(VGPV_arm_linux_android) \
684 || defined(VGPV_x86_linux_android) \
685 || defined(VGPV_mips32_linux_android) \
686 || defined(VGPV_arm64_linux_android)
687 /* Android has no pthread_cancel. As it also does not have
688 an invoker implementation, there is no need for cleanup action.
689 So, we just do nothing. */
690 DEBUG(1, "sigalrm received, no action on android\n");
691 #else
692 /* Note: we cannot directly invoke restore_and_detach : this must
693 be done by the thread that has attached.
694 We have in this thread pushed a cleanup handler that will
695 cleanup what is needed. */
696 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
697 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
698 #endif
699 } else {
700 ERROR(0, "unexpected signal %d\n", signum);
704 /* install the signal handlers allowing e.g. vgdb to cleanup in
705 case of termination. */
706 static
707 void install_handlers(void)
709 struct sigaction action, oldaction;
711 action.sa_handler = received_signal;
712 sigemptyset(&action.sa_mask);
713 action.sa_flags = 0;
715 /* SIGINT: when user types C-c in gdb, this sends
716 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
717 The later is enough to wakeup the valgrind process. */
718 if (sigaction(SIGINT, &action, &oldaction) != 0)
719 XERROR(errno, "vgdb error sigaction SIGINT\n");
720 /* We might do something more intelligent than just
721 reporting this SIGINT E.g. behave similarly to the gdb: two
722 control-C without feedback from the debugged process would
723 mean to stop debugging it. */
725 /* SIGUSR1: this is used to facilitate automatic testing. When
726 vgdb receives this signal, it will simulate the user typing C-c. */
727 if (sigaction(SIGUSR1, &action, &oldaction) != 0)
728 XERROR(errno, "vgdb error sigaction SIGUSR1\n");
731 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
732 when detaching or similar. A clean shutdown will be done as both
733 the read and write side will detect an end of file. */
734 if (sigaction(SIGTERM, &action, &oldaction) != 0)
735 XERROR(errno, "vgdb error sigaction SIGTERM\n");
737 /* SIGPIPE: can receive this signal when gdb detaches or kill the
738 process debugged: gdb will close its pipes to vgdb. vgdb
739 must resist to this signal to allow a clean shutdown. */
740 if (sigaction(SIGPIPE, &action, &oldaction) != 0)
741 XERROR(errno, "vgdb error sigaction SIGPIPE\n");
743 /* SIGALRM: in case invoke thread is blocked, alarm is used
744 to cleanup. */
745 if (sigaction(SIGALRM, &action, &oldaction) != 0)
746 XERROR(errno, "vgdb error sigaction SIGALRM\n");
748 /* unmask all signals, in case the process that launched vgdb
749 masked some. */
750 if (sigprocmask(SIG_SETMASK, &action.sa_mask, NULL) != 0)
751 XERROR(errno, "vgdb error sigprocmask");
754 /* close the FIFOs provided connections, terminate the invoker thread. */
755 static
756 void close_connection(int to_pid, int from_pid)
758 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
759 sigint, sigterm, sighup, sigpipe);
760 /* Note that we do not forward sigterm to the valgrind process:
761 a sigterm signal is (probably) received from gdb if the user wants to
762 kill the debugged process. The kill instruction has been given to
763 the valgrind process, which should execute a clean exit. */
765 /* We first close the connection to pid. The pid will then
766 terminates its gdbserver work. We keep the from pid
767 fifo opened till the invoker thread is finished.
768 This allows the gdbserver to finish sending its last reply. */
769 if (close(to_pid) != 0)
770 ERROR(errno, "close to_pid\n");
772 /* if there is a task that was busy trying to wake up valgrind
773 process, we wait for it to be terminated otherwise threads
774 in the valgrind process can stay stopped if vgdb main
775 exits before the invoke thread had time to detach from
776 all valgrind threads. */
777 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
778 int join;
780 /* It is surprisingly complex to properly shutdown or exit the
781 valgrind process in which gdbserver has been invoked through
782 ptrace. In the normal case (gdb detaches from the process,
783 or process is continued), the valgrind process will reach the
784 breakpoint place. Using ptrace, vgdb will ensure the
785 previous activity of the process is resumed (e.g. restart a
786 blocking system call). The special case is when gdb asks the
787 valgrind process to exit (using either the "kill" command or
788 "monitor exit"). In such a case, the valgrind process will
789 call exit. But a ptraced process will be blocked in exit,
790 waiting for the ptracing process to detach or die. vgdb
791 cannot detach unconditionally as otherwise, in the normal
792 case, the valgrind process would stop abnormally with SIGSTOP
793 (as vgdb would not be there to catch it). vgdb can also not
794 die unconditionally otherwise again, similar problem. So, we
795 assume that most of the time, we arrive here in the normal
796 case, and so, the breakpoint has been encountered by the
797 valgrind process, so the invoker thread will exit and the
798 join will succeed. For the "kill" case, we cause an alarm
799 signal to be sent after a few seconds. This means that in the
800 normal case, the gdbserver code in valgrind process must have
801 returned the control in less than the alarm nr of seconds,
802 otherwise, valgrind will stop abnormally with SIGSTOP. */
803 (void) alarm(3);
805 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
806 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
807 if (join != 0)
808 XERROR
809 (join,
810 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
812 if (close(from_pid) != 0)
813 ERROR(errno, "close from_pid\n");
816 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
817 error is encountered. */
818 static
819 void gdb_relay(int pid)
821 int from_pid = -1; /* fd to read from pid */
822 int to_pid = -1; /* fd to write to pid */
824 int shutdown_loop = 0;
825 fprintf(stderr, "relaying data between gdb and process %d\n", pid);
826 fflush(stderr);
828 if (max_invoke_ms > 0)
829 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
830 invoke_gdbserver_in_valgrind, (void *) &pid);
831 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
832 acquire_lock(shared_mem_fd, pid);
834 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
835 "read mode from pid");
837 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
839 while (1) {
840 ConnectionKind ck;
841 int ret;
842 struct pollfd pollfds[NumConnectionKind];
844 /* watch data written by gdb, watch POLLERR on both gdb fd */
845 pollfds[FROM_GDB].fd = from_gdb;
846 pollfds[FROM_GDB].events = POLLIN;
847 pollfds[FROM_GDB].revents = 0;
848 pollfds[TO_GDB].fd = to_gdb;
849 pollfds[TO_GDB].events = 0;
850 pollfds[TO_GDB].revents = 0;
852 /* watch data written by pid, watch POLLERR on both pid fd */
853 pollfds[FROM_PID].fd = from_pid;
854 pollfds[FROM_PID].events = POLLIN;
855 pollfds[FROM_PID].revents = 0;
856 pollfds[TO_PID].fd = to_pid;
857 pollfds[TO_PID].events = 0;
858 pollfds[TO_PID].revents = 0;
860 ret = poll(pollfds,
861 NumConnectionKind,
862 (shutting_down ?
863 1 /* one second */
864 : -1 /* infinite */));
865 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
867 /* check for unexpected error */
868 if (ret <= 0 && errno != EINTR) {
869 ERROR(errno, "unexpected poll ret %d\n", ret);
870 shutting_down = True;
871 break;
874 /* check for data to read */
875 for (ck = 0; ck < NumConnectionKind; ck ++) {
876 if (pollfds[ck].revents & POLLIN) {
877 switch (ck) {
878 case FROM_GDB:
879 if (!read_from_gdb_write_to_pid(to_pid))
880 shutting_down = True;
881 break;
882 case FROM_PID:
883 if (!read_from_pid_write_to_gdb(from_pid))
884 shutting_down = True;
885 break;
886 default: XERROR(0, "unexpected POLLIN on %s\n",
887 ppConnectionKind(ck));
892 /* check for an fd being in error condition */
893 for (ck = 0; ck < NumConnectionKind; ck ++) {
894 if (pollfds[ck].revents & POLLERR) {
895 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
896 ppConnectionKind(ck), pollfds[ck].fd);
897 invoker_valgrind_dying();
898 shutting_down = True;
900 if (pollfds[ck].revents & POLLHUP) {
901 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
902 ppConnectionKind(ck), pollfds[ck].fd);
903 invoker_valgrind_dying();
904 shutting_down = True;
906 if (pollfds[ck].revents & POLLNVAL) {
907 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
908 ppConnectionKind(ck), pollfds[ck].fd);
909 invoker_valgrind_dying();
910 shutting_down = True;
914 if (shutting_down) {
915 /* we let some time to the final packets to be transferred */
916 shutdown_loop++;
917 if (shutdown_loop > 3)
918 break;
921 close_connection(to_pid, from_pid);
924 static int packet_len_for_command(char *cmd)
926 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
927 return 7+ 2*strlen(cmd) +3 + 1;
930 /* hyper-minimal protocol implementation that
931 sends the provided commands (using qRcmd packets)
932 and read and display their replies. */
933 static
934 void standalone_send_commands(int pid,
935 int last_command,
936 char *commands[] )
938 int from_pid = -1; /* fd to read from pid */
939 int to_pid = -1; /* fd to write to pid */
941 int i;
942 int hi;
943 char hex[3];
944 unsigned char cksum;
945 char *hexcommand;
946 char buf[PBUFSIZ+1]; // +1 for trailing \0
947 int buflen;
948 int nc;
951 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
952 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
953 invoke_gdbserver_in_valgrind, (void *) &pid);
955 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
956 acquire_lock(shared_mem_fd, pid);
958 /* first send a C-c \003 to pid, so that it wakes up the process
959 After that, we can open the fifo from the pid in read mode
960 We then start to wait for packets (normally first a resume reply)
961 At that point, we send our command and expect replies */
962 buf[0] = '\003';
963 i = 0;
964 while (!write_buf(to_pid, buf, 1,
965 "write \\003 to wake up", /* notify */ True)) {
966 /* If write fails, retries up to 10 times every 0.5 seconds
967 This aims at solving the race condition described in
968 remote-utils.c remote_finish function. */
969 usleep(500*1000);
970 i++;
971 if (i >= 10)
972 XERROR(errno, "failed to send wake up char after 10 trials\n");
974 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
975 "read cmd result from pid");
977 /* Enable no ack mode. */
978 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
979 /* notify */ True);
980 buflen = getpkt(buf, from_pid, to_pid);
981 if (buflen != 2 || strcmp(buf, "OK") != 0) {
982 if (buflen != 2)
983 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen);
984 else
985 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
988 for (nc = 0; nc <= last_command; nc++) {
989 fprintf(stderr, "sending command %s to pid %d\n", commands[nc], pid);
990 fflush(stderr);
992 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
993 hexcommand = vmalloc(packet_len_for_command(commands[nc]));
994 hexcommand[0] = 0;
995 strcat(hexcommand, "$qRcmd,");
996 for (i = 0; i < strlen(commands[nc]); i++) {
997 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
998 // Need to use unsigned char, to avoid sign extension.
999 strcat(hexcommand, hex);
1001 /* checksum (but without the $) */
1002 cksum = 0;
1003 for (hi = 1; hi < strlen(hexcommand); hi++)
1004 cksum+=hexcommand[hi];
1005 strcat(hexcommand, "#");
1006 sprintf(hex, "%02x", cksum);
1007 strcat(hexcommand, hex);
1008 write_buf(to_pid, hexcommand, strlen(hexcommand),
1009 "writing hex command to pid", /* notify */ True);
1011 /* we exit of the below loop explicitly when the command has
1012 been handled or because a signal handler will set
1013 shutting_down. */
1014 while (!shutting_down) {
1015 buflen = getpkt(buf, from_pid, to_pid);
1016 if (buflen < 0) {
1017 ERROR(0, "error reading packet\n");
1018 if (buflen == -2)
1019 invoker_valgrind_dying();
1020 break;
1022 if (strlen(buf) == 0) {
1023 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1024 break;
1026 if (strcmp(buf, "OK") == 0) {
1027 DEBUG(1, "OK packet rcvd\n");
1028 break;
1030 if (buf[0] == 'E') {
1031 DEBUG(0,
1032 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1033 buf);
1034 break;
1036 if (buf[0] == 'W') {
1037 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1038 break;
1040 if (buf[0] == 'T') {
1041 DEBUG(1, "T resume reply packet received: %s\n", buf);
1042 continue;
1045 /* must be here an O packet with hex encoded string reply
1046 => decode and print it */
1047 if (buf[0] != 'O') {
1048 DEBUG(0, "expecting O packet, received: %s\n", buf);
1049 continue;
1052 char buf_print[buflen/2 + 1];
1053 for (i = 1; i < buflen; i = i + 2)
1054 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1055 + fromhex(*(buf+i+1));
1056 buf_print[buflen/2] = 0;
1057 printf("%s", buf_print);
1058 fflush(stdout);
1061 free(hexcommand);
1063 shutting_down = True;
1065 close_connection(to_pid, from_pid);
1068 /* report to user the existence of a vgdb-able valgrind process
1069 with given pid.
1070 Note: this function does not use XERROR if an error is encountered
1071 while producing the command line for pid, as this is not critical
1072 and at least on MacOS, reading cmdline is not available. */
1073 static
1074 void report_pid(int pid, Bool on_stdout)
1076 char cmdline_file[50]; // large enough
1077 int fd, i;
1078 FILE *out = on_stdout ? stdout : stderr;
1080 fprintf(out, "use --pid=%d for ", pid);
1082 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1083 fd = open(cmdline_file, O_RDONLY);
1084 if (fd == -1) {
1085 DEBUG(1, "error opening cmdline file %s %s\n",
1086 cmdline_file, strerror(errno));
1087 fprintf(out, "(could not open process command line)\n");
1088 } else {
1089 char cmdline[100];
1090 ssize_t sz;
1091 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) > 0) {
1092 for (i = 0; i < sz; i++)
1093 if (cmdline[i] == 0)
1094 cmdline[i] = ' ';
1095 cmdline[sz] = 0;
1096 fprintf(out, "%s", cmdline);
1098 if (sz == -1) {
1099 DEBUG(1, "error reading cmdline file %s %s\n",
1100 cmdline_file, strerror(errno));
1101 fprintf(out, "(error reading process command line)");
1103 fprintf(out, "\n");
1104 close(fd);
1106 fflush(out);
1109 static
1110 void usage(void)
1112 fprintf(stderr,
1113 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1114 "vgdb (valgrind gdb) has two usages\n"
1115 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1116 " The OPTION(s) must be followed by the command to send\n"
1117 " To send more than one command, separate the commands with -c\n"
1118 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1119 " Only OPTION(s) can be given.\n"
1120 "\n"
1121 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1122 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1123 " [--port=<portnr>\n"
1124 " [--cmd-time-out=<number>] [-l] [-D] [-d]\n"
1125 " \n"
1126 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1127 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1128 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1129 " between the Valgrind gdbserver and vgdb.\n"
1130 " --wait (default 0) tells vgdb to check during the specified number\n"
1131 " of seconds if a Valgrind gdbserver can be found.\n"
1132 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1133 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1134 " process is blocked in a system call).\n"
1135 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1136 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1137 " gdbserver has not processed a command after number seconds\n"
1138 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1139 " -D arg tells to show shared mem status and then exit.\n"
1140 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1141 "\n"
1142 " -h --help shows this message\n"
1143 " To get help from the Valgrind gdbserver, use vgdb help\n"
1144 "\n", vgdb_prefix_default()
1146 invoker_restrictions_msg();
1149 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1150 and then exits.
1152 else if arg_pid == -1, waits maximum check_trials seconds to discover
1153 a valgrind pid appearing.
1155 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1156 with gdbserver activated.
1158 Returns the pid to work with
1159 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1161 static
1162 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1164 int i;
1165 int pid = -1;
1167 if (arg_pid == 0 || arg_pid < -1) {
1168 fprintf(stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1169 exit(1);
1170 } else {
1171 /* search for a matching named fifo.
1172 If we have been given a pid, we will check that the matching FIFO is
1173 there (or wait the nr of check_trials for this to appear).
1174 If no pid has been given, then if we find only one FIFO,
1175 we will use this to build the pid to use.
1176 If we find multiple processes with valid FIFO, we report them and will
1177 exit with an error. */
1178 DIR *vgdb_dir;
1179 char *vgdb_dir_name = vmalloc(strlen (vgdb_prefix) + 3);
1180 struct dirent *f;
1181 int is;
1182 int nr_valid_pid = 0;
1183 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1184 char *vgdb_format = vmalloc(strlen(vgdb_prefix) + strlen(suffix) + 1);
1186 strcpy(vgdb_format, vgdb_prefix);
1187 strcat(vgdb_format, suffix);
1189 if (strchr(vgdb_prefix, '/') != NULL) {
1190 strcpy(vgdb_dir_name, vgdb_prefix);
1191 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1192 if (vgdb_dir_name[is] == '/') {
1193 vgdb_dir_name[is+1] = '\0';
1194 break;
1196 } else {
1197 strcpy(vgdb_dir_name, "");
1200 DEBUG(1, "searching pid in directory %s format %s\n",
1201 vgdb_dir_name, vgdb_format);
1203 /* try to find FIFOs with valid pid.
1204 On exit of the loop, pid is set to:
1205 the last pid found if show_list (or -1 if no process was listed)
1206 -1 if no FIFOs matching a running process is found
1207 -2 if multiple FIFOs of running processes are found
1208 otherwise it is set to the (only) pid found that can be debugged
1210 for (i = 0; i < check_trials; i++) {
1211 DEBUG(1, "check_trial %d \n", i);
1212 if (i > 0)
1213 /* wait one second before checking again */
1214 sleep(1);
1216 vgdb_dir = opendir(strlen(vgdb_dir_name) ? vgdb_dir_name : "./");
1217 if (vgdb_dir == NULL)
1218 XERROR(errno,
1219 "vgdb error: opening directory %s searching vgdb fifo\n",
1220 vgdb_dir_name);
1222 errno = 0; /* avoid complain if vgdb_dir is empty */
1223 while ((f = readdir(vgdb_dir))) {
1224 struct stat st;
1225 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
1226 char *wrongpid;
1227 int newpid;
1229 strcpy(pathname, vgdb_dir_name);
1230 strcat(pathname, f->d_name);
1231 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
1232 if (stat(pathname, &st) != 0) {
1233 if (debuglevel >= 3)
1234 ERROR(errno, "vgdb error: stat %s searching vgdb fifo\n",
1235 pathname);
1236 } else if (S_ISFIFO(st.st_mode)) {
1237 DEBUG(3, "trying FIFO %s\n", pathname);
1238 if (strncmp(pathname, vgdb_format,
1239 strlen(vgdb_format)) == 0) {
1240 newpid = strtol(pathname + strlen(vgdb_format),
1241 &wrongpid, 10);
1242 if (*wrongpid == '-' && newpid > 0
1243 && kill(newpid, 0) == 0) {
1244 nr_valid_pid++;
1245 if (show_list) {
1246 report_pid(newpid, /*on_stdout*/ True);
1247 pid = newpid;
1248 } else if (arg_pid != -1) {
1249 if (arg_pid == newpid) {
1250 pid = newpid;
1252 } else if (nr_valid_pid > 1) {
1253 if (nr_valid_pid == 2) {
1254 fprintf
1255 (stderr,
1256 "no --pid= arg given"
1257 " and multiple valgrind pids found:\n");
1258 report_pid(pid, /*on_stdout*/ False);
1260 pid = -2;
1261 report_pid(newpid, /*on_stdout*/ False);
1262 } else {
1263 pid = newpid;
1268 errno = 0; /* avoid complain if at the end of vgdb_dir */
1270 if (f == NULL && errno != 0)
1271 XERROR(errno, "vgdb error: reading directory %s for vgdb fifo\n",
1272 vgdb_dir_name);
1274 closedir(vgdb_dir);
1275 if (pid != -1)
1276 break;
1279 free(vgdb_dir_name);
1280 free(vgdb_format);
1283 if (show_list) {
1284 exit(1);
1285 } else if (pid == -1) {
1286 if (arg_pid == -1)
1287 fprintf(stderr, "vgdb error: no FIFO found and no pid given\n");
1288 else
1289 fprintf(stderr, "vgdb error: no FIFO found matching pid %d\n",
1290 arg_pid);
1291 exit(1);
1293 else if (pid == -2) {
1294 /* no arg_pid given, multiple FIFOs found */
1295 exit(1);
1297 else {
1298 return pid;
1302 /* return true if the numeric value of an option of the
1303 form --xxxxxxxxx=<number> could properly be extracted
1304 from arg. If True is returned, *value contains the
1305 extracted value.*/
1306 static
1307 Bool numeric_val(char* arg, int *value)
1309 const char *eq_pos = strchr(arg, '=');
1310 char *wrong;
1311 long long int long_value;
1313 if (eq_pos == NULL)
1314 return False;
1316 long_value = strtoll(eq_pos+1, &wrong, 10);
1317 if (long_value < 0 || long_value > INT_MAX)
1318 return False;
1319 if (*wrong)
1320 return False;
1322 *value = (int) long_value;
1323 return True;
1326 /* true if arg matches the provided option */
1327 static
1328 Bool is_opt(char* arg, const char *option)
1330 int option_len = strlen(option);
1331 if (option[option_len-1] == '=')
1332 return (0 == strncmp(option, arg, option_len));
1333 else
1334 return (0 == strcmp(option, arg));
1337 /* Parse command lines options. If error(s), exits.
1338 Otherwise returns the options in *p_... args.
1339 commands must be big enough for the commands extracted from argv.
1340 On return, *p_last_command gives the position in commands where
1341 the last command has been allocated (using vmalloc). */
1342 static
1343 void parse_options(int argc, char** argv,
1344 Bool *p_show_shared_mem,
1345 Bool *p_show_list,
1346 int *p_arg_pid,
1347 int *p_check_trials,
1348 int *p_port,
1349 int *p_last_command,
1350 char *commands[])
1352 Bool show_shared_mem = False;
1353 Bool show_list = False;
1354 int arg_pid = -1;
1355 int check_trials = 1;
1356 int last_command = -1;
1357 int int_port = 0;
1359 int i;
1360 int arg_errors = 0;
1362 for (i = 1; i < argc; i++) {
1363 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
1364 usage();
1365 exit(0);
1366 } else if (is_opt(argv[i], "-d")) {
1367 debuglevel++;
1368 } else if (is_opt(argv[i], "-D")) {
1369 show_shared_mem = True;
1370 } else if (is_opt(argv[i], "-l")) {
1371 show_list = True;
1372 } else if (is_opt(argv[i], "--pid=")) {
1373 int newpid;
1374 if (!numeric_val(argv[i], &newpid)) {
1375 fprintf(stderr, "invalid --pid argument %s\n", argv[i]);
1376 arg_errors++;
1377 } else if (arg_pid != -1) {
1378 fprintf(stderr, "multiple --pid arguments given\n");
1379 arg_errors++;
1380 } else {
1381 arg_pid = newpid;
1383 } else if (is_opt(argv[i], "--wait=")) {
1384 if (!numeric_val(argv[i], &check_trials)) {
1385 fprintf(stderr, "invalid --wait argument %s\n", argv[i]);
1386 arg_errors++;
1388 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
1389 if (!numeric_val(argv[i], &max_invoke_ms)) {
1390 fprintf(stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
1391 arg_errors++;
1393 } else if (is_opt(argv[i], "--cmd-time-out=")) {
1394 if (!numeric_val(argv[i], &cmd_time_out)) {
1395 fprintf(stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
1396 arg_errors++;
1398 } else if (is_opt(argv[i], "--port=")) {
1399 if (!numeric_val(argv[i], &int_port)) {
1400 fprintf(stderr, "invalid --port argument %s\n", argv[i]);
1401 arg_errors++;
1403 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
1404 vgdb_prefix = argv[i] + 14;
1405 } else if (is_opt(argv[i], "-c")) {
1406 last_command++;
1407 commands[last_command] = vmalloc(1);
1408 commands[last_command][0] = '\0';
1409 } else if (0 == strncmp(argv[i], "-", 1)) {
1410 fprintf(stderr, "unknown or invalid argument %s\n", argv[i]);
1411 arg_errors++;
1412 } else {
1413 int len;
1414 if (last_command == -1) {
1415 /* only one command, no -c command indicator */
1416 last_command++;
1417 commands[last_command] = vmalloc(1);
1418 commands[last_command][0] = '\0';
1420 len = strlen(commands[last_command]);
1421 commands[last_command] = vrealloc(commands[last_command],
1422 len + 1 + strlen(argv[i]) + 1);
1423 if (len > 0)
1424 strcat(commands[last_command], " ");
1425 strcat(commands[last_command], argv[i]);
1426 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
1427 fprintf(stderr, "command %s too long\n", commands[last_command]);
1428 arg_errors++;
1434 if (vgdb_prefix == NULL)
1435 vgdb_prefix = vgdb_prefix_default();
1437 if (isatty(0)
1438 && !show_shared_mem
1439 && !show_list
1440 && int_port == 0
1441 && last_command == -1) {
1442 arg_errors++;
1443 fprintf(stderr,
1444 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1447 if (show_shared_mem && show_list) {
1448 arg_errors++;
1449 fprintf(stderr,
1450 "Can't use both -D and -l options\n");
1453 if (max_invoke_ms > 0
1454 && cmd_time_out != NEVER
1455 && (cmd_time_out * 1000) <= max_invoke_ms) {
1456 arg_errors++;
1457 fprintf(stderr,
1458 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1461 if (show_list && arg_pid != -1) {
1462 arg_errors++;
1463 fprintf(stderr,
1464 "Can't use both --pid and -l options\n");
1467 if (int_port > 0 && last_command != -1) {
1468 arg_errors++;
1469 fprintf(stderr,
1470 "Can't use --port to send commands\n");
1473 if (arg_errors > 0) {
1474 fprintf(stderr, "args error. Try `vgdb --help` for more information\n");
1475 exit(1);
1478 *p_show_shared_mem = show_shared_mem;
1479 *p_show_list = show_list;
1480 *p_arg_pid = arg_pid;
1481 *p_check_trials = check_trials;
1482 *p_port = int_port;
1483 *p_last_command = last_command;
1486 int main(int argc, char** argv)
1488 int i;
1489 int pid;
1491 Bool show_shared_mem;
1492 Bool show_list;
1493 int arg_pid;
1494 int check_trials;
1495 int in_port;
1496 int last_command;
1497 char *commands[argc]; // we will never have more commands than args.
1499 parse_options(argc, argv,
1500 &show_shared_mem,
1501 &show_list,
1502 &arg_pid,
1503 &check_trials,
1504 &in_port,
1505 &last_command,
1506 commands);
1508 /* when we are working as a relay for gdb, handle some signals by
1509 only reporting them (according to debug level). Also handle these
1510 when ptrace will be used: vgdb must clean up the ptrace effect before
1511 dying. */
1512 if (max_invoke_ms > 0 || last_command == -1)
1513 install_handlers();
1515 pid = search_arg_pid(arg_pid, check_trials, show_list);
1517 prepare_fifos_and_shared_mem(pid);
1519 if (in_port > 0)
1520 wait_for_gdb_connect(in_port);
1522 if (show_shared_mem) {
1523 fprintf(stderr,
1524 "vgdb %d "
1525 "written_by_vgdb %d "
1526 "seen_by_valgrind %d\n"
1527 "vgdb pid %d\n",
1528 VS_vgdb_pid,
1529 VS_written_by_vgdb,
1530 VS_seen_by_valgrind,
1531 VS_vgdb_pid);
1532 exit(0);
1535 if (last_command >= 0) {
1536 standalone_send_commands(pid, last_command, commands);
1537 } else {
1538 gdb_relay(pid);
1542 free(from_gdb_to_pid);
1543 free(to_gdb_from_pid);
1544 free(shared_mem);
1546 for (i = 0; i <= last_command; i++)
1547 free(commands[i]);
1548 return 0;