Bug 439685 compiler warning in callgrind/main.c
[valgrind.git] / coregrind / vgdb.c
blob7ed9a8b2e902a2d8a4b2a2bb85f81e7b7f275649
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 /* For accept4. */
28 #define _GNU_SOURCE
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>
50 #include <sys/wait.h>
52 /* vgdb has two usages:
53 1. relay application between gdb and the gdbserver embedded in valgrind.
54 2. standalone to send monitor commands to a running valgrind-ified process
56 It is made of a main program which reads arguments. If no
57 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
58 assumed.
60 As relay application, vgdb reads bytes from gdb on stdin and
61 writes these bytes to valgrind. Bytes read from valgrind are
62 written to gdb on stdout. Read/Write from/to valgrind is done
63 using FIFOs. There is one thread reading from stdin, writing to
64 valgrind on a FIFO. There is one thread reading from valgrind on a
65 FIFO, writing to gdb on stdout
67 As a standalone utility, vgdb builds command packets to write to valgrind,
68 sends it and reads the reply. The same two threads are used to write/read.
69 Once all the commands are sent and their replies received, vgdb will exit.
72 int debuglevel;
73 Bool timestamp = False;
74 char timestamp_out[20];
75 static char *vgdb_prefix = NULL;
76 static char *valgrind_path = NULL;
77 static char **vargs;
78 static char cvargs = 0;
80 char *timestamp_str (Bool produce)
82 static char out[50];
83 char *ptr;
84 struct timeval dbgtv;
85 struct tm *ts_tm;
87 if (produce) {
88 gettimeofday(&dbgtv, NULL);
89 ts_tm = localtime(&dbgtv.tv_sec);
90 ptr = out + strftime(out, sizeof(out), "%H:%M:%S", ts_tm);
91 sprintf(ptr, ".%6.6ld ", dbgtv.tv_usec);
92 } else {
93 out[0] = 0;
95 return out;
98 /* Will be set to True when any condition indicating we have to shutdown
99 is encountered. */
100 Bool shutting_down = False;
102 VgdbShared32 *shared32;
103 VgdbShared64 *shared64;
104 #define VS_written_by_vgdb (shared32 != NULL ? \
105 shared32->written_by_vgdb \
106 : shared64->written_by_vgdb)
107 #define VS_seen_by_valgrind (shared32 != NULL ? \
108 shared32->seen_by_valgrind \
109 : shared64->seen_by_valgrind)
111 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
113 void *vmalloc(size_t size)
115 void * mem = malloc(size);
116 if (mem == NULL)
117 XERROR(errno, "can't allocate memory\n");
118 return mem;
121 void *vrealloc(void *ptr,size_t size)
123 void * mem = realloc(ptr, size);
124 if (mem == NULL)
125 XERROR(errno, "can't reallocate memory\n");
126 return mem;
129 /* Return the name of a directory for temporary files. */
130 static
131 const char *vgdb_tmpdir(void)
133 const char *tmpdir;
135 tmpdir = getenv("TMPDIR");
136 if (tmpdir == NULL || *tmpdir == '\0')
137 tmpdir = VG_TMPDIR;
138 if (tmpdir == NULL || *tmpdir == '\0')
139 tmpdir = "/tmp"; /* fallback */
141 return tmpdir;
144 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
145 to communicate with valgrind */
146 static
147 char *vgdb_prefix_default(void)
149 static HChar *prefix;
151 if (prefix == NULL) {
152 const char *tmpdir = vgdb_tmpdir();
153 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
154 strcpy(prefix, tmpdir);
155 strcat(prefix, "/vgdb-pipe");
157 return prefix;
160 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
161 static
162 void add_written(int nrw)
164 if (shared32 != NULL)
165 shared32->written_by_vgdb += nrw;
166 else if (shared64 != NULL)
167 shared64->written_by_vgdb += nrw;
168 else
169 assert(0);
172 static int shared_mem_fd = -1;
173 static
174 void map_vgdbshared(char* shared_mem)
176 struct stat fdstat;
177 void **s;
178 int tries = 50;
179 int err;
181 /* valgrind might still be starting up, give it 5 seconds. */
182 do {
183 shared_mem_fd = open(shared_mem, O_RDWR | O_CLOEXEC);
184 err = errno;
185 if (shared_mem_fd == -1 && err == ENOENT && tries > 0)
186 usleep (100000); /* wait 0.1 seconds */
187 } while (shared_mem_fd == -1 && err == ENOENT && tries-- > 0);
189 /* shared_mem_fd will not be closed till vgdb exits. */
191 if (shared_mem_fd == -1)
192 XERROR(errno, "error opening %s shared memory file\n", shared_mem);
194 if (fstat(shared_mem_fd, &fdstat) != 0)
195 XERROR(errno, "fstat\n");
197 if (fdstat.st_size == sizeof(VgdbShared64))
198 s = (void*) &shared64;
199 else if (fdstat.st_size == sizeof(VgdbShared32))
200 s = (void*) &shared32;
201 else
202 #if VEX_HOST_WORDSIZE == 8
203 XERROR(0,
204 "error size shared memory file %s.\n"
205 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
206 shared_mem,
207 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
208 (long int)fdstat.st_size);
209 #elif VEX_HOST_WORDSIZE == 4
210 XERROR(0,
211 "error size shared memory file %s.\n"
212 "expecting size %d (32bits) got %ld.\n",
213 shared_mem,
214 (int) sizeof(VgdbShared32),
215 fdstat.st_size);
216 #else
217 # error "unexpected wordsize"
218 #endif
220 #if VEX_HOST_WORDSIZE == 4
221 if (shared64 != NULL)
222 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
223 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
224 #endif
226 *s = (void*) mmap(NULL, fdstat.st_size,
227 PROT_READ|PROT_WRITE, MAP_SHARED,
228 shared_mem_fd, 0);
230 if (*s == (void *) -1)
231 XERROR(errno, "error mmap shared memory file %s\n", shared_mem);
235 /* This function loops till shutting_down becomes true. In this loop,
236 it verifies if valgrind process is reading the characters written
237 by vgdb. The verification is done every max_invoke_ms ms. If
238 valgrind is not reading characters, it will use invoker_invoke_gdbserver
239 to ensure that the gdbserver code is called soon by valgrind. */
240 static int max_invoke_ms = 100;
241 #define NEVER 99999999
242 static int cmd_time_out = NEVER;
243 static
244 void *invoke_gdbserver_in_valgrind(void *v_pid)
246 struct timeval cmd_max_end_time;
247 Bool cmd_started = False;
248 struct timeval invoke_time;
250 int pid = *(int *)v_pid;
251 int written_by_vgdb_before_sleep;
252 int seen_by_valgrind_before_sleep;
254 int invoked_written = -1;
255 unsigned int usecs;
257 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
259 while (!shutting_down) {
260 written_by_vgdb_before_sleep = VS_written_by_vgdb;
261 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
262 DEBUG(3,
263 "written_by_vgdb_before_sleep %d "
264 "seen_by_valgrind_before_sleep %d\n",
265 written_by_vgdb_before_sleep,
266 seen_by_valgrind_before_sleep);
267 if (cmd_time_out != NEVER
268 && !cmd_started
269 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
270 /* A command was started. Record the time at which it was started. */
271 DEBUG(1, "IO for command started\n");
272 gettimeofday(&cmd_max_end_time, NULL);
273 cmd_max_end_time.tv_sec += cmd_time_out;
274 cmd_started = True;
276 if (max_invoke_ms > 0) {
277 usecs = 1000 * max_invoke_ms;
278 gettimeofday(&invoke_time, NULL);
279 invoke_time.tv_sec += max_invoke_ms / 1000;
280 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
281 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
282 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
283 } else {
284 usecs = 0;
286 if (cmd_started) {
287 // 0 usecs here means the thread just has to check gdbserver eats
288 // the characters in <= cmd_time_out seconds.
289 // We will just wait by 1 second max at a time.
290 if (usecs == 0 || usecs > 1000 * 1000)
291 usecs = 1000 * 1000;
293 usleep(usecs);
295 /* If nothing happened during our sleep, let's try to wake up valgrind
296 or check for cmd time out. */
297 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
298 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
299 && VS_written_by_vgdb > VS_seen_by_valgrind) {
300 struct timeval now;
301 gettimeofday(&now, NULL);
302 DEBUG(2,
303 "after sleep "
304 "written_by_vgdb %d "
305 "seen_by_valgrind %d "
306 "invoked_written %d\n",
307 VS_written_by_vgdb,
308 VS_seen_by_valgrind,
309 invoked_written);
310 /* if the pid does not exist anymore, we better stop */
311 if (kill(pid, 0) != 0)
312 XERROR(errno,
313 "invoke_gdbserver_in_valgrind: "
314 "check for pid %d existence failed\n", pid);
315 if (cmd_started) {
316 if (timercmp(&now, &cmd_max_end_time, >))
317 XERROR(0,
318 "pid %d did not handle a command in %d seconds\n",
319 pid, cmd_time_out);
321 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
322 /* only need to wake up if the nr written has changed since
323 last invoke. */
324 if (invoked_written != written_by_vgdb_before_sleep) {
325 if (invoker_invoke_gdbserver(pid)) {
326 /* If invoke successful, no need to invoke again
327 for the same value of written_by_vgdb_before_sleep. */
328 invoked_written = written_by_vgdb_before_sleep;
332 } else {
333 // Something happened => restart timer check.
334 if (cmd_time_out != NEVER) {
335 DEBUG(2, "some IO was done => restart command\n");
336 cmd_started = False;
340 pthread_cleanup_pop(0);
341 return NULL;
344 static
345 int open_fifo(const char* name, int flags, const char* desc)
347 int fd;
348 DEBUG(1, "opening %s %s\n", name, desc);
349 fd = open(name, flags | O_CLOEXEC);
350 if (fd == -1)
351 XERROR(errno, "error opening %s %s\n", name, desc);
353 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
354 return fd;
357 /* acquire a lock on the first byte of the given fd. If not successful,
358 exits with error.
359 This allows to avoid having two vgdb speaking with the same Valgrind
360 gdbserver as this causes serious headaches to the protocol. */
361 static
362 void acquire_lock(int fd, int valgrind_pid)
364 struct flock fl;
365 fl.l_type = F_WRLCK;
366 fl.l_whence = SEEK_SET;
367 fl.l_start = 0;
368 fl.l_len = 1;
369 if (fcntl(fd, F_SETLK, &fl) < 0) {
370 if (errno == EAGAIN || errno == EACCES) {
371 XERROR(errno,
372 "Cannot acquire lock.\n"
373 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
374 VS_vgdb_pid,
375 valgrind_pid);
376 } else {
377 XERROR(errno, "cannot acquire lock.\n");
381 /* Here, we have the lock. It will be released when fd will be closed. */
382 /* We indicate our pid to Valgrind gdbserver */
383 if (shared32 != NULL)
384 shared32->vgdb_pid = getpid();
385 else if (shared64 != NULL)
386 shared64->vgdb_pid = getpid();
387 else
388 assert(0);
391 #define PBUFSIZ 16384 /* keep in sync with server.h */
393 /* read some characters from fd.
394 Returns the nr of characters read, -1 if error.
395 desc is a string used in tracing */
396 static
397 int read_buf(int fd, char* buf, const char* desc)
399 int nrread;
400 DEBUG(2, "reading %s\n", desc);
401 nrread = read(fd, buf, PBUFSIZ);
402 if (nrread == -1) {
403 ERROR(errno, "error reading %s\n", desc);
404 return -1;
406 buf[nrread] = '\0';
407 DEBUG(2, "read %s %s\n", desc, buf);
408 return nrread;
411 /* write size bytes from buf to fd.
412 desc is a description of the action for which the write is done.
413 If notify, then add size to the shared cntr indicating to the
414 valgrind process that there is new data.
415 Returns True if write is ok, False if there was a problem. */
416 static
417 Bool write_buf(int fd, const char* buf, int size, const char* desc, Bool notify)
419 int nrwritten;
420 int nrw;
421 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
422 size, buf, notify);
423 nrwritten = 0;
424 while (nrwritten < size) {
425 nrw = write(fd, buf+nrwritten, size - nrwritten);
426 if (nrw == -1) {
427 ERROR(errno, "error write %s\n", desc);
428 return False;
430 nrwritten = nrwritten + nrw;
431 if (notify)
432 add_written(nrw);
434 return True;
437 typedef enum {
438 FROM_GDB,
439 TO_GDB,
440 FROM_PID,
441 TO_PID } ConnectionKind;
442 static const int NumConnectionKind = TO_PID+1;
443 static
444 const char *ppConnectionKind(ConnectionKind con)
446 switch (con) {
447 case FROM_GDB: return "FROM_GDB";
448 case TO_GDB: return "TO_GDB";
449 case FROM_PID: return "FROM_PID";
450 case TO_PID: return "TO_PID";
451 default: return "invalid connection kind";
455 static char *shared_mem;
457 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
458 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
460 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
461 static char *to_gdb_from_pid; /* fifo name to read pid replies */
463 /* Returns True in case read/write operations were done properly.
464 Returns False in case of error.
465 to_pid is the file descriptor to write to the process pid. */
466 static
467 Bool read_from_gdb_write_to_pid(int to_pid)
469 char buf[PBUFSIZ+1]; // +1 for trailing \0
470 int nrread;
471 Bool ret;
473 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
474 if (nrread <= 0) {
475 if (nrread == 0)
476 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
477 else
478 DEBUG(1, "error reading bytes from gdb\n");
479 close(from_gdb);
480 shutting_down = True;
481 return False;
483 ret = write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
484 if (!ret) {
485 /* Let gdb know the packet couldn't be delivered. */
486 write_buf(to_gdb, "$E01#a6", 8, "error back to gdb", False);
488 return ret;
491 /* Returns True in case read/write operations were done properly.
492 Returns False in case of error.
493 from_pid is the file descriptor to read data from the process pid. */
494 static
495 Bool read_from_pid_write_to_gdb(int from_pid)
497 char buf[PBUFSIZ+1]; // +1 for trailing \0
498 int nrread;
500 nrread = read_buf(from_pid, buf, "from pid");
501 if (nrread <= 0) {
502 if (nrread == 0)
503 DEBUG(1, "read 0 bytes from pid => assume exit\n");
504 else
505 DEBUG(1, "error reading bytes from pid\n");
506 close(from_pid);
507 shutting_down = True;
508 return False;
510 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
513 static
514 void wait_for_gdb_connect(int in_port)
516 struct sockaddr_in addr;
518 #ifdef SOCK_CLOEXEC
519 int listen_gdb = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
520 #else
521 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
522 #endif
524 int gdb_connect;
526 if (-1 == listen_gdb) {
527 XERROR(errno, "cannot create socket\n");
530 /* allow address reuse to avoid "address already in use" errors */
532 int one = 1;
533 if (setsockopt(listen_gdb, SOL_SOCKET, SO_REUSEADDR,
534 &one, sizeof(one)) < 0) {
535 XERROR(errno, "cannot enable address reuse\n");
538 memset(&addr, 0, sizeof(addr));
540 addr.sin_family = AF_INET;
541 addr.sin_port = htons((unsigned short int)in_port);
542 addr.sin_addr.s_addr = INADDR_ANY;
544 if (-1 == bind(listen_gdb, (struct sockaddr *)&addr, sizeof(addr))) {
545 XERROR(errno, "bind failed\n");
547 TSFPRINTF(stderr, "listening on port %d ...", in_port);
548 if (-1 == listen(listen_gdb, 1)) {
549 XERROR(errno, "error listen failed\n");
552 #ifdef SOCK_CLOEXEC
553 gdb_connect = accept4(listen_gdb, NULL, NULL, SOCK_CLOEXEC);
554 #else
555 gdb_connect = accept(listen_gdb, NULL, NULL);
556 #endif
558 if (gdb_connect < 0) {
559 XERROR(errno, "accept failed\n");
561 fprintf(stderr, "connected.\n");
562 fflush(stderr);
563 close(listen_gdb);
564 from_gdb = gdb_connect;
565 to_gdb = gdb_connect;
568 /* prepares the FIFOs filenames, map the shared memory. */
569 static
570 void prepare_fifos_and_shared_mem(int pid)
572 const HChar *user, *host;
573 unsigned len;
575 user = getenv("LOGNAME");
576 if (user == NULL) user = getenv("USER");
577 if (user == NULL) user = "???";
578 if (strchr(user, '/')) user = "???";
580 host = getenv("HOST");
581 if (host == NULL) host = getenv("HOSTNAME");
582 if (host == NULL) host = "???";
583 if (strchr(host, '/')) host = "???";
585 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
586 from_gdb_to_pid = vmalloc(len);
587 to_gdb_from_pid = vmalloc(len);
588 shared_mem = vmalloc(len);
589 /* below 3 lines must match the equivalent in remote-utils.c */
590 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
591 pid, user, host);
592 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
593 pid, user, host);
594 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
595 pid, user, host);
596 DEBUG(1, "vgdb: using %s %s %s\n",
597 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
599 map_vgdbshared(shared_mem);
602 static void
603 cleanup_fifos_and_shared_mem(void)
605 free(from_gdb_to_pid);
606 free(to_gdb_from_pid);
607 free(shared_mem);
608 close(shared_mem_fd);
611 /* Convert hex digit A to a number. */
613 static int
614 fromhex(int a)
616 if (a >= '0' && a <= '9')
617 return a - '0';
618 else if (a >= 'a' && a <= 'f')
619 return a - 'a' + 10;
620 else
621 XERROR(0, "Reply contains invalid hex digit %c\n", a);
622 return 0;
625 /* Returns next char from fd. -1 if error, -2 if EOF.
626 NB: must always call it with the same fd */
627 static int
628 readchar(int fd)
630 static char buf[PBUFSIZ+1]; // +1 for trailing \0
631 static int bufcnt = 0;
632 static unsigned char *bufp;
633 // unsigned bufp to e.g. avoid having 255 converted to int -1
635 if (bufcnt-- > 0)
636 return *bufp++;
638 bufcnt = read_buf(fd, buf, "static buf readchar");
640 if (bufcnt <= 0) {
641 if (bufcnt == 0) {
642 TSFPRINTF(stderr, "readchar: Got EOF\n");
643 return -2;
644 } else {
645 ERROR(errno, "readchar\n");
646 return -1;
650 bufp = (unsigned char *)buf;
651 bufcnt--;
652 return *bufp++;
655 /* Read a packet from fromfd, with error checking,
656 and store it in BUF.
657 If checksum incorrect, writes a - on ackfd.
658 Returns length of packet, or -1 if error or -2 if EOF. */
659 static int
660 getpkt(char *buf, int fromfd, int ackfd)
662 char *bp;
663 unsigned char csum, c1, c2;
664 int c;
666 while (1) {
667 csum = 0;
669 while (1) {
670 c = readchar(fromfd);
671 if (c == '$')
672 break;
673 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
674 if (c < 0)
675 return c;
678 bp = buf;
679 while (1) {
680 c = readchar(fromfd);
681 if (c < 0)
682 return c;
683 if (c == '#')
684 break;
685 if (c == '*') {
686 int repeat;
687 int r;
688 int prev;
689 prev = *(bp-1);
690 csum += c;
691 repeat = readchar(fromfd);
692 csum += repeat;
693 for (r = 0; r < repeat - 29; r ++)
694 *bp++ = prev;
695 } else {
696 *bp++ = c;
697 csum += c;
700 *bp = 0;
702 c1 = fromhex(readchar (fromfd));
703 c2 = fromhex(readchar (fromfd));
705 if (csum == (c1 << 4) + c2)
706 break;
708 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
709 (c1 << 4) + c2, csum, buf);
710 if (write(ackfd, "-", 1) != 1)
711 ERROR(0, "error when writing - (nack)\n");
712 else
713 add_written(1);
716 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
717 return bp - buf;
720 static int sigint = 0;
721 static int sigterm = 0;
722 static int sigpipe = 0;
723 static int sighup = 0;
724 static int sigusr1 = 0;
725 static int sigalrm = 0;
726 static int sigusr1_fd = -1;
727 static pthread_t invoke_gdbserver_in_valgrind_thread;
729 static
730 void received_signal(int signum)
732 if (signum == SIGINT)
733 sigint++;
734 else if (signum == SIGUSR1) {
735 sigusr1++;
736 if (sigusr1_fd >= 0) {
737 char control_c = '\003';
738 write_buf(sigusr1_fd, &control_c, 1,
739 "write \\003 on SIGUSR1", /* notify */ True);
742 else if (signum == SIGTERM) {
743 shutting_down = True;
744 sigterm++;
745 } else if (signum == SIGHUP) {
746 shutting_down = True;
747 sighup++;
748 } else if (signum == SIGPIPE) {
749 sigpipe++;
750 } else if (signum == SIGALRM) {
751 sigalrm++;
752 #if defined(VGPV_arm_linux_android) \
753 || defined(VGPV_x86_linux_android) \
754 || defined(VGPV_mips32_linux_android) \
755 || defined(VGPV_arm64_linux_android)
756 /* Android has no pthread_cancel. As it also does not have
757 an invoker implementation, there is no need for cleanup action.
758 So, we just do nothing. */
759 DEBUG(1, "sigalrm received, no action on android\n");
760 #else
761 /* Note: we cannot directly invoke restore_and_detach : this must
762 be done by the thread that has attached.
763 We have in this thread pushed a cleanup handler that will
764 cleanup what is needed. */
765 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
766 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
767 #endif
768 } else {
769 ERROR(0, "unexpected signal %d\n", signum);
773 /* install the signal handlers allowing e.g. vgdb to cleanup in
774 case of termination. */
775 static
776 void install_handlers(void)
778 struct sigaction action, oldaction;
780 action.sa_handler = received_signal;
781 sigemptyset(&action.sa_mask);
782 action.sa_flags = 0;
784 /* SIGINT: when user types C-c in gdb, this sends
785 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
786 The later is enough to wakeup the valgrind process. */
787 if (sigaction(SIGINT, &action, &oldaction) != 0)
788 XERROR(errno, "vgdb error sigaction SIGINT\n");
789 /* We might do something more intelligent than just
790 reporting this SIGINT E.g. behave similarly to the gdb: two
791 control-C without feedback from the debugged process would
792 mean to stop debugging it. */
794 /* SIGUSR1: this is used to facilitate automatic testing. When
795 vgdb receives this signal, it will simulate the user typing C-c. */
796 if (sigaction(SIGUSR1, &action, &oldaction) != 0)
797 XERROR(errno, "vgdb error sigaction SIGUSR1\n");
800 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
801 when detaching or similar. A clean shutdown will be done as both
802 the read and write side will detect an end of file. */
803 if (sigaction(SIGTERM, &action, &oldaction) != 0)
804 XERROR(errno, "vgdb error sigaction SIGTERM\n");
806 /* SIGPIPE: can receive this signal when gdb detaches or kill the
807 process debugged: gdb will close its pipes to vgdb. vgdb
808 must resist to this signal to allow a clean shutdown. */
809 if (sigaction(SIGPIPE, &action, &oldaction) != 0)
810 XERROR(errno, "vgdb error sigaction SIGPIPE\n");
812 /* SIGALRM: in case invoke thread is blocked, alarm is used
813 to cleanup. */
814 if (sigaction(SIGALRM, &action, &oldaction) != 0)
815 XERROR(errno, "vgdb error sigaction SIGALRM\n");
817 /* unmask all signals, in case the process that launched vgdb
818 masked some. */
819 if (sigprocmask(SIG_SETMASK, &action.sa_mask, NULL) != 0)
820 XERROR(errno, "vgdb error sigprocmask\n");
823 /* close the FIFOs provided connections, terminate the invoker thread. */
824 static
825 void close_connection(int to_pid, int from_pid)
827 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
828 sigint, sigterm, sighup, sigpipe);
829 /* Note that we do not forward sigterm to the valgrind process:
830 a sigterm signal is (probably) received from gdb if the user wants to
831 kill the debugged process. The kill instruction has been given to
832 the valgrind process, which should execute a clean exit. */
834 /* We first close the connection to pid. The pid will then
835 terminates its gdbserver work. We keep the from pid
836 fifo opened till the invoker thread is finished.
837 This allows the gdbserver to finish sending its last reply. */
838 if (close(to_pid) != 0)
839 ERROR(errno, "close to_pid\n");
841 /* if there is a task that was busy trying to wake up valgrind
842 process, we wait for it to be terminated otherwise threads
843 in the valgrind process can stay stopped if vgdb main
844 exits before the invoke thread had time to detach from
845 all valgrind threads. */
846 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
847 int join;
849 /* It is surprisingly complex to properly shutdown or exit the
850 valgrind process in which gdbserver has been invoked through
851 ptrace. In the normal case (gdb detaches from the process,
852 or process is continued), the valgrind process will reach the
853 breakpoint place. Using ptrace, vgdb will ensure the
854 previous activity of the process is resumed (e.g. restart a
855 blocking system call). The special case is when gdb asks the
856 valgrind process to exit (using either the "kill" command or
857 "monitor exit"). In such a case, the valgrind process will
858 call exit. But a ptraced process will be blocked in exit,
859 waiting for the ptracing process to detach or die. vgdb
860 cannot detach unconditionally as otherwise, in the normal
861 case, the valgrind process would stop abnormally with SIGSTOP
862 (as vgdb would not be there to catch it). vgdb can also not
863 die unconditionally otherwise again, similar problem. So, we
864 assume that most of the time, we arrive here in the normal
865 case, and so, the breakpoint has been encountered by the
866 valgrind process, so the invoker thread will exit and the
867 join will succeed. For the "kill" case, we cause an alarm
868 signal to be sent after a few seconds. This means that in the
869 normal case, the gdbserver code in valgrind process must have
870 returned the control in less than the alarm nr of seconds,
871 otherwise, valgrind will stop abnormally with SIGSTOP. */
872 (void) alarm(3);
874 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
875 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
876 if (join != 0)
877 XERROR
878 (join,
879 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
881 #if !defined(VGO_freebsd)
882 if (close(from_pid) != 0)
883 ERROR(errno, "close from_pid\n");
884 #endif
887 static
888 int tohex (int nib)
890 if (nib < 10)
891 return '0' + nib;
892 else
893 return 'a' + nib - 10;
896 /* Returns an allocated hex-decoded string from the buf starting at offset
897 off. Will update off to where the buf has been decoded. Stops decoding
898 at end of buf (zero) or when seeing the delim char. */
899 static
900 char *decode_hexstring (const char *buf, size_t prefixlen, size_t len)
902 int buflen;
903 char *buf_print;
905 if (len)
906 buflen = len;
907 else
908 buflen = strlen(buf) - prefixlen;
910 buf_print = vmalloc (buflen/2 + 1);
912 for (int i = 0; i < buflen; i = i + 2) {
913 buf_print[i/2] = ((fromhex(buf[i+prefixlen]) << 4)
914 + fromhex(buf[i+prefixlen+1]));
916 buf_print[buflen/2] = '\0';
917 DEBUG(1, "decode_hexstring: %s\n", buf_print);
918 return buf_print;
921 static Bool
922 write_to_gdb (const char *m, int cnt)
924 int written = 0;
925 while (written < cnt) {
926 int res = write (to_gdb, m + written, cnt - written);
927 if (res < 0) {
928 perror ("write_to_gdb");
929 return False;
931 written += res;
934 return True;
937 static Bool
938 write_checksum (const char *str)
940 unsigned char csum = 0;
941 int i = 0;
942 while (str[i] != 0)
943 csum += str[i++];
945 char p[2];
946 p[0] = tohex ((csum >> 4) & 0x0f);
947 p[1] = tohex (csum & 0x0f);
948 return write_to_gdb (p, 2);
951 static Bool
952 write_reply(const char *reply)
954 write_to_gdb ("$", 1);
955 write_to_gdb (reply, strlen (reply));
956 write_to_gdb ("#", 1);
957 return write_checksum (reply);
960 /* Creates a packet from a string message, called needs to free. */
961 static char *
962 create_packet(const char *msg)
964 unsigned char csum = 0;
965 int i = 1;
966 char *p = vmalloc (strlen (msg) + 5); /* $ + msg + # + hexhex + 0 */
967 strcpy (&p[1], msg);
968 p[0] = '$';
969 while (p[i] != 0)
970 csum += p[i++];
971 p[i++] = '#';
972 p[i++] = tohex ((csum >> 4) & 0x0f);
973 p[i++] = tohex (csum & 0x0f);
974 p[i] = '\0';
975 return p;
978 static int read_one_char (char *c)
980 int i;
982 i = read (from_gdb, c, 1);
983 while (i == -1 && errno == EINTR);
985 return i;
988 static Bool
989 send_packet(const char *reply, int noackmode)
991 int ret;
992 char c;
994 send_packet_start:
995 if (!write_reply(reply))
996 return False;
997 if (!noackmode) {
998 // Look for '+' or '-'.
999 // We must wait for "+" if !noackmode.
1000 do {
1001 ret = read_one_char(&c);
1002 if (ret <= 0)
1003 return False;
1004 // And if in !noackmode if we get "-" we should resent the packet.
1005 if (c == '-')
1006 goto send_packet_start;
1007 } while (c != '+');
1008 DEBUG(1, "sent packet to gdb got: %c\n",c);
1010 return True;
1013 // Reads one packet from_gdb starting with $ into buf.
1014 // Skipping any other characters.
1015 // Returns the size of the packet, 0 for end of input,
1016 // or -1 if no packet could be read.
1017 static int receive_packet(char *buf, int noackmode)
1019 int bufcnt = 0, ret;
1020 char c, c1, c2;
1021 unsigned char csum = 0;
1023 // Look for first '$' (start of packet) or error.
1024 receive_packet_start:
1025 do {
1026 ret = read_one_char(&c);
1027 if (ret <= 0)
1028 return ret;
1029 } while (c != '$');
1031 // Found start of packet ('$')
1032 while (bufcnt < (PBUFSIZ+1)) {
1033 ret = read_one_char(&c);
1034 if (ret <= 0)
1035 return ret;
1036 if (c == '#') {
1037 if ((ret = read_one_char(&c1)) <= 0
1038 || (ret = read_one_char(&c2)) <= 0) {
1039 return ret;
1041 c1 = fromhex(c1);
1042 c2 = fromhex(c2);
1043 break;
1045 buf[bufcnt] = c;
1046 csum += buf[bufcnt];
1047 bufcnt++;
1050 // Packet complete, add terminator.
1051 buf[bufcnt] ='\0';
1053 if (!(csum == (c1 << 4) + c2)) {
1054 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1055 (c1 << 4) + c2, csum, buf);
1056 if (!noackmode)
1057 if (!write_to_gdb ("-", 1))
1058 return -1;
1059 /* Try again, gdb should resend the packet. */
1060 bufcnt = 0;
1061 csum = 0;
1062 goto receive_packet_start;
1065 if (!noackmode)
1066 if (!write_to_gdb ("+", 1))
1067 return -1;
1068 return bufcnt;
1071 // Returns a pointer to the char after the next delim char.
1072 static const char *next_delim_string (const char *buf, char delim)
1074 while (*buf) {
1075 if (*buf++ == delim)
1076 break;
1078 return buf;
1081 // Throws away the packet name and decodes the hex string, which is placed in
1082 // decoded_string (the caller owns this and is responsible for freeing it).
1083 static int split_hexdecode(const char *buf, const char *string,
1084 const char *delim, char **decoded_string)
1086 const char *next_str = next_delim_string(buf, *delim);
1087 if (next_str) {
1088 *decoded_string = decode_hexstring (next_str, 0, 0);
1089 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string);
1090 return 1;
1091 } else {
1092 TSFPRINTF(stderr, "%s decoding error: finding the hex string in %s failed!\n", string, buf);
1093 return 0;
1097 static int count_delims(char delim, char *buf)
1099 size_t count = 0;
1100 char *ptr = buf;
1102 while (*ptr)
1103 count += *ptr++ == delim;
1104 return count;
1107 // Determine the length of the arguments.
1108 // This depends on the len array being initialized to -1 for each element.
1109 // We first skip the command (e.g. vRun;arg0;arg1)
1110 static void count_len(char delim, char *buf, size_t *len)
1112 int i = 0;
1113 char *ptr = buf;
1115 // Skip the command
1116 while (*ptr && *ptr != delim)
1117 ptr++;
1119 // Delimiter counts towards the first arg0
1120 if (*ptr == delim) {
1121 ptr++;
1122 len[i]++;
1125 // For each arg0... count chars (delim counts towards next arg)
1126 while (*ptr) {
1127 i += *ptr++ == delim;
1128 len[i]++;
1132 /* Declare here, will be used early, implementation follows later. */
1133 static void gdb_relay(int pid, int send_noack_mode, char *q_buf);
1135 /* Returns zero on success (and the pid of the valgrind process),
1136 or the errno from the child on failure. */
1137 static
1138 int fork_and_exec_valgrind (int argc, char **argv, const char *working_dir,
1139 pid_t *pid)
1141 int err = 0;
1142 // We will use a pipe to track what the child does,
1143 // so we can report failure.
1144 int pipefd[2];
1145 #ifdef HAVE_PIPE2
1146 if (pipe2 (pipefd, O_CLOEXEC) == -1) {
1147 err = errno;
1148 perror ("pipe2 failed");
1149 return err;
1151 #else
1152 if (pipe (pipefd) == -1) {
1153 err = errno;
1154 perror ("pipe failed");
1155 return err;
1156 } else {
1157 if (fcntl (pipefd[0], F_SETFD, FD_CLOEXEC) == -1
1158 || fcntl (pipefd[1], F_SETFD, FD_CLOEXEC) == -1) {
1159 err = errno;
1160 perror ("fcntl failed");
1161 close (pipefd[0]);
1162 close (pipefd[1]);
1163 return err;
1166 #endif
1168 pid_t p = fork ();
1169 if (p < 0) {
1170 err = errno;
1171 perror ("fork failed");
1172 return err;
1173 } else if (p > 0) {
1174 // I am the parent (vgdb), p is the pid of the child (valgrind)
1175 // We only read from the child to see if everything is OK.
1176 // If the pipe closes, we get zero back, which is good.
1177 // An error reading the pipe is bad (and really shouldn't happen).
1178 // Otherwise the child sent us an errno code about what went wrong.
1179 close (pipefd[1]);
1181 while (err == 0) {
1182 int r = read (pipefd[0], &err, sizeof (int));
1183 if (r == 0) // end of file, good pipe closed after execve
1184 break;
1185 if (r == -1) {
1186 if (errno == EINTR)
1187 continue;
1188 else {
1189 err = errno;
1190 perror ("pipe read");
1195 close (pipefd[0]);
1196 if (err != 0)
1197 return err;
1198 else {
1199 *pid = p;
1200 return 0;
1202 } else {
1203 // p == 0, I am the child (will start valgrind)
1204 // We write success to the pipe, no need to read from it.
1205 close (pipefd[0]);
1207 if (working_dir != NULL && working_dir[0] != '\0') {
1208 if (chdir (working_dir) != 0) {
1209 err = errno;
1210 perror("chdir");
1211 write (pipefd[1], &err, sizeof (int));
1212 _exit (-1);
1216 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1217 can attach and --launched-with-multi to let valgrind know it doesn't
1218 need to show a banner how to connect to gdb, we will do that
1219 automagically. And add --vgdb-shadow-registers=yes to make shadow
1220 registers available by default. Add any other valgrind arguments the
1221 user gave with --vargs. Then the rest of the arguments to valgrind are
1222 the program to exec plus its arguments. */
1223 const int extra_vargs = 3;
1224 /* vargv[0] == "valgrind",
1225 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1226 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1227 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1228 vargs[arguments - 1] = NULL */
1229 int arguments = 1 + extra_vargs + cvargs + argc + 1;
1230 // We combine const and non-const char[]. This is mildly annoying
1231 // since we then need a char *const * for execvp. So we strdup the
1232 // const char*. Not pretty :{
1233 char **vargv = vmalloc (arguments * sizeof (char *));
1234 vargv[0] = strdup ("valgrind");
1235 vargv[1] = strdup ("--vgdb-error=0");
1236 vargv[2] = strdup ("--launched-with-multi=yes");
1237 vargv[3] = strdup ("--vgdb-shadow-registers=yes");
1238 // Add --vargs
1239 for (int i = 0; i < cvargs; i++) {
1240 vargv[i + extra_vargs + 1] = vargs[i];
1242 // Add command and args
1243 for (int i = 0; i < argc; i++) {
1244 vargv[i + extra_vargs + 1 + cvargs] = argv[i];
1246 vargv[arguments - 1] = NULL;
1248 if (!valgrind_path) {
1249 // TODO use execvpe (or something else if not on GNU/Linux
1250 /* We want to make a copy of the environ on start. When we
1251 get a QEnvironmentReset we copy that back. If we get an
1252 EvironSet/Add/Remove we update the copy. */
1253 execvp ("valgrind", vargv);
1255 else {
1256 vargv[0] = valgrind_path;
1257 execvp (vargv[0], vargv);
1260 // We really shouldn't get here...
1261 err = errno;
1262 /* Note we are after fork and exec failed, we cannot really call
1263 perror or printf in this situation since they aren't async-safe. */
1264 // perror ("execvp valgrind");
1265 // printf ("execve returned??? confusing: %d\n", res);
1266 write (pipefd[1], &err, sizeof (int));
1267 _exit (-1);
1270 abort (); // Impossible
1273 /* Do multi stuff. */
1274 static
1275 void do_multi_mode(void)
1277 char *buf = vmalloc(PBUFSIZ+1);
1278 char *q_buf = vmalloc(PBUFSIZ+1); //save the qSupported packet sent by gdb
1279 //to send it to the valgrind gdbserver later
1280 q_buf[0] = '\0';
1281 int noackmode = 0, pkt_size = 0, bad_unknown_packets = 0;
1282 char *string = NULL;
1283 char *working_dir = NULL;
1284 DEBUG(1, "doing multi stuff...\n");
1285 while (1){
1286 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1287 the pipe to gdb. */
1288 pkt_size = receive_packet(buf, noackmode);
1289 if (pkt_size <= 0) {
1290 DEBUG(1, "receive_packet: %d\n", pkt_size);
1291 break;
1294 DEBUG(1, "packet recieved: '%s'\n", buf);
1296 #define QSUPPORTED "qSupported:"
1297 #define STARTNOACKMODE "QStartNoAckMode"
1298 #define QRCMD "qRcmd" // This is the monitor command in gdb
1299 #define VRUN "vRun"
1300 #define XFER "qXfer"
1301 #define QATTACHED "qAttached"
1302 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1303 #define QENVIRONMENTRESET "QEnvironmentReset"
1304 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1305 #define QSETWORKINGDIR "QSetWorkingDir"
1306 #define QTSTATUS "qTStatus"
1308 if (strncmp(QSUPPORTED, buf, strlen(QSUPPORTED)) == 0) {
1309 DEBUG(1, "CASE %s\n", QSUPPORTED);
1310 // And here is our reply.
1311 // XXX error handling? We don't check the arguments.
1312 char *reply;
1313 strcpy(q_buf, buf);
1314 // Keep this in sync with coregrind/m_gdbserver/server.c
1315 asprintf (&reply,
1316 "PacketSize=%x;"
1317 "QStartNoAckMode+;"
1318 "QPassSignals+;"
1319 "QCatchSyscalls+;"
1320 /* Just report support always. */
1321 "qXfer:auxv:read+;"
1322 /* We'll force --vgdb-shadow-registers=yes */
1323 "qXfer:features:read+;"
1324 "qXfer:exec-file:read+;"
1325 "qXfer:siginfo:read+;"
1326 /* Some extra's vgdb support before valgrind starts up. */
1327 "QEnvironmentHexEncoded+;"
1328 "QEnvironmentReset+;"
1329 "QEnvironmentUnset+;"
1330 "QSetWorkingDir+", (UInt)PBUFSIZ - 1);
1331 send_packet(reply, noackmode);
1332 free (reply);
1334 else if (strncmp(STARTNOACKMODE, buf, strlen(STARTNOACKMODE)) == 0) {
1335 // We have to ack this one
1336 send_packet("OK", 0);
1337 noackmode = 1;
1339 else if (buf[0] == '!') {
1340 send_packet("OK", noackmode);
1342 else if (buf[0] == '?') {
1343 send_packet("W00", noackmode);
1345 else if (strncmp("H", buf, strlen("H")) == 0) {
1346 // Set thread packet, but we are not running yet.
1347 send_packet("E01", noackmode);
1349 else if (strncmp("vMustReplyEmpty", buf, strlen("vMustReplyEmpty")) == 0) {
1350 send_packet ("", noackmode);
1352 else if (strncmp(QRCMD, buf, strlen(QRCMD)) == 0) {
1353 send_packet ("No running target, monitor commands not available yet.", noackmode);
1355 char *decoded_string = decode_hexstring (buf, strlen (QRCMD) + 1, 0);
1356 DEBUG(1, "qRcmd decoded: %s\n", decoded_string);
1357 free (decoded_string);
1359 else if (strncmp(VRUN, buf, strlen(VRUN)) == 0) {
1360 // vRun;filename[;argument]*
1361 // vRun, filename and arguments are split on ';',
1362 // no ';' at the end.
1363 // If there are no arguments count is one (just the filename).
1364 // Otherwise it is the number of arguments plus one (the filename).
1365 // The filename must be there and starts after the first ';'.
1366 // TODO: Handle vRun;[;argument]*
1367 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1368 // If filename is an empty string, the stub may use a default program
1369 // (e.g. the last program run).
1370 size_t count = count_delims(';', buf);
1371 size_t *len = vmalloc(count * sizeof(count));
1372 const char *delim = ";";
1373 const char *next_str = next_delim_string(buf, *delim);
1374 char **decoded_string = vmalloc(count * sizeof (char *));
1376 // Count the lenghts of each substring, init to -1 to compensate for
1377 // each substring starting with a delim char.
1378 for (int i = 0; i < count; i++)
1379 len[i] = -1;
1380 count_len(';', buf, len);
1381 if (next_str) {
1382 DEBUG(1, "vRun: next_str %s\n", next_str);
1383 for (int i = 0; i < count; i++) {
1384 /* Handle the case when the arguments
1385 * was specified to gdb's run command
1386 * but no remote exec-file was set,
1387 * so the first vRun argument is missing.
1388 * For example vRun;;6c. */
1389 if (*next_str == *delim) {
1390 next_str++;
1391 /* empty string that can be freed. */
1392 decoded_string[i] = strdup("");
1394 else {
1395 decoded_string[i] = decode_hexstring (next_str, 0, len[i]);
1396 if (i < count - 1)
1397 next_str = next_delim_string(next_str, *delim);
1399 DEBUG(1, "vRun decoded: %s, next_str %s, len[%d] %d\n", decoded_string[i], next_str, i, len[i]);
1402 /* If we didn't get any arguments or the filename is an empty
1403 string, valgrind won't know which program to run. */
1404 DEBUG (1, "count: %d, len[0]: %d\n", count, len[0]);
1405 if (! count || len[0] == 0) {
1406 free(len);
1407 for (int i = 0; i < count; i++)
1408 free (decoded_string[i]);
1409 free (decoded_string);
1410 send_packet ("E01", noackmode);
1411 continue;
1414 /* We have collected the decoded strings so we can use them to
1415 launch valgrind with the correct arguments... We then use the
1416 valgrind pid to start relaying packets. */
1417 pid_t valgrind_pid = -1;
1418 int res = fork_and_exec_valgrind (count,
1419 decoded_string,
1420 working_dir,
1421 &valgrind_pid);
1423 if (res == 0) {
1424 // Lets report we Stopped with SIGTRAP (05).
1425 send_packet ("S05", noackmode);
1426 prepare_fifos_and_shared_mem(valgrind_pid);
1427 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n", from_gdb_to_pid, to_gdb_from_pid);
1428 // gdb_rely is an endless loop till valgrind quits.
1429 shutting_down = False;
1431 gdb_relay (valgrind_pid, 1, q_buf);
1432 cleanup_fifos_and_shared_mem();
1433 DEBUG(1, "valgrind relay done\n");
1434 int status;
1435 pid_t p = waitpid (valgrind_pid, &status, 0);
1436 DEBUG(2, "waitpid: %d\n", (int) p);
1437 if (p == -1)
1438 DEBUG(1, "waitpid error %s\n", strerror (errno));
1439 else {
1440 if (WIFEXITED(status))
1441 DEBUG(1, "valgrind exited with %d\n",
1442 WEXITSTATUS(status));
1443 else if (WIFSIGNALED(status))
1444 DEBUG(1, "valgrind kill by signal %d\n",
1445 WTERMSIG(status));
1446 else
1447 DEBUG(1, "valgind unexpectedly stopped or continued");
1449 } else {
1450 send_packet ("E01", noackmode);
1451 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1452 strerror (res));
1455 free(len);
1456 for (int i = 0; i < count; i++)
1457 free (decoded_string[i]);
1458 free (decoded_string);
1459 } else {
1460 free(len);
1461 send_packet ("E01", noackmode);
1462 DEBUG(1, "vRun decoding error: no next_string!\n");
1463 continue;
1465 } else if (strncmp(QATTACHED, buf, strlen(QATTACHED)) == 0) {
1466 send_packet ("1", noackmode);
1467 DEBUG(1, "qAttached sent: '1'\n");
1468 const char *next_str = next_delim_string(buf, ':');
1469 if (next_str) {
1470 char *decoded_string = decode_hexstring (next_str, 0, 0);
1471 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string, next_str);
1472 free (decoded_string);
1473 } else {
1474 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf);
1475 continue;
1477 } /* Reset the state of environment variables in the remote target before starting
1478 the inferior. In this context, reset means unsetting all environment variables
1479 that were previously set by the user (i.e., were not initially present in the environment). */
1480 else if (strncmp(QENVIRONMENTRESET, buf,
1481 strlen(QENVIRONMENTRESET)) == 0) {
1482 send_packet ("OK", noackmode);
1483 // TODO clear all environment strings. We're not using
1484 // environment strings now. But we should.
1485 } else if (strncmp(QENVIRONMENTHEXENCODED, buf,
1486 strlen(QENVIRONMENTHEXENCODED)) == 0) {
1487 send_packet ("OK", noackmode);
1488 if (!split_hexdecode(buf, QENVIRONMENTHEXENCODED, ":", &string))
1489 break;
1490 // TODO Collect all environment strings and add them to environ
1491 // before launcing valgrind.
1492 free (string);
1493 string = NULL;
1494 } else if (strncmp(QENVIRONMENTUNSET, buf,
1495 strlen(QENVIRONMENTUNSET)) == 0) {
1496 send_packet ("OK", noackmode);
1497 if (!split_hexdecode(buf, QENVIRONMENTUNSET, ":", &string))
1498 break;
1499 // TODO Remove this environment string from the collection.
1500 free (string);
1501 string = NULL;
1502 } else if (strncmp(QSETWORKINGDIR, buf,
1503 strlen(QSETWORKINGDIR)) == 0) {
1504 // Silly, but we can only reply OK, even if the working directory is
1505 // bad. Errors will be reported when we try to execute the actual
1506 // process.
1507 send_packet ("OK", noackmode);
1508 // Free any previously set working_dir
1509 free (working_dir);
1510 working_dir = NULL;
1511 if (!split_hexdecode(buf, QSETWORKINGDIR, ":", &working_dir)) {
1512 continue; // We cannot report the error to gdb...
1514 DEBUG(1, "set working dir to: %s\n", working_dir);
1515 } else if (strncmp(XFER, buf, strlen(XFER)) == 0) {
1516 char *buf_dup = strdup(buf);
1517 DEBUG(1, "strdup: buf_dup %s\n", buf_dup);
1518 if (buf_dup) {
1519 const char *delim = ":";
1520 size_t count = count_delims(delim[0], buf);
1521 if (count < 4) {
1522 strsep(&buf_dup, delim);
1523 strsep(&buf_dup, delim);
1524 strsep(&buf_dup, delim);
1525 char *decoded_string = decode_hexstring (buf_dup, 0, 0);
1526 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string, buf_dup);
1527 free (decoded_string);
1529 free (buf_dup);
1530 } else {
1531 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf);
1532 free (buf_dup);
1533 continue;
1535 // Whether we could decode it or not, we cannot handle it now. We
1536 // need valgrind gdbserver to properly reply. So error out here.
1537 send_packet ("E00", noackmode);
1538 } else if (strncmp(QTSTATUS, buf, strlen(QTSTATUS)) == 0) {
1539 // We don't support trace experiments
1540 DEBUG(1, "Got QTSTATUS\n");
1541 send_packet ("", noackmode);
1542 } else if (strcmp("qfThreadInfo", buf) == 0) {
1543 DEBUG(1, "Got qfThreadInfo\n");
1544 /* There are no threads yet, reply 'l' end of list. */
1545 send_packet ("l", noackmode);
1546 } else if (buf[0] != '\0') {
1547 // We didn't understand.
1548 DEBUG(1, "Unknown packet received: '%s'\n", buf);
1549 bad_unknown_packets++;
1550 if (bad_unknown_packets > 10) {
1551 DEBUG(1, "Too many bad/unknown packets received\n");
1552 break;
1554 send_packet ("", noackmode);
1557 DEBUG(1, "done doing multi stuff...\n");
1558 free(working_dir);
1559 free(buf);
1560 free(q_buf);
1562 shutting_down = True;
1563 close (to_gdb);
1564 close (from_gdb);
1567 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1568 encountered. q_buf is the qSupported packet received from gdb. */
1569 static
1570 void gdb_relay(int pid, int send_noack_mode, char *q_buf)
1572 int from_pid = -1; /* fd to read from pid */
1573 int to_pid = -1; /* fd to write to pid */
1575 int shutdown_loop = 0;
1576 TSFPRINTF(stderr, "relaying data between gdb and process %d\n", pid);
1578 if (max_invoke_ms > 0)
1579 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1580 invoke_gdbserver_in_valgrind, (void *) &pid);
1581 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1582 acquire_lock(shared_mem_fd, pid);
1584 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
1585 "read mode from pid");
1587 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1589 Bool waiting_for_noack_mode = False;
1590 Bool waiting_for_qsupported = False;
1591 if(send_noack_mode) {
1592 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid, from_pid);
1593 write_buf(to_pid, "$QStartNoAckMode#b0", 19,
1594 "write start no ack mode",
1595 /* notify */ True);
1596 waiting_for_noack_mode = True;
1599 while (1) {
1600 ConnectionKind ck;
1601 int ret;
1602 struct pollfd pollfds[NumConnectionKind];
1604 /* watch data written by gdb, watch POLLERR on both gdb fd */
1605 pollfds[FROM_GDB].fd = from_gdb;
1606 pollfds[FROM_GDB].events = POLLIN;
1607 pollfds[FROM_GDB].revents = 0;
1608 pollfds[TO_GDB].fd = to_gdb;
1609 pollfds[TO_GDB].events = 0;
1610 pollfds[TO_GDB].revents = 0;
1612 /* watch data written by pid, watch POLLERR on both pid fd */
1613 pollfds[FROM_PID].fd = from_pid;
1614 pollfds[FROM_PID].events = POLLIN;
1615 pollfds[FROM_PID].revents = 0;
1616 pollfds[TO_PID].fd = to_pid;
1617 pollfds[TO_PID].events = 0;
1618 pollfds[TO_PID].revents = 0;
1620 ret = poll(pollfds,
1621 NumConnectionKind,
1622 (shutting_down ?
1623 1 /* one second */
1624 : -1 /* infinite */));
1625 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1627 /* check for unexpected error */
1628 if (ret <= 0 && errno != EINTR) {
1629 ERROR(errno, "unexpected poll ret %d\n", ret);
1630 shutting_down = True;
1631 break;
1634 /* check for data to read */
1635 for (ck = 0; ck < NumConnectionKind; ck ++) {
1636 if (pollfds[ck].revents & POLLIN) {
1637 switch (ck) {
1638 case FROM_GDB:
1639 if (waiting_for_noack_mode || waiting_for_qsupported)
1640 break; /* Don't add any messages while vgdb is talking. */
1641 if (!read_from_gdb_write_to_pid(to_pid))
1642 shutting_down = True;
1643 break;
1644 case FROM_PID:
1645 // First handle any messages from vgdb
1646 if (waiting_for_noack_mode) {
1647 char buf[PBUFSIZ+1]; // +1 for trailing \0
1648 size_t buflen;
1649 buflen = getpkt(buf, from_pid, to_pid);
1650 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1651 if (buflen != 2)
1652 ERROR(0, "no ack mode: unexpected buflen %d, buf %s\n",
1653 buflen, buf);
1654 else
1655 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1657 waiting_for_noack_mode = False;
1659 /* Propagate qSupported to valgrind, we already replied. */
1660 if (q_buf != NULL && q_buf[0] != '\0') {
1661 char *pkt = create_packet (q_buf);
1662 write_buf(to_pid, pkt, strlen(pkt),
1663 "write qSupported", /* notify */ True);
1664 free(pkt);
1665 waiting_for_qsupported = True;
1667 } else if (waiting_for_qsupported) {
1668 char buf[PBUFSIZ+1]; // +1 for trailing \0
1669 size_t buflen;
1670 buflen = getpkt(buf, from_pid, to_pid);
1671 /* Should we sanity check the result? */
1672 if (buflen > 0) {
1673 waiting_for_qsupported = False;
1674 } else {
1675 ERROR(0, "Unexpected getpkt for qSupported reply: %d\n",
1676 buflen);
1678 } else if (!read_from_pid_write_to_gdb(from_pid))
1679 shutting_down = True;
1680 break;
1681 default: XERROR(0, "unexpected POLLIN on %s\n",
1682 ppConnectionKind(ck));
1687 /* check for an fd being in error condition */
1688 for (ck = 0; ck < NumConnectionKind; ck ++) {
1689 if (pollfds[ck].revents & POLLERR) {
1690 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1691 ppConnectionKind(ck), pollfds[ck].fd);
1692 invoker_valgrind_dying();
1693 shutting_down = True;
1695 if (pollfds[ck].revents & POLLHUP) {
1696 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1697 ppConnectionKind(ck), pollfds[ck].fd);
1698 invoker_valgrind_dying();
1699 shutting_down = True;
1701 if (pollfds[ck].revents & POLLNVAL) {
1702 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1703 ppConnectionKind(ck), pollfds[ck].fd);
1704 invoker_valgrind_dying();
1705 shutting_down = True;
1709 if (shutting_down) {
1710 /* we let some time to the final packets to be transferred */
1711 shutdown_loop++;
1712 if (shutdown_loop > 3)
1713 break;
1716 close_connection(to_pid, from_pid);
1719 static int packet_len_for_command(char *cmd)
1721 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1722 return 7+ 2*strlen(cmd) +3 + 1;
1725 /* hyper-minimal protocol implementation that
1726 sends the provided commands (using qRcmd packets)
1727 and read and display their replies. */
1728 static
1729 void standalone_send_commands(int pid,
1730 int last_command,
1731 char *commands[] )
1733 int from_pid = -1; /* fd to read from pid */
1734 int to_pid = -1; /* fd to write to pid */
1736 int i;
1737 int hi;
1738 char hex[3];
1739 unsigned char cksum;
1740 char *hexcommand;
1741 char buf[PBUFSIZ+1]; // +1 for trailing \0
1742 int buflen;
1743 int nc;
1746 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
1747 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1748 invoke_gdbserver_in_valgrind, (void *) &pid);
1750 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1751 acquire_lock(shared_mem_fd, pid);
1753 /* first send a C-c \003 to pid, so that it wakes up the process
1754 After that, we can open the fifo from the pid in read mode
1755 We then start to wait for packets (normally first a resume reply)
1756 At that point, we send our command and expect replies */
1757 buf[0] = '\003';
1758 i = 0;
1759 while (!write_buf(to_pid, buf, 1,
1760 "write \\003 to wake up", /* notify */ True)) {
1761 /* If write fails, retries up to 10 times every 0.5 seconds
1762 This aims at solving the race condition described in
1763 remote-utils.c remote_finish function. */
1764 usleep(500*1000);
1765 i++;
1766 if (i >= 10)
1767 XERROR(errno, "failed to send wake up char after 10 trials\n");
1769 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1770 "read cmd result from pid");
1772 /* Enable no ack mode. */
1773 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1774 /* notify */ True);
1775 buflen = getpkt(buf, from_pid, to_pid);
1776 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1777 if (buflen != 2)
1778 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen);
1779 else
1780 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1783 for (nc = 0; nc <= last_command; nc++) {
1784 TSFPRINTF(stderr, "sending command %s to pid %d\n", commands[nc], pid);
1786 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1787 hexcommand = vmalloc(packet_len_for_command(commands[nc]));
1788 hexcommand[0] = 0;
1789 strcat(hexcommand, "$qRcmd,");
1790 for (i = 0; i < strlen(commands[nc]); i++) {
1791 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
1792 // Need to use unsigned char, to avoid sign extension.
1793 strcat(hexcommand, hex);
1795 /* checksum (but without the $) */
1796 cksum = 0;
1797 for (hi = 1; hi < strlen(hexcommand); hi++)
1798 cksum+=hexcommand[hi];
1799 strcat(hexcommand, "#");
1800 sprintf(hex, "%02x", cksum);
1801 strcat(hexcommand, hex);
1802 write_buf(to_pid, hexcommand, strlen(hexcommand),
1803 "writing hex command to pid", /* notify */ True);
1805 /* we exit of the below loop explicitly when the command has
1806 been handled or because a signal handler will set
1807 shutting_down. */
1808 while (!shutting_down) {
1809 buflen = getpkt(buf, from_pid, to_pid);
1810 if (buflen < 0) {
1811 ERROR(0, "error reading packet\n");
1812 if (buflen == -2)
1813 invoker_valgrind_dying();
1814 break;
1816 if (strlen(buf) == 0) {
1817 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1818 break;
1820 if (strcmp(buf, "OK") == 0) {
1821 DEBUG(1, "OK packet rcvd\n");
1822 break;
1824 if (buf[0] == 'E') {
1825 DEBUG(0,
1826 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1827 buf);
1828 break;
1830 if (buf[0] == 'W') {
1831 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1832 break;
1834 if (buf[0] == 'T') {
1835 DEBUG(1, "T resume reply packet received: %s\n", buf);
1836 continue;
1839 /* must be here an O packet with hex encoded string reply
1840 => decode and print it */
1841 if (buf[0] != 'O') {
1842 DEBUG(0, "expecting O packet, received: %s\n", buf);
1843 continue;
1846 char buf_print[buflen/2 + 1];
1847 for (i = 1; i < buflen; i = i + 2)
1848 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1849 + fromhex(*(buf+i+1));
1850 buf_print[buflen/2] = 0;
1851 printf("%s", buf_print);
1852 fflush(stdout);
1855 free(hexcommand);
1857 shutting_down = True;
1859 close_connection(to_pid, from_pid);
1862 /* report to user the existence of a vgdb-able valgrind process
1863 with given pid.
1864 Note: this function does not use XERROR if an error is encountered
1865 while producing the command line for pid, as this is not critical
1866 and at least on MacOS, reading cmdline is not available. */
1867 static
1868 void report_pid(int pid, Bool on_stdout)
1870 char cmdline_file[50]; // large enough
1871 int fd, i;
1872 FILE *out = on_stdout ? stdout : stderr;
1874 TSFPRINTF(out, "use --pid=%d for ", pid);
1876 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1877 fd = open(cmdline_file, O_RDONLY | O_CLOEXEC);
1878 if (fd == -1) {
1879 DEBUG(1, "error opening cmdline file %s %s\n",
1880 cmdline_file, strerror(errno));
1881 fprintf(out, "(could not open process command line)\n");
1882 } else {
1883 char cmdline[100];
1884 ssize_t sz;
1885 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) > 0) {
1886 for (i = 0; i < sz; i++)
1887 if (cmdline[i] == 0)
1888 cmdline[i] = ' ';
1889 cmdline[sz] = 0;
1890 fprintf(out, "%s", cmdline);
1892 if (sz == -1) {
1893 DEBUG(1, "error reading cmdline file %s %s\n",
1894 cmdline_file, strerror(errno));
1895 fprintf(out, "(error reading process command line)");
1897 fprintf(out, "\n");
1898 close(fd);
1900 fflush(out);
1903 static
1904 void usage(void)
1906 fprintf(stderr,
1907 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1908 "vgdb (valgrind gdb) has two usages\n"
1909 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1910 " The OPTION(s) must be followed by the command to send\n"
1911 " To send more than one command, separate the commands with -c\n"
1912 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1913 " Only OPTION(s) can be given.\n"
1914 "\n"
1915 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1916 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1917 " [--port=<portnr>\n"
1918 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1919 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
1920 " \n"
1921 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1922 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1923 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1924 " between the Valgrind gdbserver and vgdb.\n"
1925 " --wait (default 0) tells vgdb to check during the specified number\n"
1926 " of seconds if a Valgrind gdbserver can be found.\n"
1927 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1928 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1929 " process is blocked in a system call).\n"
1930 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1931 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1932 " gdbserver has not processed a command after number seconds\n"
1933 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
1934 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
1935 " --vargs everything that follows is an argument for valgrind.\n"
1936 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1937 " -T arg tells to add timestamps to vgdb information messages.\n"
1938 " -D arg tells to show shared mem status and then exit.\n"
1939 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
1940 "\n"
1941 " -h --help shows this message\n"
1942 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
1943 " To get help from the Valgrind gdbserver, use vgdb help\n"
1944 "\n", vgdb_prefix_default(), VG_LIBDIR "/valgrind-monitor.py"
1946 invoker_restrictions_msg();
1949 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
1950 and then exits.
1952 else if arg_pid == -1, waits maximum check_trials seconds to discover
1953 a valgrind pid appearing.
1955 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1956 with gdbserver activated.
1958 Returns the pid to work with
1959 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1961 static
1962 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1964 int i;
1965 int pid = -1;
1967 if (arg_pid == 0 || arg_pid < -1) {
1968 TSFPRINTF(stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1969 exit(1);
1970 } else {
1971 /* search for a matching named fifo.
1972 If we have been given a pid, we will check that the matching FIFO is
1973 there (or wait the nr of check_trials for this to appear).
1974 If no pid has been given, then if we find only one FIFO,
1975 we will use this to build the pid to use.
1976 If we find multiple processes with valid FIFO, we report them and will
1977 exit with an error. */
1978 DIR *vgdb_dir;
1979 char *vgdb_dir_name = vmalloc(strlen (vgdb_prefix) + 3);
1980 struct dirent *f;
1981 int is;
1982 int nr_valid_pid = 0;
1983 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1984 char *vgdb_format = vmalloc(strlen(vgdb_prefix) + strlen(suffix) + 1);
1986 strcpy(vgdb_format, vgdb_prefix);
1987 strcat(vgdb_format, suffix);
1989 if (strchr(vgdb_prefix, '/') != NULL) {
1990 strcpy(vgdb_dir_name, vgdb_prefix);
1991 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1992 if (vgdb_dir_name[is] == '/') {
1993 vgdb_dir_name[is+1] = '\0';
1994 break;
1996 } else {
1997 strcpy(vgdb_dir_name, "");
2000 DEBUG(1, "searching pid in directory %s format %s\n",
2001 vgdb_dir_name, vgdb_format);
2003 /* try to find FIFOs with valid pid.
2004 On exit of the loop, pid is set to:
2005 the last pid found if show_list (or -1 if no process was listed)
2006 -1 if no FIFOs matching a running process is found
2007 -2 if multiple FIFOs of running processes are found
2008 otherwise it is set to the (only) pid found that can be debugged
2010 for (i = 0; i < check_trials; i++) {
2011 DEBUG(1, "check_trial %d \n", i);
2012 if (i > 0)
2013 /* wait one second before checking again */
2014 sleep(1);
2016 vgdb_dir = opendir(strlen(vgdb_dir_name) ? vgdb_dir_name : "./");
2017 if (vgdb_dir == NULL)
2018 XERROR(errno,
2019 "vgdb error: opening directory %s searching vgdb fifo\n",
2020 vgdb_dir_name);
2022 errno = 0; /* avoid complain if vgdb_dir is empty */
2023 while ((f = readdir(vgdb_dir))) {
2024 struct stat st;
2025 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
2026 char *wrongpid;
2027 int newpid;
2029 strcpy(pathname, vgdb_dir_name);
2030 strcat(pathname, f->d_name);
2031 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
2032 if (stat(pathname, &st) != 0) {
2033 if (debuglevel >= 3)
2034 ERROR(errno, "vgdb error: stat %s searching vgdb fifo\n",
2035 pathname);
2036 } else if (S_ISFIFO(st.st_mode)) {
2037 DEBUG(3, "trying FIFO %s\n", pathname);
2038 if (strncmp(pathname, vgdb_format,
2039 strlen(vgdb_format)) == 0) {
2040 newpid = strtol(pathname + strlen(vgdb_format),
2041 &wrongpid, 10);
2042 if (*wrongpid == '-' && newpid > 0
2043 && kill(newpid, 0) == 0) {
2044 nr_valid_pid++;
2045 if (show_list) {
2046 report_pid(newpid, /*on_stdout*/ True);
2047 pid = newpid;
2048 } else if (arg_pid != -1) {
2049 if (arg_pid == newpid) {
2050 pid = newpid;
2052 } else if (nr_valid_pid > 1) {
2053 if (nr_valid_pid == 2) {
2054 TSFPRINTF
2055 (stderr,
2056 "no --pid= arg given"
2057 " and multiple valgrind pids found:\n");
2058 report_pid(pid, /*on_stdout*/ False);
2060 pid = -2;
2061 report_pid(newpid, /*on_stdout*/ False);
2062 } else {
2063 pid = newpid;
2068 errno = 0; /* avoid complain if at the end of vgdb_dir */
2070 if (f == NULL && errno != 0)
2071 XERROR(errno, "vgdb error: reading directory %s for vgdb fifo\n",
2072 vgdb_dir_name);
2074 closedir(vgdb_dir);
2075 if (pid != -1)
2076 break;
2079 free(vgdb_dir_name);
2080 free(vgdb_format);
2083 if (show_list) {
2084 exit(1);
2085 } else if (pid == -1) {
2086 if (arg_pid == -1)
2087 TSFPRINTF(stderr, "vgdb error: no FIFO found and no pid given\n");
2088 else
2089 TSFPRINTF(stderr, "vgdb error: no FIFO found matching pid %d\n",
2090 arg_pid);
2091 exit(1);
2093 else if (pid == -2) {
2094 /* no arg_pid given, multiple FIFOs found */
2095 exit(1);
2097 else {
2098 return pid;
2102 /* return true if the numeric value of an option of the
2103 form --xxxxxxxxx=<number> could properly be extracted
2104 from arg. If True is returned, *value contains the
2105 extracted value.*/
2106 static
2107 Bool numeric_val(char* arg, int *value)
2109 const char *eq_pos = strchr(arg, '=');
2110 char *wrong;
2111 long long int long_value;
2113 if (eq_pos == NULL)
2114 return False;
2116 long_value = strtoll(eq_pos+1, &wrong, 10);
2117 if (long_value < 0 || long_value > INT_MAX)
2118 return False;
2119 if (*wrong)
2120 return False;
2122 *value = (int) long_value;
2123 return True;
2126 /* true if arg matches the provided option */
2127 static
2128 Bool is_opt(char* arg, const char *option)
2130 int option_len = strlen(option);
2131 if (option[option_len-1] == '=')
2132 return (0 == strncmp(option, arg, option_len));
2133 else
2134 return (0 == strcmp(option, arg));
2137 /* Parse command lines options. If error(s), exits.
2138 Otherwise returns the options in *p_... args.
2139 commands must be big enough for the commands extracted from argv.
2140 On return, *p_last_command gives the position in commands where
2141 the last command has been allocated (using vmalloc). */
2142 static
2143 void parse_options(int argc, char** argv,
2144 Bool *p_show_shared_mem,
2145 Bool *p_show_list,
2146 Bool *p_multi_mode,
2147 int *p_arg_pid,
2148 int *p_check_trials,
2149 int *p_port,
2150 int *p_last_command,
2151 char *commands[])
2153 Bool show_shared_mem = False;
2154 Bool show_list = False;
2155 Bool multi_mode = False;
2156 int arg_pid = -1;
2157 int check_trials = 1;
2158 int last_command = -1;
2159 int int_port = 0;
2161 int i;
2162 int arg_errors = 0;
2164 for (i = 1; i < argc; i++) {
2165 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2166 usage();
2167 exit(0);
2168 } else if (is_opt(argv[i], "-d")) {
2169 debuglevel++;
2170 } else if (is_opt(argv[i], "-D")) {
2171 show_shared_mem = True;
2172 } else if (is_opt(argv[i], "-l")) {
2173 show_list = True;
2174 } else if (is_opt(argv[i], "--multi")) {
2175 multi_mode = True;
2176 } else if (is_opt(argv[i], "-T")) {
2177 timestamp = True;
2178 } else if (is_opt(argv[i], "--pid=")) {
2179 int newpid;
2180 if (!numeric_val(argv[i], &newpid)) {
2181 TSFPRINTF(stderr, "invalid --pid argument %s\n", argv[i]);
2182 arg_errors++;
2183 } else if (arg_pid != -1) {
2184 TSFPRINTF(stderr, "multiple --pid arguments given\n");
2185 arg_errors++;
2186 } else {
2187 arg_pid = newpid;
2189 } else if (is_opt(argv[i], "--wait=")) {
2190 if (!numeric_val(argv[i], &check_trials)) {
2191 TSFPRINTF(stderr, "invalid --wait argument %s\n", argv[i]);
2192 arg_errors++;
2194 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2195 if (!numeric_val(argv[i], &max_invoke_ms)) {
2196 TSFPRINTF(stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
2197 arg_errors++;
2199 } else if (is_opt(argv[i], "--cmd-time-out=")) {
2200 if (!numeric_val(argv[i], &cmd_time_out)) {
2201 TSFPRINTF(stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
2202 arg_errors++;
2204 } else if (is_opt(argv[i], "--port=")) {
2205 if (!numeric_val(argv[i], &int_port)) {
2206 TSFPRINTF(stderr, "invalid --port argument %s\n", argv[i]);
2207 arg_errors++;
2209 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2210 vgdb_prefix = strdup (argv[i] + 14);
2211 } else if (is_opt(argv[i], "--valgrind=")) {
2212 char *path = argv[i] + 11;
2213 /* Compute the absolute path. */
2214 valgrind_path = realpath(path, NULL);
2215 if (!valgrind_path) {
2216 TSFPRINTF(stderr, "%s is not a correct path. %s, exiting.\n", path, strerror (errno));
2217 exit(1);
2219 DEBUG(2, "valgrind's real path: %s\n", valgrind_path);
2220 } else if (is_opt(argv[i], "--vargs")) {
2221 // Everything that follows now is an argument for valgrind
2222 // No other options (or commands) can follow
2223 // argc - i is the number of left over arguments
2224 // allocate enough space, but all args in it.
2225 cvargs = argc - i - 1;
2226 vargs = vmalloc (cvargs * sizeof(vargs));
2227 i++;
2228 for (int j = 0; i < argc; i++) {
2229 vargs[j] = argv[i];
2230 j++;
2232 } else if (is_opt(argv[i], "-c")) {
2233 last_command++;
2234 commands[last_command] = vmalloc(1);
2235 commands[last_command][0] = '\0';
2236 } else if (0 == strncmp(argv[i], "-", 1)) {
2237 TSFPRINTF(stderr, "unknown or invalid argument %s\n", argv[i]);
2238 arg_errors++;
2239 } else {
2240 int len;
2241 if (last_command == -1) {
2242 /* only one command, no -c command indicator */
2243 last_command++;
2244 commands[last_command] = vmalloc(1);
2245 commands[last_command][0] = '\0';
2247 len = strlen(commands[last_command]);
2248 commands[last_command] = vrealloc(commands[last_command],
2249 len + 1 + strlen(argv[i]) + 1);
2250 if (len > 0)
2251 strcat(commands[last_command], " ");
2252 strcat(commands[last_command], argv[i]);
2253 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2254 TSFPRINTF(stderr, "command %s too long\n", commands[last_command]);
2255 arg_errors++;
2261 if (vgdb_prefix == NULL)
2262 vgdb_prefix = vgdb_prefix_default();
2264 if (multi_mode
2265 && (show_shared_mem
2266 || show_list
2267 || last_command != -1)) {
2268 arg_errors++;
2269 TSFPRINTF(stderr,
2270 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2273 if (isatty(0)
2274 && !show_shared_mem
2275 && !show_list
2276 && int_port == 0
2277 && last_command == -1) {
2278 arg_errors++;
2279 TSFPRINTF(stderr,
2280 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2283 if (show_shared_mem && show_list) {
2284 arg_errors++;
2285 TSFPRINTF(stderr,
2286 "Can't use both -D and -l options\n");
2289 if (max_invoke_ms > 0
2290 && cmd_time_out != NEVER
2291 && (cmd_time_out * 1000) <= max_invoke_ms) {
2292 arg_errors++;
2293 TSFPRINTF(stderr,
2294 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2297 if (show_list && arg_pid != -1) {
2298 arg_errors++;
2299 TSFPRINTF(stderr,
2300 "Can't use both --pid and -l options\n");
2303 if (int_port > 0 && last_command != -1) {
2304 arg_errors++;
2305 TSFPRINTF(stderr,
2306 "Can't use --port to send commands\n");
2309 if (arg_errors > 0) {
2310 TSFPRINTF(stderr, "args error. Try `vgdb --help` for more information\n");
2311 exit(1);
2314 *p_show_shared_mem = show_shared_mem;
2315 *p_show_list = show_list;
2316 *p_multi_mode = multi_mode;
2317 *p_arg_pid = arg_pid;
2318 *p_check_trials = check_trials;
2319 *p_port = int_port;
2320 *p_last_command = last_command;
2323 int main(int argc, char** argv)
2325 int i;
2326 int pid;
2328 Bool show_shared_mem;
2329 Bool show_list;
2330 Bool multi_mode;
2331 int arg_pid;
2332 int check_trials;
2333 int in_port;
2334 int last_command;
2335 char *commands[argc]; // we will never have more commands than args.
2337 parse_options(argc, argv,
2338 &show_shared_mem,
2339 &show_list,
2340 &multi_mode,
2341 &arg_pid,
2342 &check_trials,
2343 &in_port,
2344 &last_command,
2345 commands);
2347 /* when we are working as a relay for gdb, handle some signals by
2348 only reporting them (according to debug level). Also handle these
2349 when ptrace will be used: vgdb must clean up the ptrace effect before
2350 dying. */
2351 if (max_invoke_ms > 0 || last_command == -1)
2352 install_handlers();
2354 if (!multi_mode) {
2355 pid = search_arg_pid(arg_pid, check_trials, show_list);
2357 prepare_fifos_and_shared_mem(pid);
2358 } else {
2359 pid = 0;
2362 if (in_port > 0)
2363 wait_for_gdb_connect(in_port);
2365 if (show_shared_mem) {
2366 TSFPRINTF(stderr,
2367 "vgdb %d "
2368 "written_by_vgdb %d "
2369 "seen_by_valgrind %d\n",
2370 VS_vgdb_pid,
2371 VS_written_by_vgdb,
2372 VS_seen_by_valgrind);
2373 TSFPRINTF(stderr, "vgdb pid %d\n", VS_vgdb_pid);
2374 exit(0);
2377 if (multi_mode) {
2378 do_multi_mode ();
2379 } else if (last_command >= 0) {
2380 standalone_send_commands(pid, last_command, commands);
2381 } else {
2382 gdb_relay(pid, 0, NULL);
2385 free(vgdb_prefix);
2386 free(valgrind_path);
2387 if (!multi_mode)
2388 cleanup_fifos_and_shared_mem();
2390 for (i = 0; i <= last_command; i++)
2391 free(commands[i]);
2392 return 0;