Add new exp files to EXTRA_DIST in memcheck/tests/Makefile.am
[valgrind.git] / coregrind / vgdb.c
blob872c7d2801ab9c6c8d7caf5d2b8637fbf68e0507
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 three 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
55 3. multi mode where vgdb uses the GDB extended remote protocol.
57 It is made of a main program which reads arguments. If no
58 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
59 assumed.
61 As relay application, vgdb reads bytes from gdb on stdin and
62 writes these bytes to valgrind. Bytes read from valgrind are
63 written to gdb on stdout. Read/Write from/to valgrind is done
64 using FIFOs. There is one thread reading from stdin, writing to
65 valgrind on a FIFO. There is one thread reading from valgrind on a
66 FIFO, writing to gdb on stdout
68 As a standalone utility, vgdb builds command packets to write to valgrind,
69 sends it and reads the reply. The same two threads are used to write/read.
70 Once all the commands are sent and their replies received, vgdb will exit.
72 When --multi is given vgdb communicates with GDB through the extended remote
73 protocol and will launch valgrind whenever GDB sends the vRun packet, after
74 which it will function in the first mode, relaying packets between GDB and
75 the gdbserver embedded in valgrind till that valgrind quits. vgdb will stay
76 connected to GDB.
79 int debuglevel;
80 Bool timestamp = False;
81 char timestamp_out[20];
82 static char *vgdb_prefix = NULL;
83 static char *valgrind_path = NULL;
84 static char **vargs;
85 static char cvargs = 0;
87 char *timestamp_str (Bool produce)
89 static char out[50];
90 char *ptr;
91 struct timeval dbgtv;
92 struct tm *ts_tm;
94 if (produce) {
95 gettimeofday(&dbgtv, NULL);
96 ts_tm = localtime(&dbgtv.tv_sec);
97 ptr = out + strftime(out, sizeof(out), "%H:%M:%S", ts_tm);
98 sprintf(ptr, ".%6.6ld ", dbgtv.tv_usec);
99 } else {
100 out[0] = 0;
102 return out;
105 /* Will be set to True when any condition indicating we have to shutdown
106 is encountered. */
107 Bool shutting_down = False;
109 VgdbShared32 *shared32;
110 VgdbShared64 *shared64;
111 #define VS_written_by_vgdb (shared32 != NULL ? \
112 shared32->written_by_vgdb \
113 : shared64->written_by_vgdb)
114 #define VS_seen_by_valgrind (shared32 != NULL ? \
115 shared32->seen_by_valgrind \
116 : shared64->seen_by_valgrind)
118 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
120 void *vmalloc(size_t size)
122 void * mem = malloc(size);
123 if (mem == NULL)
124 XERROR(errno, "can't allocate memory\n");
125 return mem;
128 void *vrealloc(void *ptr,size_t size)
130 void * mem = realloc(ptr, size);
131 if (mem == NULL)
132 XERROR(errno, "can't reallocate memory\n");
133 return mem;
136 /* Return the name of a directory for temporary files. */
137 static
138 const char *vgdb_tmpdir(void)
140 const char *tmpdir;
142 tmpdir = getenv("TMPDIR");
143 if (tmpdir == NULL || *tmpdir == '\0')
144 tmpdir = VG_TMPDIR;
145 if (tmpdir == NULL || *tmpdir == '\0')
146 tmpdir = "/tmp"; /* fallback */
148 return tmpdir;
151 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
152 to communicate with valgrind */
153 static
154 char *vgdb_prefix_default(void)
156 static HChar *prefix;
158 if (prefix == NULL) {
159 const char *tmpdir = vgdb_tmpdir();
160 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
161 strcpy(prefix, tmpdir);
162 strcat(prefix, "/vgdb-pipe");
164 return prefix;
167 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
168 static
169 void add_written(int nrw)
171 if (shared32 != NULL)
172 shared32->written_by_vgdb += nrw;
173 else if (shared64 != NULL)
174 shared64->written_by_vgdb += nrw;
175 else
176 assert(0);
179 static int shared_mem_fd = -1;
180 static
181 void map_vgdbshared(char* shared_mem, int check_trials)
183 struct stat fdstat;
184 void **s;
185 int tries = 50;
186 int err;
188 /* valgrind might still be starting up, give it 5 seconds by
189 * default, or check_trails seconds if it is set by --wait
190 * to more than a second. */
191 if (check_trials > 1) {
192 DEBUG(1, "check_trials %d\n", check_trials);
193 tries = check_trials * 10;
195 do {
196 shared_mem_fd = open(shared_mem, O_RDWR | O_CLOEXEC);
197 err = errno;
198 if (shared_mem_fd == -1 && err == ENOENT && tries > 0)
199 usleep (100000); /* wait 0.1 seconds */
200 } while (shared_mem_fd == -1 && err == ENOENT && tries-- > 0);
202 /* shared_mem_fd will not be closed till vgdb exits. */
204 if (shared_mem_fd == -1)
205 XERROR(errno, "error opening %s shared memory file\n", shared_mem);
207 if (fstat(shared_mem_fd, &fdstat) != 0)
208 XERROR(errno, "fstat\n");
210 if (fdstat.st_size == sizeof(VgdbShared64))
211 s = (void*) &shared64;
212 else if (fdstat.st_size == sizeof(VgdbShared32))
213 s = (void*) &shared32;
214 else
215 #if VEX_HOST_WORDSIZE == 8
216 XERROR(0,
217 "error size shared memory file %s.\n"
218 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
219 shared_mem,
220 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
221 (long int)fdstat.st_size);
222 #elif VEX_HOST_WORDSIZE == 4
223 XERROR(0,
224 "error size shared memory file %s.\n"
225 "expecting size %d (32bits) got %ld.\n",
226 shared_mem,
227 (int) sizeof(VgdbShared32),
228 fdstat.st_size);
229 #else
230 # error "unexpected wordsize"
231 #endif
233 #if VEX_HOST_WORDSIZE == 4
234 if (shared64 != NULL)
235 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
236 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
237 #endif
239 *s = (void*) mmap(NULL, fdstat.st_size,
240 PROT_READ|PROT_WRITE, MAP_SHARED,
241 shared_mem_fd, 0);
243 if (*s == (void *) -1)
244 XERROR(errno, "error mmap shared memory file %s\n", shared_mem);
248 /* This function loops till shutting_down becomes true. In this loop,
249 it verifies if valgrind process is reading the characters written
250 by vgdb. The verification is done every max_invoke_ms ms. If
251 valgrind is not reading characters, it will use invoker_invoke_gdbserver
252 to ensure that the gdbserver code is called soon by valgrind. */
253 static int max_invoke_ms = 100;
254 #define NEVER 99999999
255 static int cmd_time_out = NEVER;
256 static
257 void *invoke_gdbserver_in_valgrind(void *v_pid)
259 struct timeval cmd_max_end_time;
260 Bool cmd_started = False;
261 struct timeval invoke_time;
263 int pid = *(int *)v_pid;
264 int written_by_vgdb_before_sleep;
265 int seen_by_valgrind_before_sleep;
267 int invoked_written = -1;
268 unsigned int usecs;
270 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
272 while (!shutting_down) {
273 written_by_vgdb_before_sleep = VS_written_by_vgdb;
274 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
275 DEBUG(3,
276 "written_by_vgdb_before_sleep %d "
277 "seen_by_valgrind_before_sleep %d\n",
278 written_by_vgdb_before_sleep,
279 seen_by_valgrind_before_sleep);
280 if (cmd_time_out != NEVER
281 && !cmd_started
282 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
283 /* A command was started. Record the time at which it was started. */
284 DEBUG(1, "IO for command started\n");
285 gettimeofday(&cmd_max_end_time, NULL);
286 cmd_max_end_time.tv_sec += cmd_time_out;
287 cmd_started = True;
289 if (max_invoke_ms > 0) {
290 usecs = 1000 * max_invoke_ms;
291 gettimeofday(&invoke_time, NULL);
292 invoke_time.tv_sec += max_invoke_ms / 1000;
293 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
294 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
295 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
296 } else {
297 usecs = 0;
299 if (cmd_started) {
300 // 0 usecs here means the thread just has to check gdbserver eats
301 // the characters in <= cmd_time_out seconds.
302 // We will just wait by 1 second max at a time.
303 if (usecs == 0 || usecs > 1000 * 1000)
304 usecs = 1000 * 1000;
306 usleep(usecs);
308 /* If nothing happened during our sleep, let's try to wake up valgrind
309 or check for cmd time out. */
310 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
311 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
312 && VS_written_by_vgdb > VS_seen_by_valgrind) {
313 struct timeval now;
314 gettimeofday(&now, NULL);
315 DEBUG(2,
316 "after sleep "
317 "written_by_vgdb %d "
318 "seen_by_valgrind %d "
319 "invoked_written %d\n",
320 VS_written_by_vgdb,
321 VS_seen_by_valgrind,
322 invoked_written);
323 /* if the pid does not exist anymore, we better stop */
324 if (kill(pid, 0) != 0)
325 XERROR(errno,
326 "invoke_gdbserver_in_valgrind: "
327 "check for pid %d existence failed\n", pid);
328 if (cmd_started) {
329 if (timercmp(&now, &cmd_max_end_time, >))
330 XERROR(0,
331 "pid %d did not handle a command in %d seconds\n",
332 pid, cmd_time_out);
334 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
335 /* only need to wake up if the nr written has changed since
336 last invoke. */
337 if (invoked_written != written_by_vgdb_before_sleep) {
338 if (invoker_invoke_gdbserver(pid)) {
339 /* If invoke successful, no need to invoke again
340 for the same value of written_by_vgdb_before_sleep. */
341 invoked_written = written_by_vgdb_before_sleep;
345 } else {
346 // Something happened => restart timer check.
347 if (cmd_time_out != NEVER) {
348 DEBUG(2, "some IO was done => restart command\n");
349 cmd_started = False;
353 pthread_cleanup_pop(0);
354 return NULL;
357 static
358 int open_fifo(const char* name, int flags, const char* desc)
360 int fd;
361 DEBUG(1, "opening %s %s\n", name, desc);
362 fd = open(name, flags | O_CLOEXEC);
363 if (fd == -1)
364 XERROR(errno, "error opening %s %s\n", name, desc);
366 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
367 return fd;
370 /* acquire a lock on the first byte of the given fd. If not successful,
371 exits with error.
372 This allows to avoid having two vgdb speaking with the same Valgrind
373 gdbserver as this causes serious headaches to the protocol. */
374 static
375 void acquire_lock(int fd, int valgrind_pid)
377 struct flock fl;
378 fl.l_type = F_WRLCK;
379 fl.l_whence = SEEK_SET;
380 fl.l_start = 0;
381 fl.l_len = 1;
382 if (fcntl(fd, F_SETLK, &fl) < 0) {
383 if (errno == EAGAIN || errno == EACCES) {
384 XERROR(errno,
385 "Cannot acquire lock.\n"
386 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
387 VS_vgdb_pid,
388 valgrind_pid);
389 } else {
390 XERROR(errno, "cannot acquire lock.\n");
394 /* Here, we have the lock. It will be released when fd will be closed. */
395 /* We indicate our pid to Valgrind gdbserver */
396 if (shared32 != NULL)
397 shared32->vgdb_pid = getpid();
398 else if (shared64 != NULL)
399 shared64->vgdb_pid = getpid();
400 else
401 assert(0);
404 #define PBUFSIZ 16384 /* keep in sync with server.h */
406 /* read some characters from fd.
407 Returns the nr of characters read, -1 if error.
408 desc is a string used in tracing */
409 static
410 int read_buf(int fd, char* buf, const char* desc)
412 int nrread;
413 DEBUG(2, "reading %s\n", desc);
414 /* The file descriptor is on non-blocking mode and read_buf should only
415 be called when poll gave us an POLLIN event signaling the file
416 descriptor is ready for reading from. Still sometimes we do get an
417 occasional EAGAIN. Just do as told in that case and try to read
418 again. */
419 do {
420 nrread = read(fd, buf, PBUFSIZ);
421 } while (nrread == -1 && errno == EAGAIN);
422 if (nrread == -1) {
423 ERROR(errno, "error reading %s\n", desc);
424 return -1;
426 buf[nrread] = '\0';
427 DEBUG(2, "read %s %s\n", desc, buf);
428 return nrread;
431 /* write size bytes from buf to fd.
432 desc is a description of the action for which the write is done.
433 If notify, then add size to the shared cntr indicating to the
434 valgrind process that there is new data.
435 Returns True if write is ok, False if there was a problem. */
436 static
437 Bool write_buf(int fd, const char* buf, int size, const char* desc, Bool notify)
439 int nrwritten;
440 int nrw;
441 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
442 size, buf, notify);
443 nrwritten = 0;
444 while (nrwritten < size) {
445 nrw = write(fd, buf+nrwritten, size - nrwritten);
446 if (nrw == -1) {
447 ERROR(errno, "error write %s\n", desc);
448 return False;
450 nrwritten = nrwritten + nrw;
451 if (notify)
452 add_written(nrw);
454 return True;
457 typedef enum {
458 FROM_GDB,
459 TO_GDB,
460 FROM_PID,
461 TO_PID } ConnectionKind;
462 static const int NumConnectionKind = TO_PID+1;
463 static
464 const char *ppConnectionKind(ConnectionKind con)
466 switch (con) {
467 case FROM_GDB: return "FROM_GDB";
468 case TO_GDB: return "TO_GDB";
469 case FROM_PID: return "FROM_PID";
470 case TO_PID: return "TO_PID";
471 default: return "invalid connection kind";
475 static char *shared_mem;
477 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
478 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
480 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
481 static char *to_gdb_from_pid; /* fifo name to read pid replies */
483 /* Returns True in case read/write operations were done properly.
484 Returns False in case of error.
485 to_pid is the file descriptor to write to the process pid. */
486 static
487 Bool read_from_gdb_write_to_pid(int to_pid)
489 char buf[PBUFSIZ+1]; // +1 for trailing \0
490 int nrread;
491 Bool ret;
493 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
494 if (nrread <= 0) {
495 if (nrread == 0)
496 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
497 else
498 DEBUG(1, "error reading bytes from gdb\n");
499 close(from_gdb);
500 shutting_down = True;
501 return False;
503 ret = write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
504 if (!ret) {
505 /* Let gdb know the packet couldn't be delivered. */
506 write_buf(to_gdb, "$E01#a6", 8, "error back to gdb", False);
508 return ret;
511 /* Returns True in case read/write operations were done properly.
512 Returns False in case of error.
513 from_pid is the file descriptor to read data from the process pid. */
514 static
515 Bool read_from_pid_write_to_gdb(int from_pid)
517 char buf[PBUFSIZ+1]; // +1 for trailing \0
518 int nrread;
520 nrread = read_buf(from_pid, buf, "from pid");
521 if (nrread <= 0) {
522 if (nrread == 0)
523 DEBUG(1, "read 0 bytes from pid => assume exit\n");
524 else
525 DEBUG(1, "error reading bytes from pid\n");
526 close(from_pid);
527 shutting_down = True;
528 return False;
530 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
533 static
534 void wait_for_gdb_connect(int in_port)
536 struct sockaddr_in addr;
538 #ifdef SOCK_CLOEXEC
539 int listen_gdb = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
540 #else
541 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
542 #endif
544 int gdb_connect;
546 if (-1 == listen_gdb) {
547 XERROR(errno, "cannot create socket\n");
550 /* allow address reuse to avoid "address already in use" errors */
552 int one = 1;
553 if (setsockopt(listen_gdb, SOL_SOCKET, SO_REUSEADDR,
554 &one, sizeof(one)) < 0) {
555 XERROR(errno, "cannot enable address reuse\n");
558 memset(&addr, 0, sizeof(addr));
560 addr.sin_family = AF_INET;
561 addr.sin_port = htons((unsigned short int)in_port);
562 addr.sin_addr.s_addr = INADDR_ANY;
564 if (-1 == bind(listen_gdb, (struct sockaddr *)&addr, sizeof(addr))) {
565 XERROR(errno, "bind failed\n");
567 TSFPRINTF(stderr, "listening on port %d ...", in_port);
568 if (-1 == listen(listen_gdb, 1)) {
569 XERROR(errno, "error listen failed\n");
572 #ifdef SOCK_CLOEXEC
573 gdb_connect = accept4(listen_gdb, NULL, NULL, SOCK_CLOEXEC);
574 #else
575 gdb_connect = accept(listen_gdb, NULL, NULL);
576 #endif
578 if (gdb_connect < 0) {
579 XERROR(errno, "accept failed\n");
581 fprintf(stderr, "connected.\n");
582 fflush(stderr);
583 close(listen_gdb);
584 from_gdb = gdb_connect;
585 to_gdb = gdb_connect;
588 /* prepares the FIFOs filenames, map the shared memory. */
589 static
590 void prepare_fifos_and_shared_mem(int pid, int check_trials)
592 const HChar *user, *host;
593 unsigned len;
595 user = getenv("LOGNAME");
596 if (user == NULL) user = getenv("USER");
597 if (user == NULL) user = "???";
598 if (strchr(user, '/')) user = "???";
600 host = getenv("HOST");
601 if (host == NULL) host = getenv("HOSTNAME");
602 if (host == NULL) host = "???";
603 if (strchr(host, '/')) host = "???";
605 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
606 from_gdb_to_pid = vmalloc(len);
607 to_gdb_from_pid = vmalloc(len);
608 shared_mem = vmalloc(len);
609 /* below 3 lines must match the equivalent in remote-utils.c */
610 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
611 pid, user, host);
612 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
613 pid, user, host);
614 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
615 pid, user, host);
616 DEBUG(1, "vgdb: using %s %s %s\n",
617 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
619 map_vgdbshared(shared_mem, check_trials);
622 static void
623 cleanup_fifos_and_shared_mem(void)
625 free(from_gdb_to_pid);
626 free(to_gdb_from_pid);
627 free(shared_mem);
628 close(shared_mem_fd);
631 /* Convert hex digit A to a number. */
633 static int
634 fromhex(int a)
636 if (a >= '0' && a <= '9')
637 return a - '0';
638 else if (a >= 'a' && a <= 'f')
639 return a - 'a' + 10;
640 else
641 XERROR(0, "Reply contains invalid hex digit %c\n", a);
642 return 0;
645 /* Returns next char from fd. -1 if error, -2 if EOF.
646 NB: must always call it with the same fd */
647 static int
648 readchar(int fd)
650 static char buf[PBUFSIZ+1]; // +1 for trailing \0
651 static int bufcnt = 0;
652 static unsigned char *bufp;
653 // unsigned bufp to e.g. avoid having 255 converted to int -1
655 if (bufcnt-- > 0)
656 return *bufp++;
658 bufcnt = read_buf(fd, buf, "static buf readchar");
660 if (bufcnt <= 0) {
661 if (bufcnt == 0) {
662 TSFPRINTF(stderr, "readchar: Got EOF\n");
663 return -2;
664 } else {
665 ERROR(errno, "readchar\n");
666 return -1;
670 bufp = (unsigned char *)buf;
671 bufcnt--;
672 return *bufp++;
675 /* Read a packet from fromfd, with error checking,
676 and store it in BUF.
677 If checksum incorrect, writes a - on ackfd.
678 Returns length of packet, or -1 if error or -2 if EOF. */
679 static int
680 getpkt(char *buf, int fromfd, int ackfd)
682 char *bp;
683 unsigned char csum, c1, c2;
684 int c;
686 while (1) {
687 csum = 0;
689 while (1) {
690 c = readchar(fromfd);
691 if (c == '$')
692 break;
693 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
694 if (c < 0)
695 return c;
698 bp = buf;
699 while (1) {
700 c = readchar(fromfd);
701 if (c < 0)
702 return c;
703 if (c == '#')
704 break;
705 if (c == '*') {
706 int repeat;
707 int r;
708 int prev;
709 prev = *(bp-1);
710 csum += c;
711 repeat = readchar(fromfd);
712 csum += repeat;
713 for (r = 0; r < repeat - 29; r ++)
714 *bp++ = prev;
715 } else {
716 *bp++ = c;
717 csum += c;
720 *bp = 0;
722 c1 = fromhex(readchar (fromfd));
723 c2 = fromhex(readchar (fromfd));
725 if (csum == (c1 << 4) + c2)
726 break;
728 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
729 (c1 << 4) + c2, csum, buf);
730 if (write(ackfd, "-", 1) != 1)
731 ERROR(errno, "error when writing - (nack)\n");
732 else
733 add_written(1);
736 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
737 return bp - buf;
740 static int sigint = 0;
741 static int sigterm = 0;
742 static int sigpipe = 0;
743 static int sighup = 0;
744 static int sigusr1 = 0;
745 static int sigalrm = 0;
746 static int sigusr1_fd = -1;
747 static pthread_t invoke_gdbserver_in_valgrind_thread;
749 static
750 void received_signal(int signum)
752 if (signum == SIGINT)
753 sigint++;
754 else if (signum == SIGUSR1) {
755 sigusr1++;
756 if (sigusr1_fd >= 0) {
757 char control_c = '\003';
758 write_buf(sigusr1_fd, &control_c, 1,
759 "write \\003 on SIGUSR1", /* notify */ True);
762 else if (signum == SIGTERM) {
763 shutting_down = True;
764 sigterm++;
765 } else if (signum == SIGHUP) {
766 shutting_down = True;
767 sighup++;
768 } else if (signum == SIGPIPE) {
769 sigpipe++;
770 } else if (signum == SIGALRM) {
771 sigalrm++;
772 #if defined(VGPV_arm_linux_android) \
773 || defined(VGPV_x86_linux_android) \
774 || defined(VGPV_mips32_linux_android) \
775 || defined(VGPV_arm64_linux_android)
776 /* Android has no pthread_cancel. As it also does not have
777 an invoker implementation, there is no need for cleanup action.
778 So, we just do nothing. */
779 DEBUG(1, "sigalrm received, no action on android\n");
780 #else
781 /* Note: we cannot directly invoke restore_and_detach : this must
782 be done by the thread that has attached.
783 We have in this thread pushed a cleanup handler that will
784 cleanup what is needed. */
785 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
786 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
787 #endif
788 } else {
789 ERROR(0, "unexpected signal %d\n", signum);
793 /* install the signal handlers allowing e.g. vgdb to cleanup in
794 case of termination. */
795 static
796 void install_handlers(void)
798 struct sigaction action, oldaction;
800 action.sa_handler = received_signal;
801 sigemptyset(&action.sa_mask);
802 action.sa_flags = 0;
804 /* SIGINT: when user types C-c in gdb, this sends
805 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
806 The later is enough to wakeup the valgrind process. */
807 if (sigaction(SIGINT, &action, &oldaction) != 0)
808 XERROR(errno, "vgdb error sigaction SIGINT\n");
809 /* We might do something more intelligent than just
810 reporting this SIGINT E.g. behave similarly to the gdb: two
811 control-C without feedback from the debugged process would
812 mean to stop debugging it. */
814 /* SIGUSR1: this is used to facilitate automatic testing. When
815 vgdb receives this signal, it will simulate the user typing C-c. */
816 if (sigaction(SIGUSR1, &action, &oldaction) != 0)
817 XERROR(errno, "vgdb error sigaction SIGUSR1\n");
820 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
821 when detaching or similar. A clean shutdown will be done as both
822 the read and write side will detect an end of file. */
823 if (sigaction(SIGTERM, &action, &oldaction) != 0)
824 XERROR(errno, "vgdb error sigaction SIGTERM\n");
826 /* SIGPIPE: can receive this signal when gdb detaches or kill the
827 process debugged: gdb will close its pipes to vgdb. vgdb
828 must resist to this signal to allow a clean shutdown. */
829 if (sigaction(SIGPIPE, &action, &oldaction) != 0)
830 XERROR(errno, "vgdb error sigaction SIGPIPE\n");
832 /* SIGALRM: in case invoke thread is blocked, alarm is used
833 to cleanup. */
834 if (sigaction(SIGALRM, &action, &oldaction) != 0)
835 XERROR(errno, "vgdb error sigaction SIGALRM\n");
837 /* unmask all signals, in case the process that launched vgdb
838 masked some. */
839 if (sigprocmask(SIG_SETMASK, &action.sa_mask, NULL) != 0)
840 XERROR(errno, "vgdb error sigprocmask\n");
843 /* close the FIFOs provided connections, terminate the invoker thread. */
844 static
845 void close_connection(int to_pid, int from_pid)
847 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
848 sigint, sigterm, sighup, sigpipe);
849 /* Note that we do not forward sigterm to the valgrind process:
850 a sigterm signal is (probably) received from gdb if the user wants to
851 kill the debugged process. The kill instruction has been given to
852 the valgrind process, which should execute a clean exit. */
854 /* We first close the connection to pid. The pid will then
855 terminates its gdbserver work. We keep the from pid
856 fifo opened till the invoker thread is finished.
857 This allows the gdbserver to finish sending its last reply. */
858 if (close(to_pid) != 0)
859 ERROR(errno, "close to_pid\n");
861 /* if there is a task that was busy trying to wake up valgrind
862 process, we wait for it to be terminated otherwise threads
863 in the valgrind process can stay stopped if vgdb main
864 exits before the invoke thread had time to detach from
865 all valgrind threads. */
866 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
867 int join;
869 /* It is surprisingly complex to properly shutdown or exit the
870 valgrind process in which gdbserver has been invoked through
871 ptrace. In the normal case (gdb detaches from the process,
872 or process is continued), the valgrind process will reach the
873 breakpoint place. Using ptrace, vgdb will ensure the
874 previous activity of the process is resumed (e.g. restart a
875 blocking system call). The special case is when gdb asks the
876 valgrind process to exit (using either the "kill" command or
877 "monitor exit"). In such a case, the valgrind process will
878 call exit. But a ptraced process will be blocked in exit,
879 waiting for the ptracing process to detach or die. vgdb
880 cannot detach unconditionally as otherwise, in the normal
881 case, the valgrind process would stop abnormally with SIGSTOP
882 (as vgdb would not be there to catch it). vgdb can also not
883 die unconditionally otherwise again, similar problem. So, we
884 assume that most of the time, we arrive here in the normal
885 case, and so, the breakpoint has been encountered by the
886 valgrind process, so the invoker thread will exit and the
887 join will succeed. For the "kill" case, we cause an alarm
888 signal to be sent after a few seconds. This means that in the
889 normal case, the gdbserver code in valgrind process must have
890 returned the control in less than the alarm nr of seconds,
891 otherwise, valgrind will stop abnormally with SIGSTOP. */
892 (void) alarm(3);
894 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
895 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
896 if (join != 0)
897 XERROR
898 (join,
899 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
901 #if !defined(VGO_freebsd)
902 if (close(from_pid) != 0)
903 ERROR(errno, "close from_pid\n");
904 #endif
907 static
908 int tohex (int nib)
910 if (nib < 10)
911 return '0' + nib;
912 else
913 return 'a' + nib - 10;
916 /* Returns an allocated hex-decoded string from the buf. Stops decoding
917 at end of buf (zero) or when seeing the delim char. */
918 static
919 char *decode_hexstring (const char *buf, size_t prefixlen, size_t len)
921 int buflen;
922 char *buf_print;
924 if (len)
925 buflen = len;
926 else
927 buflen = strlen(buf) - prefixlen;
929 buf_print = vmalloc (buflen/2 + 1);
931 for (int i = 0; i < buflen; i = i + 2) {
932 buf_print[i/2] = ((fromhex(buf[i+prefixlen]) << 4)
933 + fromhex(buf[i+prefixlen+1]));
935 buf_print[buflen/2] = '\0';
936 DEBUG(1, "decode_hexstring: %s\n", buf_print);
937 return buf_print;
940 static Bool
941 write_to_gdb (const char *m, int cnt)
943 int written = 0;
944 while (written < cnt) {
945 int res = write (to_gdb, m + written, cnt - written);
946 if (res < 0) {
947 perror ("write_to_gdb");
948 return False;
950 written += res;
953 return True;
956 static Bool
957 write_checksum (const char *str)
959 unsigned char csum = 0;
960 int i = 0;
961 while (str[i] != 0)
962 csum += str[i++];
964 char p[2];
965 p[0] = tohex ((csum >> 4) & 0x0f);
966 p[1] = tohex (csum & 0x0f);
967 return write_to_gdb (p, 2);
970 static Bool
971 write_reply(const char *reply)
973 write_to_gdb ("$", 1);
974 write_to_gdb (reply, strlen (reply));
975 write_to_gdb ("#", 1);
976 return write_checksum (reply);
979 /* Creates a packet from a string message, caller needs to free. */
980 static char *
981 create_packet(const char *msg)
983 unsigned char csum = 0;
984 int i = 1;
985 char *p = vmalloc (strlen (msg) + 5); /* $ + msg + # + hexhex + 0 */
986 strcpy (&p[1], msg);
987 p[0] = '$';
988 while (p[i] != 0)
989 csum += p[i++];
990 p[i++] = '#';
991 p[i++] = tohex ((csum >> 4) & 0x0f);
992 p[i++] = tohex (csum & 0x0f);
993 p[i] = '\0';
994 return p;
997 static int read_one_char (char *c)
999 int i;
1001 i = read (from_gdb, c, 1);
1002 while (i == -1 && errno == EINTR);
1004 return i;
1007 static Bool
1008 send_packet(const char *reply, int noackmode)
1010 int ret;
1011 char c;
1013 send_packet_start:
1014 if (!write_reply(reply))
1015 return False;
1016 if (!noackmode) {
1017 // Look for '+' or '-'.
1018 // We must wait for "+" if !noackmode.
1019 do {
1020 ret = read_one_char(&c);
1021 if (ret <= 0)
1022 return False;
1023 // And if in !noackmode if we get "-" we should resent the packet.
1024 if (c == '-')
1025 goto send_packet_start;
1026 } while (c != '+');
1027 DEBUG(1, "sent packet to gdb got: %c\n",c);
1029 return True;
1032 // Reads one packet from_gdb starting with $ into buf.
1033 // Skipping any other characters.
1034 // Returns the size of the packet, 0 for end of input,
1035 // or -1 if no packet could be read.
1036 static int receive_packet(char *buf, int noackmode)
1038 int bufcnt = 0;
1039 int ret;
1040 char c;
1041 char c1 = '\0';
1042 char c2 = '\0';
1043 unsigned char csum = 0;
1045 // Look for first '$' (start of packet) or error.
1046 receive_packet_start:
1047 do {
1048 ret = read_one_char(&c);
1049 if (ret <= 0)
1050 return ret;
1051 } while (c != '$');
1053 // Found start of packet ('$')
1054 while (bufcnt < (PBUFSIZ+1)) {
1055 ret = read_one_char(&c);
1056 if (ret <= 0)
1057 return ret;
1058 if (c == '#') {
1059 if ((ret = read_one_char(&c1)) <= 0
1060 || (ret = read_one_char(&c2)) <= 0) {
1061 return ret;
1063 c1 = fromhex(c1);
1064 c2 = fromhex(c2);
1065 break;
1067 buf[bufcnt] = c;
1068 csum += buf[bufcnt];
1069 bufcnt++;
1072 // Packet complete, add terminator.
1073 buf[bufcnt] ='\0';
1075 if (!(csum == (c1 << 4) + c2)) {
1076 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1077 (c1 << 4) + c2, csum, buf);
1078 if (!noackmode)
1079 if (!write_to_gdb ("-", 1))
1080 return -1;
1081 /* Try again, gdb should resend the packet. */
1082 bufcnt = 0;
1083 csum = 0;
1084 goto receive_packet_start;
1087 if (!noackmode)
1088 if (!write_to_gdb ("+", 1))
1089 return -1;
1090 return bufcnt;
1093 // Returns a pointer to the char after the next delim char.
1094 static const char *next_delim_string (const char *buf, char delim)
1096 while (*buf) {
1097 if (*buf++ == delim)
1098 break;
1100 return buf;
1103 /* buf starts with the packet name followed by the delimiter, for example
1104 * vRun;2f62696e2f6c73, ";" is the delimiter here, or
1105 * qXfer:features:read:target.xml:0,1000, where the delimiter is ":".
1106 * The packet name is thrown away and the hex string is decoded and
1107 * is placed in decoded_string (the caller owns this and is responsible
1108 * for freeing it). */
1109 static int split_hexdecode(const char *buf, const char *string,
1110 const char *delim, char **decoded_string)
1112 const char *next_str = next_delim_string(buf, *delim);
1113 if (next_str) {
1114 *decoded_string = decode_hexstring (next_str, 0, 0);
1115 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string);
1116 return 1;
1117 } else {
1118 TSFPRINTF(stderr, "%s decoding error: finding the hex string in %s failed!\n", string, buf);
1119 return 0;
1123 static size_t count_delims(char delim, char *buf)
1125 size_t count = 0;
1126 char *ptr = buf;
1128 while (*ptr)
1129 count += *ptr++ == delim;
1130 return count;
1133 // Determine the length of the arguments.
1134 // This depends on the len array being initialized to -1 for each element.
1135 // We first skip the command (e.g. vRun;arg0;arg1)
1136 static void count_len(char delim, char *buf, size_t *len)
1138 int i = 0;
1139 char *ptr = buf;
1141 // Skip the command
1142 while (*ptr && *ptr != delim)
1143 ptr++;
1145 // Delimiter counts towards the first arg0
1146 if (*ptr == delim) {
1147 ptr++;
1148 len[i]++;
1151 // For each arg0... count chars (delim counts towards next arg)
1152 while (*ptr) {
1153 i += *ptr++ == delim;
1154 len[i]++;
1158 /* Declare here, will be used early, implementation follows later. */
1159 static void gdb_relay(int pid, int send_noack_mode, char *q_buf);
1161 /* Returns zero on success (and the pid of the valgrind process),
1162 or the errno from the child on failure. */
1163 static
1164 int fork_and_exec_valgrind (int argc, char **argv, const char *working_dir,
1165 int in_port, pid_t *pid)
1167 int err = 0;
1168 // We will use a pipe to track what the child does,
1169 // so we can report failure.
1170 int pipefd[2];
1171 #ifdef HAVE_PIPE2
1172 if (pipe2 (pipefd, O_CLOEXEC) == -1) {
1173 err = errno;
1174 perror ("pipe2 failed");
1175 return err;
1177 #else
1178 if (pipe (pipefd) == -1) {
1179 err = errno;
1180 perror ("pipe failed");
1181 return err;
1182 } else {
1183 if (fcntl (pipefd[0], F_SETFD, FD_CLOEXEC) == -1
1184 || fcntl (pipefd[1], F_SETFD, FD_CLOEXEC) == -1) {
1185 err = errno;
1186 perror ("fcntl failed");
1187 close (pipefd[0]);
1188 close (pipefd[1]);
1189 return err;
1192 #endif
1194 pid_t p = fork ();
1195 if (p < 0) {
1196 err = errno;
1197 perror ("fork failed");
1198 return err;
1199 } else if (p > 0) {
1200 // I am the parent (vgdb), p is the pid of the child (valgrind)
1201 // We only read from the child to see if everything is OK.
1202 // If the pipe closes, we get zero back, which is good.
1203 // An error reading the pipe is bad (and really shouldn't happen).
1204 // Otherwise the child sent us an errno code about what went wrong.
1205 close (pipefd[1]);
1207 while (err == 0) {
1208 int r = read (pipefd[0], &err, sizeof (int));
1209 if (r == 0) // end of file, good pipe closed after execve
1210 break;
1211 if (r == -1) {
1212 if (errno == EINTR)
1213 continue;
1214 else {
1215 err = errno;
1216 perror ("pipe read");
1221 close (pipefd[0]);
1222 if (err != 0)
1223 return err;
1224 else {
1225 *pid = p;
1226 return 0;
1228 } else {
1229 // p == 0, I am the child (will start valgrind)
1230 // We write success to the pipe, no need to read from it.
1231 close (pipefd[0]);
1233 if (working_dir != NULL && working_dir[0] != '\0') {
1234 if (chdir (working_dir) != 0) {
1235 err = errno;
1236 perror("chdir");
1237 // We try to write the result to the parent, but always exit.
1238 int written = 0;
1239 while (written < sizeof (int)) {
1240 int nrw = write (pipefd[1], &err, sizeof (int) - written);
1241 if (nrw == -1)
1242 break;
1243 written += nrw;
1245 _exit (-1);
1249 /* When in stdio mode (talking to gdb through stdin/stdout, not
1250 through a socket), redirect stdout to stderr and close stdin
1251 for the inferior. That way at least some output can be seen,
1252 but there will be no input. */
1253 if (in_port <= 0) {
1254 /* close stdin */
1255 close (0);
1256 /* open /dev/null as new stdin */
1257 open ("/dev/null", O_RDONLY);
1258 /* redirect stdout as stderr */
1259 dup2 (2, 1);
1262 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1263 can attach and --launched-with-multi to let valgrind know it doesn't
1264 need to show a banner how to connect to gdb, we will do that
1265 automagically. And add --vgdb-shadow-registers=yes to make shadow
1266 registers available by default. Add any other valgrind arguments the
1267 user gave with --vargs. Then the rest of the arguments to valgrind are
1268 the program to exec plus its arguments. */
1269 const int extra_vargs = 3;
1270 /* vargv[0] == "valgrind",
1271 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1272 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1273 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1274 vargs[arguments - 1] = NULL */
1275 int arguments = 1 + extra_vargs + cvargs + argc + 1;
1276 // We combine const and non-const char[]. This is mildly annoying
1277 // since we then need a char *const * for execvp. So we strdup the
1278 // const char*. Not pretty :{
1279 char **vargv = vmalloc (arguments * sizeof (char *));
1280 vargv[0] = strdup ("valgrind");
1281 vargv[1] = strdup ("--vgdb-error=0");
1282 vargv[2] = strdup ("--launched-with-multi=yes");
1283 vargv[3] = strdup ("--vgdb-shadow-registers=yes");
1284 // Add --vargs
1285 for (int i = 0; i < cvargs; i++) {
1286 vargv[i + extra_vargs + 1] = vargs[i];
1288 // Add command and args
1289 for (int i = 0; i < argc; i++) {
1290 vargv[i + extra_vargs + 1 + cvargs] = argv[i];
1292 vargv[arguments - 1] = NULL;
1294 if (!valgrind_path) {
1295 // TODO use execvpe (or something else if not on GNU/Linux
1296 /* We want to make a copy of the environ on start. When we
1297 get a QEnvironmentReset we copy that back. If we get an
1298 EvironSet/Add/Remove we update the copy. */
1299 execvp ("valgrind", vargv);
1301 else {
1302 vargv[0] = valgrind_path;
1303 execvp (vargv[0], vargv);
1306 // We really shouldn't get here...
1307 err = errno;
1308 /* Note we are after fork and exec failed, we cannot really call
1309 perror or printf in this situation since they aren't async-safe. */
1310 // perror ("execvp valgrind");
1311 // printf ("execve returned??? confusing: %d\n", res);
1312 // We try to write the result to the parent, but always exit.
1313 int written = 0;
1314 while (written < sizeof (int)) {
1315 int nrw = write (pipefd[1], &err, sizeof (int) - written);
1316 if (nrw == -1)
1317 break;
1318 written += nrw;
1320 _exit (-1);
1323 abort (); // Impossible
1326 /* Do multi stuff. */
1327 static
1328 void do_multi_mode(int check_trials, int in_port)
1330 char *buf = vmalloc(PBUFSIZ+1);
1331 char *q_buf = vmalloc(PBUFSIZ+1); //save the qSupported packet sent by gdb
1332 //to send it to the valgrind gdbserver later
1333 q_buf[0] = '\0';
1334 int noackmode = 0, pkt_size = 0, bad_unknown_packets = 0;
1335 char *string = NULL;
1336 char *working_dir = NULL;
1337 DEBUG(1, "doing multi stuff...\n");
1338 while (1){
1339 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1340 the pipe to gdb. */
1341 pkt_size = receive_packet(buf, noackmode);
1342 if (pkt_size <= 0) {
1343 DEBUG(1, "receive_packet: %d\n", pkt_size);
1344 break;
1347 DEBUG(1, "packet received: '%s'\n", buf);
1349 #define QSUPPORTED "qSupported:"
1350 #define STARTNOACKMODE "QStartNoAckMode"
1351 #define QRCMD "qRcmd" // This is the monitor command in gdb
1352 #define VRUN "vRun"
1353 #define XFER "qXfer"
1354 #define QATTACHED "qAttached"
1355 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1356 #define QENVIRONMENTRESET "QEnvironmentReset"
1357 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1358 #define QSETWORKINGDIR "QSetWorkingDir"
1359 #define QTSTATUS "qTStatus"
1361 if (strncmp(QSUPPORTED, buf, strlen(QSUPPORTED)) == 0) {
1362 DEBUG(1, "CASE %s\n", QSUPPORTED);
1363 // And here is our reply.
1364 // XXX error handling? We don't check the arguments.
1365 char *reply;
1366 strcpy(q_buf, buf);
1367 // Keep this in sync with coregrind/m_gdbserver/server.c
1368 if (asprintf (&reply,
1369 "PacketSize=%x;"
1370 "QStartNoAckMode+;"
1371 "QPassSignals+;"
1372 "QCatchSyscalls+;"
1373 /* Just report support always. */
1374 "qXfer:auxv:read+;"
1375 /* We'll force --vgdb-shadow-registers=yes */
1376 "qXfer:features:read+;"
1377 "qXfer:exec-file:read+;"
1378 "qXfer:siginfo:read+;"
1379 /* Extra vgdb support before valgrind starts up. */
1380 "QEnvironmentHexEncoded+;"
1381 "QEnvironmentReset+;"
1382 "QEnvironmentUnset+;"
1383 "QSetWorkingDir+", (UInt)PBUFSIZ - 1) != -1) {
1384 send_packet(reply, noackmode);
1385 free (reply);
1386 } else {
1387 XERROR(errno, "asprintf failed\n");
1390 else if (strncmp(STARTNOACKMODE, buf, strlen(STARTNOACKMODE)) == 0) {
1391 // We have to ack this one
1392 send_packet("OK", 0);
1393 noackmode = 1;
1395 else if (buf[0] == '!') {
1396 send_packet("OK", noackmode);
1398 else if (buf[0] == '?') {
1399 send_packet("W00", noackmode);
1401 else if (strncmp("H", buf, strlen("H")) == 0) {
1402 // Set thread packet, but we are not running yet.
1403 send_packet("E01", noackmode);
1405 else if (strncmp("vMustReplyEmpty", buf, strlen("vMustReplyEmpty")) == 0) {
1406 send_packet ("", noackmode);
1408 else if (strncmp(QRCMD, buf, strlen(QRCMD)) == 0) {
1409 send_packet ("No running target, monitor commands not available yet.", noackmode);
1411 char *decoded_string = decode_hexstring (buf, strlen (QRCMD) + 1, 0);
1412 DEBUG(1, "qRcmd decoded: %s\n", decoded_string);
1413 free (decoded_string);
1415 else if (strncmp(VRUN, buf, strlen(VRUN)) == 0) {
1416 // vRun;filename[;argument]*
1417 // vRun, filename and arguments are split on ';',
1418 // no ';' at the end.
1419 // If there are no arguments count is one (just the filename).
1420 // Otherwise it is the number of arguments plus one (the filename).
1421 // The filename must be there and starts after the first ';'.
1422 // TODO: Handle vRun;[;argument]*
1423 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1424 // If filename is an empty string, the stub may use a default program
1425 // (e.g. the last program run).
1426 size_t count = count_delims(';', buf);
1427 size_t *len = vmalloc(count * sizeof(count));
1428 const char *delim = ";";
1429 const char *next_str = next_delim_string(buf, *delim);
1430 char **decoded_string = vmalloc(count * sizeof (char *));
1432 // Count the lenghts of each substring, init to -1 to compensate for
1433 // each substring starting with a delim char.
1434 for (size_t i = 0; i < count; i++)
1435 len[i] = -1;
1436 count_len(';', buf, len);
1437 if (next_str) {
1438 DEBUG(1, "vRun: next_str %s\n", next_str);
1439 for (size_t i = 0; i < count; i++) {
1440 /* Handle the case when the arguments
1441 * was specified to gdb's run command
1442 * but no remote exec-file was set,
1443 * so the first vRun argument is missing.
1444 * For example vRun;;6c. */
1445 if (*next_str == *delim) {
1446 next_str++;
1447 /* empty string that can be freed. */
1448 decoded_string[i] = strdup("");
1450 else {
1451 decoded_string[i] = decode_hexstring (next_str, 0, len[i]);
1452 if (i < count - 1)
1453 next_str = next_delim_string(next_str, *delim);
1455 DEBUG(1, "vRun decoded: %s, next_str %s, len[%zu] %zu\n",
1456 decoded_string[i], next_str, i, len[i]);
1459 /* If we didn't get any arguments or the filename is an empty
1460 string, valgrind won't know which program to run. */
1461 DEBUG (1, "count: %zu, len[0]: %zu\n", count, len[0]);
1462 if (! count || len[0] == 0) {
1463 free(len);
1464 for (size_t i = 0; i < count; i++)
1465 free (decoded_string[i]);
1466 free (decoded_string);
1467 send_packet ("E01", noackmode);
1468 continue;
1471 /* We have collected the decoded strings so we can use them to
1472 launch valgrind with the correct arguments... We then use the
1473 valgrind pid to start relaying packets. */
1474 pid_t valgrind_pid = -1;
1475 int res = fork_and_exec_valgrind ((int)count,
1476 decoded_string,
1477 working_dir,
1478 in_port,
1479 &valgrind_pid);
1481 if (res == 0) {
1482 // Lets report we Stopped with SIGTRAP (05).
1483 send_packet ("S05", noackmode);
1484 prepare_fifos_and_shared_mem(valgrind_pid, check_trials);
1485 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n",
1486 from_gdb_to_pid, to_gdb_from_pid);
1487 // gdb_relay is an endless loop till valgrind quits.
1488 shutting_down = False;
1490 gdb_relay (valgrind_pid, 1, q_buf);
1491 cleanup_fifos_and_shared_mem();
1492 DEBUG(1, "valgrind relay done\n");
1493 int status;
1494 pid_t p = waitpid (valgrind_pid, &status, 0);
1495 DEBUG(2, "waitpid: %d\n", (int) p);
1496 if (p == -1)
1497 DEBUG(1, "waitpid error %s\n", strerror (errno));
1498 else {
1499 if (WIFEXITED(status))
1500 DEBUG(1, "valgrind exited with %d\n",
1501 WEXITSTATUS(status));
1502 else if (WIFSIGNALED(status))
1503 DEBUG(1, "valgrind kill by signal %d\n",
1504 WTERMSIG(status));
1505 else
1506 DEBUG(1, "valgrind unexpectedly stopped or continued");
1508 } else {
1509 send_packet ("E01", noackmode);
1510 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1511 strerror (res));
1514 free(len);
1515 for (int i = 0; i < count; i++)
1516 free (decoded_string[i]);
1517 free (decoded_string);
1518 } else {
1519 free(len);
1520 send_packet ("E01", noackmode);
1521 DEBUG(1, "vRun decoding error: no next_string!\n");
1522 continue;
1524 } else if (strncmp(QATTACHED, buf, strlen(QATTACHED)) == 0) {
1525 send_packet ("1", noackmode);
1526 DEBUG(1, "qAttached sent: '1'\n");
1527 const char *next_str = next_delim_string(buf, ':');
1528 if (next_str) {
1529 char *decoded_string = decode_hexstring (next_str, 0, 0);
1530 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string, next_str);
1531 free (decoded_string);
1532 } else {
1533 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf);
1534 continue;
1536 } /* Reset the state of environment variables in the remote target
1537 before starting the inferior. In this context, reset means
1538 unsetting all environment variables that were previously set
1539 by the user (i.e., were not initially present in the environment). */
1540 else if (strncmp(QENVIRONMENTRESET, buf,
1541 strlen(QENVIRONMENTRESET)) == 0) {
1542 send_packet ("OK", noackmode);
1543 // TODO clear all environment strings. We're not using
1544 // environment strings now. But we should.
1545 } else if (strncmp(QENVIRONMENTHEXENCODED, buf,
1546 strlen(QENVIRONMENTHEXENCODED)) == 0) {
1547 send_packet ("OK", noackmode);
1548 if (!split_hexdecode(buf, QENVIRONMENTHEXENCODED, ":", &string))
1549 break;
1550 // TODO Collect all environment strings and add them to environ
1551 // before launching valgrind.
1552 free (string);
1553 string = NULL;
1554 } else if (strncmp(QENVIRONMENTUNSET, buf,
1555 strlen(QENVIRONMENTUNSET)) == 0) {
1556 send_packet ("OK", noackmode);
1557 if (!split_hexdecode(buf, QENVIRONMENTUNSET, ":", &string))
1558 break;
1559 // TODO Remove this environment string from the collection.
1560 free (string);
1561 string = NULL;
1562 } else if (strncmp(QSETWORKINGDIR, buf,
1563 strlen(QSETWORKINGDIR)) == 0) {
1564 // Silly, but we can only reply OK, even if the working directory is
1565 // bad. Errors will be reported when we try to execute the actual
1566 // process.
1567 send_packet ("OK", noackmode);
1568 // Free any previously set working_dir
1569 free (working_dir);
1570 working_dir = NULL;
1571 if (!split_hexdecode(buf, QSETWORKINGDIR, ":", &working_dir)) {
1572 continue; // We cannot report the error to gdb...
1574 DEBUG(1, "set working dir to: %s\n", working_dir);
1575 } else if (strncmp(XFER, buf, strlen(XFER)) == 0) {
1576 char *buf_dup = strdup(buf);
1577 DEBUG(1, "strdup: buf_dup %s\n", buf_dup);
1578 if (buf_dup) {
1579 const char *delim = ":";
1580 size_t count = count_delims(delim[0], buf);
1581 if (count < 4) {
1582 strsep(&buf_dup, delim);
1583 strsep(&buf_dup, delim);
1584 strsep(&buf_dup, delim);
1585 char *decoded_string = decode_hexstring (buf_dup, 0, 0);
1586 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string, buf_dup);
1587 free (decoded_string);
1589 free (buf_dup);
1590 } else {
1591 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf);
1592 free (buf_dup);
1593 continue;
1595 // Whether we could decode it or not, we cannot handle it now. We
1596 // need valgrind gdbserver to properly reply. So error out here.
1597 send_packet ("E00", noackmode);
1598 } else if (strncmp(QTSTATUS, buf, strlen(QTSTATUS)) == 0) {
1599 // We don't support trace experiments
1600 DEBUG(1, "Got QTSTATUS\n");
1601 send_packet ("", noackmode);
1602 } else if (strcmp("qfThreadInfo", buf) == 0) {
1603 DEBUG(1, "Got qfThreadInfo\n");
1604 /* There are no threads yet, reply 'l' end of list. */
1605 send_packet ("l", noackmode);
1606 } else if (buf[0] != '\0') {
1607 // We didn't understand.
1608 DEBUG(1, "Unknown packet received: '%s'\n", buf);
1609 bad_unknown_packets++;
1610 if (bad_unknown_packets > 10) {
1611 DEBUG(1, "Too many bad/unknown packets received\n");
1612 break;
1614 send_packet ("", noackmode);
1617 DEBUG(1, "done doing multi stuff...\n");
1618 free(working_dir);
1619 free(buf);
1620 free(q_buf);
1622 shutting_down = True;
1623 close (to_gdb);
1624 close (from_gdb);
1627 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1628 encountered. q_buf is the qSupported packet received from gdb. */
1629 static
1630 void gdb_relay(int pid, int send_noack_mode, char *q_buf)
1632 int from_pid = -1; /* fd to read from pid */
1633 int to_pid = -1; /* fd to write to pid */
1635 int shutdown_loop = 0;
1636 TSFPRINTF(stderr, "relaying data between gdb and process %d\n", pid);
1638 if (max_invoke_ms > 0)
1639 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1640 invoke_gdbserver_in_valgrind, (void *) &pid);
1641 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1642 acquire_lock(shared_mem_fd, pid);
1644 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
1645 "read mode from pid");
1647 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1649 Bool waiting_for_noack_mode = False;
1650 Bool waiting_for_qsupported = False;
1651 if(send_noack_mode) {
1652 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid, from_pid);
1653 write_buf(to_pid, "$QStartNoAckMode#b0", 19,
1654 "write start no ack mode",
1655 /* notify */ True);
1656 waiting_for_noack_mode = True;
1659 while (1) {
1660 ConnectionKind ck;
1661 int ret;
1662 struct pollfd pollfds[NumConnectionKind];
1664 /* watch data written by gdb, watch POLLERR on both gdb fd */
1665 pollfds[FROM_GDB].fd = from_gdb;
1666 pollfds[FROM_GDB].events = POLLIN;
1667 pollfds[FROM_GDB].revents = 0;
1668 pollfds[TO_GDB].fd = to_gdb;
1669 pollfds[TO_GDB].events = 0;
1670 pollfds[TO_GDB].revents = 0;
1672 /* watch data written by pid, watch POLLERR on both pid fd */
1673 pollfds[FROM_PID].fd = from_pid;
1674 pollfds[FROM_PID].events = POLLIN;
1675 pollfds[FROM_PID].revents = 0;
1676 pollfds[TO_PID].fd = to_pid;
1677 pollfds[TO_PID].events = 0;
1678 pollfds[TO_PID].revents = 0;
1680 ret = poll(pollfds,
1681 NumConnectionKind,
1682 (shutting_down ?
1683 1 /* one second */
1684 : -1 /* infinite */));
1685 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1687 /* check for unexpected error */
1688 if (ret <= 0 && errno != EINTR) {
1689 ERROR(errno, "unexpected poll ret %d\n", ret);
1690 shutting_down = True;
1691 break;
1694 /* check for data to read */
1695 for (ck = 0; ck < NumConnectionKind; ck ++) {
1696 if (pollfds[ck].revents & POLLIN) {
1697 switch (ck) {
1698 case FROM_GDB:
1699 if (waiting_for_noack_mode || waiting_for_qsupported)
1700 break; /* Don't add any messages while vgdb is talking. */
1701 if (!read_from_gdb_write_to_pid(to_pid))
1702 shutting_down = True;
1703 break;
1704 case FROM_PID:
1705 // First handle any messages from vgdb
1706 if (waiting_for_noack_mode) {
1707 char buf[PBUFSIZ+1]; // +1 for trailing \0
1708 size_t buflen;
1709 buflen = getpkt(buf, from_pid, to_pid);
1710 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1711 if (buflen != 2)
1712 ERROR(0, "no ack mode: unexpected buflen %zu, buf %s\n",
1713 buflen, buf);
1714 else
1715 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1717 waiting_for_noack_mode = False;
1719 /* Propagate qSupported to valgrind, we already replied. */
1720 if (q_buf != NULL && q_buf[0] != '\0') {
1721 char *pkt = create_packet (q_buf);
1722 write_buf(to_pid, pkt, strlen(pkt),
1723 "write qSupported", /* notify */ True);
1724 free(pkt);
1725 waiting_for_qsupported = True;
1727 } else if (waiting_for_qsupported) {
1728 char buf[PBUFSIZ+1]; // +1 for trailing \0
1729 size_t buflen;
1730 buflen = getpkt(buf, from_pid, to_pid);
1731 /* Should we sanity check the result? */
1732 if (buflen > 0) {
1733 waiting_for_qsupported = False;
1734 } else {
1735 ERROR(0, "Unexpected getpkt for qSupported reply: %zu\n",
1736 buflen);
1738 } else if (!read_from_pid_write_to_gdb(from_pid))
1739 shutting_down = True;
1740 break;
1741 default: XERROR(0, "unexpected POLLIN on %s\n",
1742 ppConnectionKind(ck));
1747 /* check for an fd being in error condition */
1748 for (ck = 0; ck < NumConnectionKind; ck ++) {
1749 if (pollfds[ck].revents & POLLERR) {
1750 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1751 ppConnectionKind(ck), pollfds[ck].fd);
1752 invoker_valgrind_dying();
1753 shutting_down = True;
1755 if (pollfds[ck].revents & POLLHUP) {
1756 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1757 ppConnectionKind(ck), pollfds[ck].fd);
1758 invoker_valgrind_dying();
1759 shutting_down = True;
1761 if (pollfds[ck].revents & POLLNVAL) {
1762 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1763 ppConnectionKind(ck), pollfds[ck].fd);
1764 invoker_valgrind_dying();
1765 shutting_down = True;
1769 if (shutting_down) {
1770 /* we let some time to the final packets to be transferred */
1771 shutdown_loop++;
1772 if (shutdown_loop > 3)
1773 break;
1776 close_connection(to_pid, from_pid);
1779 static int packet_len_for_command(char *cmd)
1781 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1782 return 7+ 2*strlen(cmd) +3 + 1;
1785 /* hyper-minimal protocol implementation that
1786 sends the provided commands (using qRcmd packets)
1787 and read and display their replies. */
1788 static
1789 void standalone_send_commands(int pid,
1790 int last_command,
1791 char *commands[] )
1793 int from_pid = -1; /* fd to read from pid */
1794 int to_pid = -1; /* fd to write to pid */
1796 int i;
1797 int hi;
1798 char hex[3];
1799 unsigned char cksum;
1800 char *hexcommand;
1801 char buf[PBUFSIZ+1]; // +1 for trailing \0
1802 int buflen;
1803 int nc;
1806 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
1807 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1808 invoke_gdbserver_in_valgrind, (void *) &pid);
1810 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1811 acquire_lock(shared_mem_fd, pid);
1813 /* first send a C-c \003 to pid, so that it wakes up the process
1814 After that, we can open the fifo from the pid in read mode
1815 We then start to wait for packets (normally first a resume reply)
1816 At that point, we send our command and expect replies */
1817 buf[0] = '\003';
1818 i = 0;
1819 while (!write_buf(to_pid, buf, 1,
1820 "write \\003 to wake up", /* notify */ True)) {
1821 /* If write fails, retries up to 10 times every 0.5 seconds
1822 This aims at solving the race condition described in
1823 remote-utils.c remote_finish function. */
1824 usleep(500*1000);
1825 i++;
1826 if (i >= 10)
1827 XERROR(errno, "failed to send wake up char after 10 trials\n");
1829 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1830 "read cmd result from pid");
1832 /* Enable no ack mode. */
1833 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1834 /* notify */ True);
1835 buflen = getpkt(buf, from_pid, to_pid);
1836 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1837 if (buflen != 2)
1838 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen);
1839 else
1840 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1843 for (nc = 0; nc <= last_command; nc++) {
1844 TSFPRINTF(stderr, "sending command %s to pid %d\n", commands[nc], pid);
1846 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1847 hexcommand = vmalloc(packet_len_for_command(commands[nc]));
1848 hexcommand[0] = 0;
1849 strcat(hexcommand, "$qRcmd,");
1850 for (i = 0; i < strlen(commands[nc]); i++) {
1851 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
1852 // Need to use unsigned char, to avoid sign extension.
1853 strcat(hexcommand, hex);
1855 /* checksum (but without the $) */
1856 cksum = 0;
1857 for (hi = 1; hi < strlen(hexcommand); hi++)
1858 cksum+=hexcommand[hi];
1859 strcat(hexcommand, "#");
1860 sprintf(hex, "%02x", cksum);
1861 strcat(hexcommand, hex);
1862 write_buf(to_pid, hexcommand, strlen(hexcommand),
1863 "writing hex command to pid", /* notify */ True);
1865 /* we exit of the below loop explicitly when the command has
1866 been handled or because a signal handler will set
1867 shutting_down. */
1868 while (!shutting_down) {
1869 buflen = getpkt(buf, from_pid, to_pid);
1870 if (buflen < 0) {
1871 ERROR(0, "error reading packet\n");
1872 if (buflen == -2)
1873 invoker_valgrind_dying();
1874 break;
1876 if (strlen(buf) == 0) {
1877 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1878 break;
1880 if (strcmp(buf, "OK") == 0) {
1881 DEBUG(1, "OK packet rcvd\n");
1882 break;
1884 if (buf[0] == 'E') {
1885 DEBUG(0,
1886 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1887 buf);
1888 break;
1890 if (buf[0] == 'W') {
1891 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1892 break;
1894 if (buf[0] == 'T') {
1895 DEBUG(1, "T resume reply packet received: %s\n", buf);
1896 continue;
1899 /* must be here an O packet with hex encoded string reply
1900 => decode and print it */
1901 if (buf[0] != 'O') {
1902 DEBUG(0, "expecting O packet, received: %s\n", buf);
1903 continue;
1906 char buf_print[buflen/2 + 1];
1907 for (i = 1; i < buflen; i = i + 2)
1908 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1909 + fromhex(*(buf+i+1));
1910 buf_print[buflen/2] = 0;
1911 printf("%s", buf_print);
1912 fflush(stdout);
1915 free(hexcommand);
1917 shutting_down = True;
1919 close_connection(to_pid, from_pid);
1922 /* report to user the existence of a vgdb-able valgrind process
1923 with given pid.
1924 Note: this function does not use XERROR if an error is encountered
1925 while producing the command line for pid, as this is not critical
1926 and at least on MacOS, reading cmdline is not available. */
1927 static
1928 void report_pid(int pid, Bool on_stdout)
1930 char cmdline_file[50]; // large enough
1931 int fd, i;
1932 FILE *out = on_stdout ? stdout : stderr;
1934 TSFPRINTF(out, "use --pid=%d for ", pid);
1936 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1937 fd = open(cmdline_file, O_RDONLY | O_CLOEXEC);
1938 if (fd == -1) {
1939 DEBUG(1, "error opening cmdline file %s %s\n",
1940 cmdline_file, strerror(errno));
1941 fprintf(out, "(could not open process command line)\n");
1942 } else {
1943 char cmdline[100];
1944 ssize_t sz;
1945 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) > 0) {
1946 for (i = 0; i < sz; i++)
1947 if (cmdline[i] == 0)
1948 cmdline[i] = ' ';
1949 cmdline[sz] = 0;
1950 fprintf(out, "%s", cmdline);
1952 if (sz == -1) {
1953 DEBUG(1, "error reading cmdline file %s %s\n",
1954 cmdline_file, strerror(errno));
1955 fprintf(out, "(error reading process command line)");
1957 fprintf(out, "\n");
1958 close(fd);
1960 fflush(out);
1963 static
1964 void usage(void)
1966 fprintf(stderr,
1967 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1968 "vgdb (valgrind gdb) has two usages\n"
1969 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1970 " The OPTION(s) must be followed by the command to send\n"
1971 " To send more than one command, separate the commands with -c\n"
1972 " 2. relay application between gdb and a Valgrind gdbserver.\n"
1973 " Only OPTION(s) can be given.\n"
1974 "\n"
1975 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1976 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
1977 " [--port=<portnr>\n"
1978 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
1979 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
1980 " \n"
1981 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1982 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1983 " if you want to change the prefix (default %s) for the FIFOs communication\n"
1984 " between the Valgrind gdbserver and vgdb.\n"
1985 " --wait (default 0) tells vgdb to check during the specified number\n"
1986 " of seconds if a Valgrind gdbserver can be found.\n"
1987 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1988 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1989 " process is blocked in a system call).\n"
1990 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
1991 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1992 " gdbserver has not processed a command after number seconds\n"
1993 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
1994 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
1995 " --vargs everything that follows is an argument for valgrind.\n"
1996 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1997 " -T arg tells to add timestamps to vgdb information messages.\n"
1998 " -D arg tells to show shared mem status and then exit.\n"
1999 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
2000 "\n"
2001 " -h --help shows this message\n"
2002 #ifdef VG_GDBSCRIPTS_DIR
2003 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
2004 #endif
2005 " To get help from the Valgrind gdbserver, use vgdb help\n"
2006 "\n", vgdb_prefix_default()
2007 #ifdef VG_GDBSCRIPTS_DIR
2008 , VG_GDBSCRIPTS_DIR "/valgrind-monitor.py"
2009 #endif
2011 invoker_restrictions_msg();
2014 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
2015 and then exits.
2017 else if arg_pid == -1, waits maximum check_trials seconds to discover
2018 a valgrind pid appearing.
2020 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2021 with gdbserver activated.
2023 Returns the pid to work with
2024 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2026 static
2027 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
2029 int i;
2030 int pid = -1;
2032 if (arg_pid == 0 || arg_pid < -1) {
2033 TSFPRINTF(stderr, "vgdb error: invalid pid %d given\n", arg_pid);
2034 exit(1);
2035 } else {
2036 /* search for a matching named fifo.
2037 If we have been given a pid, we will check that the matching FIFO is
2038 there (or wait the nr of check_trials for this to appear).
2039 If no pid has been given, then if we find only one FIFO,
2040 we will use this to build the pid to use.
2041 If we find multiple processes with valid FIFO, we report them and will
2042 exit with an error. */
2043 DIR *vgdb_dir;
2044 char *vgdb_dir_name = vmalloc(strlen (vgdb_prefix) + 3);
2045 struct dirent *f;
2046 int is;
2047 int nr_valid_pid = 0;
2048 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
2049 char *vgdb_format = vmalloc(strlen(vgdb_prefix) + strlen(suffix) + 1);
2051 strcpy(vgdb_format, vgdb_prefix);
2052 strcat(vgdb_format, suffix);
2054 if (strchr(vgdb_prefix, '/') != NULL) {
2055 strcpy(vgdb_dir_name, vgdb_prefix);
2056 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
2057 if (vgdb_dir_name[is] == '/') {
2058 vgdb_dir_name[is+1] = '\0';
2059 break;
2061 } else {
2062 strcpy(vgdb_dir_name, "");
2065 DEBUG(1, "searching pid in directory %s format %s\n",
2066 vgdb_dir_name, vgdb_format);
2068 /* try to find FIFOs with valid pid.
2069 On exit of the loop, pid is set to:
2070 the last pid found if show_list (or -1 if no process was listed)
2071 -1 if no FIFOs matching a running process is found
2072 -2 if multiple FIFOs of running processes are found
2073 otherwise it is set to the (only) pid found that can be debugged
2075 for (i = 0; i < check_trials; i++) {
2076 DEBUG(1, "check_trial %d \n", i);
2077 if (i > 0)
2078 /* wait one second before checking again */
2079 sleep(1);
2081 vgdb_dir = opendir(strlen(vgdb_dir_name) ? vgdb_dir_name : "./");
2082 if (vgdb_dir == NULL)
2083 XERROR(errno,
2084 "vgdb error: opening directory %s searching vgdb fifo\n",
2085 vgdb_dir_name);
2087 errno = 0; /* avoid complain if vgdb_dir is empty */
2088 while ((f = readdir(vgdb_dir))) {
2089 struct stat st;
2090 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
2091 char *wrongpid;
2092 int newpid;
2094 strcpy(pathname, vgdb_dir_name);
2095 strcat(pathname, f->d_name);
2096 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
2097 if (stat(pathname, &st) != 0) {
2098 if (debuglevel >= 3)
2099 ERROR(errno, "vgdb error: stat %s searching vgdb fifo\n",
2100 pathname);
2101 } else if (S_ISFIFO(st.st_mode)) {
2102 DEBUG(3, "trying FIFO %s\n", pathname);
2103 if (strncmp(pathname, vgdb_format,
2104 strlen(vgdb_format)) == 0) {
2105 newpid = strtol(pathname + strlen(vgdb_format),
2106 &wrongpid, 10);
2107 if (*wrongpid == '-' && newpid > 0
2108 && kill(newpid, 0) == 0) {
2109 nr_valid_pid++;
2110 if (show_list) {
2111 report_pid(newpid, /*on_stdout*/ True);
2112 pid = newpid;
2113 } else if (arg_pid != -1) {
2114 if (arg_pid == newpid) {
2115 pid = newpid;
2117 } else if (nr_valid_pid > 1) {
2118 if (nr_valid_pid == 2) {
2119 TSFPRINTF
2120 (stderr,
2121 "no --pid= arg given"
2122 " and multiple valgrind pids found:\n");
2123 report_pid(pid, /*on_stdout*/ False);
2125 pid = -2;
2126 report_pid(newpid, /*on_stdout*/ False);
2127 } else {
2128 pid = newpid;
2133 errno = 0; /* avoid complain if at the end of vgdb_dir */
2135 if (f == NULL && errno != 0)
2136 XERROR(errno, "vgdb error: reading directory %s for vgdb fifo\n",
2137 vgdb_dir_name);
2139 closedir(vgdb_dir);
2140 if (pid != -1)
2141 break;
2144 free(vgdb_dir_name);
2145 free(vgdb_format);
2148 if (show_list) {
2149 exit(1);
2150 } else if (pid == -1) {
2151 if (arg_pid == -1)
2152 TSFPRINTF(stderr, "vgdb error: no FIFO found and no pid given\n");
2153 else
2154 TSFPRINTF(stderr, "vgdb error: no FIFO found matching pid %d\n",
2155 arg_pid);
2156 exit(1);
2158 else if (pid == -2) {
2159 /* no arg_pid given, multiple FIFOs found */
2160 exit(1);
2162 else {
2163 return pid;
2167 /* return true if the numeric value of an option of the
2168 form --xxxxxxxxx=<number> could properly be extracted
2169 from arg. If True is returned, *value contains the
2170 extracted value.*/
2171 static
2172 Bool numeric_val(char* arg, int *value)
2174 const char *eq_pos = strchr(arg, '=');
2175 char *wrong;
2176 long long int long_value;
2178 if (eq_pos == NULL)
2179 return False;
2181 long_value = strtoll(eq_pos+1, &wrong, 10);
2182 if (long_value < 0 || long_value > INT_MAX)
2183 return False;
2184 if (*wrong)
2185 return False;
2187 *value = (int) long_value;
2188 return True;
2191 /* true if arg matches the provided option */
2192 static
2193 Bool is_opt(char* arg, const char *option)
2195 int option_len = strlen(option);
2196 if (option[option_len-1] == '=')
2197 return (0 == strncmp(option, arg, option_len));
2198 else
2199 return (0 == strcmp(option, arg));
2202 /* Parse command lines options. If error(s), exits.
2203 Otherwise returns the options in *p_... args.
2204 commands must be big enough for the commands extracted from argv.
2205 On return, *p_last_command gives the position in commands where
2206 the last command has been allocated (using vmalloc). */
2207 static
2208 void parse_options(int argc, char** argv,
2209 Bool *p_show_shared_mem,
2210 Bool *p_show_list,
2211 Bool *p_multi_mode,
2212 int *p_arg_pid,
2213 int *p_check_trials,
2214 int *p_port,
2215 int *p_last_command,
2216 char *commands[])
2218 Bool show_shared_mem = False;
2219 Bool show_list = False;
2220 Bool multi_mode = False;
2221 int arg_pid = -1;
2222 int check_trials = 1;
2223 int last_command = -1;
2224 int int_port = 0;
2226 int i;
2227 int arg_errors = 0;
2229 for (i = 1; i < argc; i++) {
2230 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2231 usage();
2232 exit(0);
2233 } else if (is_opt(argv[i], "-d")) {
2234 debuglevel++;
2235 } else if (is_opt(argv[i], "-D")) {
2236 show_shared_mem = True;
2237 } else if (is_opt(argv[i], "-l")) {
2238 show_list = True;
2239 } else if (is_opt(argv[i], "--multi")) {
2240 multi_mode = True;
2241 } else if (is_opt(argv[i], "-T")) {
2242 timestamp = True;
2243 } else if (is_opt(argv[i], "--pid=")) {
2244 int newpid;
2245 if (!numeric_val(argv[i], &newpid)) {
2246 TSFPRINTF(stderr, "invalid --pid argument %s\n", argv[i]);
2247 arg_errors++;
2248 } else if (arg_pid != -1) {
2249 TSFPRINTF(stderr, "multiple --pid arguments given\n");
2250 arg_errors++;
2251 } else {
2252 arg_pid = newpid;
2254 } else if (is_opt(argv[i], "--wait=")) {
2255 if (!numeric_val(argv[i], &check_trials)) {
2256 TSFPRINTF(stderr, "invalid --wait argument %s\n", argv[i]);
2257 arg_errors++;
2259 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2260 if (!numeric_val(argv[i], &max_invoke_ms)) {
2261 TSFPRINTF(stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
2262 arg_errors++;
2264 } else if (is_opt(argv[i], "--cmd-time-out=")) {
2265 if (!numeric_val(argv[i], &cmd_time_out)) {
2266 TSFPRINTF(stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
2267 arg_errors++;
2269 } else if (is_opt(argv[i], "--port=")) {
2270 if (!numeric_val(argv[i], &int_port)) {
2271 TSFPRINTF(stderr, "invalid --port argument %s\n", argv[i]);
2272 arg_errors++;
2274 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2275 if (vgdb_prefix) {
2276 // was specified more than once on the command line
2277 // ignore earlier uses
2278 free(vgdb_prefix);
2280 vgdb_prefix = strdup (argv[i] + 14);
2281 } else if (is_opt(argv[i], "--valgrind=")) {
2282 char *path = argv[i] + 11;
2283 /* Compute the absolute path. */
2284 valgrind_path = realpath(path, NULL);
2285 if (!valgrind_path) {
2286 TSFPRINTF(stderr, "%s is not a correct path. %s, exiting.\n",
2287 path, strerror (errno));
2288 exit(1);
2290 DEBUG(2, "valgrind's real path: %s\n", valgrind_path);
2291 } else if (is_opt(argv[i], "--vargs")) {
2292 // Everything that follows now is an argument for valgrind
2293 // No other options (or commands) can follow
2294 // argc - i is the number of left over arguments
2295 // allocate enough space, put all args in it.
2296 cvargs = argc - i - 1;
2297 vargs = vmalloc (cvargs * sizeof(vargs));
2298 i++;
2299 for (int j = 0; i < argc; i++) {
2300 vargs[j] = argv[i];
2301 j++;
2303 } else if (is_opt(argv[i], "-c")) {
2304 last_command++;
2305 commands[last_command] = vmalloc(1);
2306 commands[last_command][0] = '\0';
2307 } else if (0 == strncmp(argv[i], "-", 1)) {
2308 TSFPRINTF(stderr, "unknown or invalid argument %s\n", argv[i]);
2309 arg_errors++;
2310 } else {
2311 int len;
2312 if (last_command == -1) {
2313 /* only one command, no -c command indicator */
2314 last_command++;
2315 commands[last_command] = vmalloc(1);
2316 commands[last_command][0] = '\0';
2318 len = strlen(commands[last_command]);
2319 commands[last_command] = vrealloc(commands[last_command],
2320 len + 1 + strlen(argv[i]) + 1);
2321 if (len > 0)
2322 strcat(commands[last_command], " ");
2323 strcat(commands[last_command], argv[i]);
2324 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2325 TSFPRINTF(stderr, "command %s too long\n", commands[last_command]);
2326 arg_errors++;
2332 if (vgdb_prefix == NULL)
2333 vgdb_prefix = vgdb_prefix_default();
2335 if (multi_mode
2336 && (show_shared_mem
2337 || show_list
2338 || last_command != -1)) {
2339 arg_errors++;
2340 TSFPRINTF(stderr,
2341 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2344 if (isatty(0)
2345 && !show_shared_mem
2346 && !show_list
2347 && int_port == 0
2348 && last_command == -1) {
2349 arg_errors++;
2350 TSFPRINTF(stderr,
2351 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2354 if (show_shared_mem && show_list) {
2355 arg_errors++;
2356 TSFPRINTF(stderr,
2357 "Can't use both -D and -l options\n");
2360 if (max_invoke_ms > 0
2361 && cmd_time_out != NEVER
2362 && (cmd_time_out * 1000) <= max_invoke_ms) {
2363 arg_errors++;
2364 TSFPRINTF(stderr,
2365 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2368 if (show_list && arg_pid != -1) {
2369 arg_errors++;
2370 TSFPRINTF(stderr,
2371 "Can't use both --pid and -l options\n");
2374 if (int_port > 0 && last_command != -1) {
2375 arg_errors++;
2376 TSFPRINTF(stderr,
2377 "Can't use --port to send commands\n");
2380 if (arg_errors > 0) {
2381 TSFPRINTF(stderr, "args error. Try `vgdb --help` for more information\n");
2382 exit(1);
2385 *p_show_shared_mem = show_shared_mem;
2386 *p_show_list = show_list;
2387 *p_multi_mode = multi_mode;
2388 *p_arg_pid = arg_pid;
2389 *p_check_trials = check_trials;
2390 *p_port = int_port;
2391 *p_last_command = last_command;
2394 int main(int argc, char** argv)
2396 int i;
2397 int pid;
2399 Bool show_shared_mem;
2400 Bool show_list;
2401 Bool multi_mode;
2402 int arg_pid;
2403 int check_trials;
2404 int in_port;
2405 int last_command;
2406 char *commands[argc]; // we will never have more commands than args.
2408 parse_options(argc, argv,
2409 &show_shared_mem,
2410 &show_list,
2411 &multi_mode,
2412 &arg_pid,
2413 &check_trials,
2414 &in_port,
2415 &last_command,
2416 commands);
2418 /* when we are working as a relay for gdb, handle some signals by
2419 only reporting them (according to debug level). Also handle these
2420 when ptrace will be used: vgdb must clean up the ptrace effect before
2421 dying. */
2422 if (max_invoke_ms > 0 || last_command == -1)
2423 install_handlers();
2425 if (!multi_mode) {
2426 pid = search_arg_pid(arg_pid, check_trials, show_list);
2428 /* We pass 1 for check_trails here, because search_arg_pid already waited. */
2429 prepare_fifos_and_shared_mem(pid, 1);
2430 } else {
2431 pid = 0;
2434 if (in_port > 0)
2435 wait_for_gdb_connect(in_port);
2437 if (show_shared_mem) {
2438 TSFPRINTF(stderr,
2439 "vgdb %d "
2440 "written_by_vgdb %d "
2441 "seen_by_valgrind %d\n",
2442 VS_vgdb_pid,
2443 VS_written_by_vgdb,
2444 VS_seen_by_valgrind);
2445 TSFPRINTF(stderr, "vgdb pid %d\n", VS_vgdb_pid);
2446 exit(0);
2449 if (multi_mode) {
2450 /* check_trails is the --wait argument in seconds, defaulting to 1
2451 * if not given. */
2452 do_multi_mode (check_trials, in_port);
2453 } else if (last_command >= 0) {
2454 standalone_send_commands(pid, last_command, commands);
2455 } else {
2456 gdb_relay(pid, 0, NULL);
2459 free(vgdb_prefix);
2460 free(valgrind_path);
2461 if (!multi_mode)
2462 cleanup_fifos_and_shared_mem();
2464 for (i = 0; i <= last_command; i++)
2465 free(commands[i]);
2466 return 0;