regtest: add a fdleak filter for write on write on linux arm64
[valgrind.git] / coregrind / vgdb.c
blob409ceac5d65cbc13dcfe8e819d7712c8dd8faecf
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 #include "m_gdbserver/remote-utils-shared.h"
54 /* vgdb has three usages:
55 1. relay application between gdb and the gdbserver embedded in valgrind.
56 2. standalone to send monitor commands to a running valgrind-ified process
57 3. multi mode where vgdb uses the GDB extended remote protocol.
59 It is made of a main program which reads arguments. If no
60 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
61 assumed.
63 As relay application, vgdb reads bytes from gdb on stdin and
64 writes these bytes to valgrind. Bytes read from valgrind are
65 written to gdb on stdout. Read/Write from/to valgrind is done
66 using FIFOs. There is one thread reading from stdin, writing to
67 valgrind on a FIFO. There is one thread reading from valgrind on a
68 FIFO, writing to gdb on stdout
70 As a standalone utility, vgdb builds command packets to write to valgrind,
71 sends it and reads the reply. The same two threads are used to write/read.
72 Once all the commands are sent and their replies received, vgdb will exit.
74 When --multi is given vgdb communicates with GDB through the extended remote
75 protocol and will launch valgrind whenever GDB sends the vRun packet, after
76 which it will function in the first mode, relaying packets between GDB and
77 the gdbserver embedded in valgrind till that valgrind quits. vgdb will stay
78 connected to GDB.
81 int debuglevel;
82 Bool timestamp = False;
83 char timestamp_out[20];
84 static char *vgdb_prefix = NULL;
85 static char *valgrind_path = NULL;
86 static char **vargs;
87 static int cvargs = 0;
89 char *timestamp_str (Bool produce)
91 static char out[50];
92 char *ptr;
93 struct timeval dbgtv;
94 struct tm *ts_tm;
96 if (produce) {
97 gettimeofday(&dbgtv, NULL);
98 ts_tm = localtime(&dbgtv.tv_sec);
99 ptr = out + strftime(out, sizeof(out), "%H:%M:%S", ts_tm);
100 sprintf(ptr, ".%6.6ld ", (long)dbgtv.tv_usec);
101 } else {
102 out[0] = 0;
104 return out;
107 /* Will be set to True when any condition indicating we have to shutdown
108 is encountered. */
109 Bool shutting_down = False;
111 VgdbShared32 *shared32;
112 VgdbShared64 *shared64;
113 #define VS_written_by_vgdb (shared32 != NULL ? \
114 shared32->written_by_vgdb \
115 : shared64->written_by_vgdb)
116 #define VS_seen_by_valgrind (shared32 != NULL ? \
117 shared32->seen_by_valgrind \
118 : shared64->seen_by_valgrind)
120 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
122 void *vmalloc(size_t size)
124 void * mem = malloc(size);
125 if (mem == NULL)
126 XERROR(errno, "can't allocate memory\n");
127 return mem;
130 void *vrealloc(void *ptr,size_t size)
132 void * mem = realloc(ptr, size);
133 if (mem == NULL)
134 XERROR(errno, "can't reallocate memory\n");
135 return mem;
138 /* Return the name of a directory for temporary files. */
139 static
140 const char *vgdb_tmpdir(void)
142 const char *tmpdir;
144 tmpdir = getenv("TMPDIR");
145 if (tmpdir == NULL || *tmpdir == '\0')
146 tmpdir = VG_TMPDIR;
147 if (tmpdir == NULL || *tmpdir == '\0')
148 tmpdir = "/tmp"; /* fallback */
150 return tmpdir;
153 /* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
154 to communicate with valgrind */
155 static
156 char *vgdb_prefix_default(void)
158 static HChar *prefix;
160 if (prefix == NULL) {
161 const char *tmpdir = vgdb_tmpdir();
162 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
163 strcpy(prefix, tmpdir);
164 strcat(prefix, "/vgdb-pipe");
166 return prefix;
169 /* add nrw to the written_by_vgdb field of shared32 or shared64 */
170 static
171 void add_written(int nrw)
173 if (shared32 != NULL)
174 shared32->written_by_vgdb += nrw;
175 else if (shared64 != NULL)
176 shared64->written_by_vgdb += nrw;
177 else
178 assert(0);
181 static int shared_mem_fd = -1;
182 static
183 void map_vgdbshared(char* shared_mem, int check_trials)
185 struct stat fdstat;
186 void **s;
187 int tries = 50;
188 int err;
190 /* valgrind might still be starting up, give it 5 seconds by
191 * default, or check_trials seconds if it is set by --wait
192 * to more than a second. */
193 if (check_trials > 1) {
194 DEBUG(1, "check_trials %d\n", check_trials);
195 tries = check_trials * 10;
197 do {
198 shared_mem_fd = open(shared_mem, O_RDWR | O_CLOEXEC);
199 err = errno;
200 if (shared_mem_fd == -1 && err == ENOENT && tries > 0)
201 usleep (100000); /* wait 0.1 seconds */
202 } while (shared_mem_fd == -1 && err == ENOENT && tries-- > 0);
204 /* shared_mem_fd will not be closed till vgdb exits. */
206 if (shared_mem_fd == -1)
207 XERROR(errno, "error opening %s shared memory file\n", shared_mem);
209 if (fstat(shared_mem_fd, &fdstat) != 0)
210 XERROR(errno, "fstat\n");
212 if (fdstat.st_size == sizeof(VgdbShared64))
213 s = (void*) &shared64;
214 else if (fdstat.st_size == sizeof(VgdbShared32))
215 s = (void*) &shared32;
216 else
217 #if VEX_HOST_WORDSIZE == 8
218 XERROR(0,
219 "error size shared memory file %s.\n"
220 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
221 shared_mem,
222 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
223 (long int)fdstat.st_size);
224 #elif VEX_HOST_WORDSIZE == 4
225 XERROR(0,
226 "error size shared memory file %s.\n"
227 "expecting size %d (32bits) got %ld.\n",
228 shared_mem,
229 (int) sizeof(VgdbShared32),
230 fdstat.st_size);
231 #else
232 # error "unexpected wordsize"
233 #endif
235 #if VEX_HOST_WORDSIZE == 4
236 if (shared64 != NULL)
237 XERROR(0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
238 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
239 #endif
241 *s = (void*) mmap(NULL, fdstat.st_size,
242 PROT_READ|PROT_WRITE, MAP_SHARED,
243 shared_mem_fd, 0);
245 if (*s == (void *) -1)
246 XERROR(errno, "error mmap shared memory file %s\n", shared_mem);
250 /* This function loops till shutting_down becomes true. In this loop,
251 it verifies if valgrind process is reading the characters written
252 by vgdb. The verification is done every max_invoke_ms ms. If
253 valgrind is not reading characters, it will use invoker_invoke_gdbserver
254 to ensure that the gdbserver code is called soon by valgrind. */
255 static int max_invoke_ms = 100;
256 #define NEVER 99999999
257 static int cmd_time_out = NEVER;
258 static
259 void *invoke_gdbserver_in_valgrind(void *v_pid)
261 struct timeval cmd_max_end_time;
262 Bool cmd_started = False;
263 struct timeval invoke_time;
265 int pid = *(int *)v_pid;
266 int written_by_vgdb_before_sleep;
267 int seen_by_valgrind_before_sleep;
269 int invoked_written = -1;
270 unsigned int usecs;
272 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
274 while (!shutting_down) {
275 written_by_vgdb_before_sleep = VS_written_by_vgdb;
276 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
277 DEBUG(3,
278 "written_by_vgdb_before_sleep %d "
279 "seen_by_valgrind_before_sleep %d\n",
280 written_by_vgdb_before_sleep,
281 seen_by_valgrind_before_sleep);
282 if (cmd_time_out != NEVER
283 && !cmd_started
284 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
285 /* A command was started. Record the time at which it was started. */
286 DEBUG(1, "IO for command started\n");
287 gettimeofday(&cmd_max_end_time, NULL);
288 cmd_max_end_time.tv_sec += cmd_time_out;
289 cmd_started = True;
291 if (max_invoke_ms > 0) {
292 usecs = 1000 * max_invoke_ms;
293 gettimeofday(&invoke_time, NULL);
294 invoke_time.tv_sec += max_invoke_ms / 1000;
295 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
296 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
297 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
298 } else {
299 usecs = 0;
301 if (cmd_started) {
302 // 0 usecs here means the thread just has to check gdbserver eats
303 // the characters in <= cmd_time_out seconds.
304 // We will just wait by 1 second max at a time.
305 if (usecs == 0 || usecs > 1000 * 1000)
306 usecs = 1000 * 1000;
308 usleep(usecs);
310 /* If nothing happened during our sleep, let's try to wake up valgrind
311 or check for cmd time out. */
312 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
313 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
314 && VS_written_by_vgdb > VS_seen_by_valgrind) {
315 struct timeval now;
316 gettimeofday(&now, NULL);
317 DEBUG(2,
318 "after sleep "
319 "written_by_vgdb %d "
320 "seen_by_valgrind %d "
321 "invoked_written %d\n",
322 VS_written_by_vgdb,
323 VS_seen_by_valgrind,
324 invoked_written);
325 /* if the pid does not exist anymore, we better stop */
326 if (kill(pid, 0) != 0)
327 XERROR(errno,
328 "invoke_gdbserver_in_valgrind: "
329 "check for pid %d existence failed\n", pid);
330 if (cmd_started) {
331 if (timercmp(&now, &cmd_max_end_time, >))
332 XERROR(0,
333 "pid %d did not handle a command in %d seconds\n",
334 pid, cmd_time_out);
336 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
337 /* only need to wake up if the nr written has changed since
338 last invoke. */
339 if (invoked_written != written_by_vgdb_before_sleep) {
340 if (invoker_invoke_gdbserver(pid)) {
341 /* If invoke successful, no need to invoke again
342 for the same value of written_by_vgdb_before_sleep. */
343 invoked_written = written_by_vgdb_before_sleep;
347 } else {
348 // Something happened => restart timer check.
349 if (cmd_time_out != NEVER) {
350 DEBUG(2, "some IO was done => restart command\n");
351 cmd_started = False;
355 pthread_cleanup_pop(0);
356 return NULL;
359 static
360 int open_fifo(const char* name, int flags, const char* desc)
362 int fd;
363 DEBUG(1, "opening %s %s\n", name, desc);
364 fd = open(name, flags | O_CLOEXEC);
365 if (fd == -1)
366 XERROR(errno, "error opening %s %s\n", name, desc);
368 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
369 return fd;
372 /* acquire a lock on the first byte of the given fd. If not successful,
373 exits with error.
374 This allows to avoid having two vgdb speaking with the same Valgrind
375 gdbserver as this causes serious headaches to the protocol. */
376 static
377 void acquire_lock(int fd, int valgrind_pid)
379 struct flock fl;
380 fl.l_type = F_WRLCK;
381 fl.l_whence = SEEK_SET;
382 fl.l_start = 0;
383 fl.l_len = 1;
384 if (fcntl(fd, F_SETLK, &fl) < 0) {
385 if (errno == EAGAIN || errno == EACCES) {
386 XERROR(errno,
387 "Cannot acquire lock.\n"
388 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
389 VS_vgdb_pid,
390 valgrind_pid);
391 } else {
392 XERROR(errno, "cannot acquire lock.\n");
396 /* Here, we have the lock. It will be released when fd will be closed. */
397 /* We indicate our pid to Valgrind gdbserver */
398 if (shared32 != NULL)
399 shared32->vgdb_pid = getpid();
400 else if (shared64 != NULL)
401 shared64->vgdb_pid = getpid();
402 else
403 assert(0);
406 #define PBUFSIZ 16384 /* keep in sync with server.h */
408 /* read some characters from fd.
409 Returns the nr of characters read, -1 if error.
410 desc is a string used in tracing */
411 static
412 size_t read_buf(int fd, char* buf, const char* desc)
414 ssize_t nrread;
415 DEBUG(2, "reading %s\n", desc);
416 /* The file descriptor is on non-blocking mode and read_buf should only
417 be called when poll gave us an POLLIN event signaling the file
418 descriptor is ready for reading from. Still sometimes we do get an
419 occasional EAGAIN. Just do as told in that case and try to read
420 again. */
421 do {
422 nrread = read(fd, buf, PBUFSIZ);
423 } while (nrread == -1 && (errno == EINTR || errno == EAGAIN));
424 if (nrread < 0) {
425 ERROR(errno, "error reading %s\n", desc);
426 return -1;
428 buf[nrread] = '\0';
429 DEBUG(2, "read %s %s\n", desc, buf);
430 return nrread;
433 /* write size bytes from buf to fd.
434 desc is a description of the action for which the write is done.
435 If notify, then add size to the shared cntr indicating to the
436 valgrind process that there is new data.
437 Returns True if write is ok, False if there was a problem. */
438 static
439 Bool write_buf(int fd, const char* buf, size_t size, const char* desc,
440 Bool notify)
442 size_t nrwritten;
443 ssize_t nrw;
444 DEBUG(2, "writing %s len %zu %.*s notify: %d\n", desc, size,
445 (int)size, buf, notify);
446 nrwritten = 0;
447 while (nrwritten < size) {
448 nrw = write(fd, buf+nrwritten, size - nrwritten);
449 if (nrw < 0) {
450 if (errno == EINTR || errno == EAGAIN)
451 continue;
453 ERROR(errno, "error write %s\n", desc);
454 return False;
456 nrwritten = nrwritten + nrw;
457 if (notify)
458 add_written(nrw);
460 return True;
463 typedef enum {
464 FROM_GDB,
465 TO_GDB,
466 FROM_PID,
467 TO_PID } ConnectionKind;
468 static const int NumConnectionKind = TO_PID+1;
469 static
470 const char *ppConnectionKind(ConnectionKind con)
472 switch (con) {
473 case FROM_GDB: return "FROM_GDB";
474 case TO_GDB: return "TO_GDB";
475 case FROM_PID: return "FROM_PID";
476 case TO_PID: return "TO_PID";
477 default: return "invalid connection kind";
481 static char *shared_mem;
483 static int from_gdb = 0; /* stdin by default, changed if --port is given. */
484 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
486 static int to_gdb = 1; /* stdout by default, changed if --port is given. */
487 static char *to_gdb_from_pid; /* fifo name to read pid replies */
489 /* Returns True in case read/write operations were done properly.
490 Returns False in case of error.
491 to_pid is the file descriptor to write to the process pid. */
492 static
493 Bool read_from_gdb_write_to_pid(int to_pid)
495 char buf[PBUFSIZ+1]; // +1 for trailing \0
496 ssize_t nrread;
497 Bool ret;
499 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
500 if (nrread <= 0) {
501 if (nrread == 0)
502 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
503 else
504 DEBUG(1, "error reading bytes from gdb\n");
505 close(from_gdb);
506 shutting_down = True;
507 return False;
509 ret = write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
510 if (!ret) {
511 /* Let gdb know the packet couldn't be delivered. */
512 write_buf(to_gdb, "$E01#a6", 8, "error back to gdb", False);
514 return ret;
517 /* Returns True in case read/write operations were done properly.
518 Returns False in case of error.
519 from_pid is the file descriptor to read data from the process pid. */
520 static
521 Bool read_from_pid_write_to_gdb(int from_pid)
523 char buf[PBUFSIZ+1]; // +1 for trailing \0
524 int nrread;
526 nrread = read_buf(from_pid, buf, "from pid");
527 if (nrread <= 0) {
528 if (nrread == 0)
529 DEBUG(1, "read 0 bytes from pid => assume exit\n");
530 else
531 DEBUG(1, "error reading bytes from pid\n");
532 close(from_pid);
533 shutting_down = True;
534 return False;
536 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
539 static
540 void wait_for_gdb_connect(int in_port)
542 struct sockaddr_in addr;
544 #ifdef SOCK_CLOEXEC
545 int listen_gdb = socket(PF_INET, SOCK_STREAM | SOCK_CLOEXEC, IPPROTO_TCP);
546 #else
547 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
548 #endif
550 int gdb_connect;
552 if (-1 == listen_gdb) {
553 XERROR(errno, "cannot create socket\n");
556 /* allow address reuse to avoid "address already in use" errors */
558 int one = 1;
559 if (setsockopt(listen_gdb, SOL_SOCKET, SO_REUSEADDR,
560 &one, sizeof(one)) < 0) {
561 XERROR(errno, "cannot enable address reuse\n");
564 memset(&addr, 0, sizeof(addr));
566 addr.sin_family = AF_INET;
567 addr.sin_port = htons((unsigned short int)in_port);
568 addr.sin_addr.s_addr = INADDR_ANY;
570 if (-1 == bind(listen_gdb, (struct sockaddr *)&addr, sizeof(addr))) {
571 XERROR(errno, "bind failed\n");
573 TSFPRINTF(stderr, "listening on port %d ...", in_port);
574 if (-1 == listen(listen_gdb, 1)) {
575 XERROR(errno, "error listen failed\n");
578 #ifdef SOCK_CLOEXEC
579 gdb_connect = accept4(listen_gdb, NULL, NULL, SOCK_CLOEXEC);
580 #else
581 gdb_connect = accept(listen_gdb, NULL, NULL);
582 #endif
584 if (gdb_connect < 0) {
585 XERROR(errno, "accept failed\n");
587 fprintf(stderr, "connected.\n");
588 fflush(stderr);
589 close(listen_gdb);
590 from_gdb = gdb_connect;
591 to_gdb = gdb_connect;
594 /* prepares the FIFOs filenames, map the shared memory. */
595 static
596 void prepare_fifos_and_shared_mem(int pid, int check_trials)
598 const HChar *user, *host;
599 unsigned len;
601 user = getenv("LOGNAME");
602 if (user == NULL) user = getenv("USER");
603 if (user == NULL) user = "???";
604 if (strchr(user, '/')) user = "???";
606 host = getenv("HOST");
607 if (host == NULL) host = getenv("HOSTNAME");
608 if (host == NULL) host = "???";
609 if (strchr(host, '/')) host = "???";
611 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
612 from_gdb_to_pid = vmalloc(len);
613 to_gdb_from_pid = vmalloc(len);
614 shared_mem = vmalloc(len);
615 /* below 3 lines must match the equivalent in remote-utils.c */
616 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
617 pid, user, host);
618 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
619 pid, user, host);
620 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
621 pid, user, host);
622 DEBUG(1, "vgdb: using %s %s %s\n",
623 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
625 map_vgdbshared(shared_mem, check_trials);
628 static void
629 cleanup_fifos_and_shared_mem(void)
631 free(from_gdb_to_pid);
632 free(to_gdb_from_pid);
633 free(shared_mem);
634 close(shared_mem_fd);
637 /* Convert hex digit A to a number. */
639 static int
640 fromhex(int a)
642 if (a >= '0' && a <= '9')
643 return a - '0';
644 else if (a >= 'a' && a <= 'f')
645 return a - 'a' + 10;
646 else
647 XERROR(0, "Reply contains invalid hex digit %c\n", a);
648 return 0;
651 /* Returns next char from fd. -1 if error, -2 if EOF.
652 NB: must always call it with the same fd */
653 static int
654 readchar(int fd)
656 static char buf[PBUFSIZ+1]; // +1 for trailing \0
657 static int bufcnt = 0;
658 static unsigned char *bufp;
659 // unsigned bufp to e.g. avoid having 255 converted to int -1
661 if (bufcnt-- > 0)
662 return *bufp++;
664 bufcnt = read_buf(fd, buf, "static buf readchar");
666 if (bufcnt <= 0) {
667 if (bufcnt == 0) {
668 TSFPRINTF(stderr, "readchar: Got EOF\n");
669 return -2;
670 } else {
671 ERROR(errno, "readchar\n");
672 return -1;
676 bufp = (unsigned char *)buf;
677 bufcnt--;
678 return *bufp++;
681 /* Read a packet from fromfd, with error checking,
682 and store it in BUF.
683 If checksum incorrect, writes a - on ackfd.
684 Returns length of packet, or -1 if error or -2 if EOF. */
685 static int
686 getpkt(char *buf, int fromfd, int ackfd)
688 char *bp;
689 unsigned char csum, c1, c2;
690 int c;
692 while (1) {
693 csum = 0;
695 while (1) {
696 c = readchar(fromfd);
697 if (c == '$')
698 break;
699 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
700 if (c < 0)
701 return c;
704 bp = buf;
705 while (1) {
706 c = readchar(fromfd);
707 if (c < 0)
708 return c;
709 if (c == '#')
710 break;
711 if (c == '*') {
712 int repeat;
713 int r;
714 int prev;
715 prev = *(bp-1);
716 csum += c;
717 repeat = readchar(fromfd);
718 csum += repeat;
719 for (r = 0; r < repeat - 29; r ++)
720 *bp++ = prev;
721 } else {
722 *bp++ = c;
723 csum += c;
726 *bp = 0;
728 c1 = fromhex(readchar (fromfd));
729 c2 = fromhex(readchar (fromfd));
731 if (csum == (c1 << 4) + c2)
732 break;
734 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
735 (c1 << 4) + c2, csum, buf);
736 ssize_t res = 0;
737 while (res == 0) {
738 res = write(ackfd, "-", 1);
739 if (res == -1 && (errno == EINTR || errno == EAGAIN))
740 res = 0;
742 if (res < 0)
743 ERROR(errno, "error when writing - (nack)\n");
744 else
745 add_written(1);
748 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
749 return bp - buf;
752 static int sigint = 0;
753 static int sigterm = 0;
754 static int sigpipe = 0;
755 static int sighup = 0;
756 static int sigusr1 = 0;
757 static int sigalrm = 0;
758 static int sigusr1_fd = -1;
759 static pthread_t invoke_gdbserver_in_valgrind_thread;
761 static
762 void received_signal(int signum)
764 if (signum == SIGINT)
765 sigint++;
766 else if (signum == SIGUSR1) {
767 sigusr1++;
768 if (sigusr1_fd >= 0) {
769 char control_c = '\003';
770 write_buf(sigusr1_fd, &control_c, 1,
771 "write \\003 on SIGUSR1", /* notify */ True);
774 else if (signum == SIGTERM) {
775 shutting_down = True;
776 sigterm++;
777 } else if (signum == SIGHUP) {
778 shutting_down = True;
779 sighup++;
780 } else if (signum == SIGPIPE) {
781 sigpipe++;
782 } else if (signum == SIGALRM) {
783 sigalrm++;
784 #if defined(VGPV_arm_linux_android) \
785 || defined(VGPV_x86_linux_android) \
786 || defined(VGPV_mips32_linux_android) \
787 || defined(VGPV_arm64_linux_android)
788 /* Android has no pthread_cancel. As it also does not have
789 an invoker implementation, there is no need for cleanup action.
790 So, we just do nothing. */
791 DEBUG(1, "sigalrm received, no action on android\n");
792 #else
793 /* Note: we cannot directly invoke restore_and_detach : this must
794 be done by the thread that has attached.
795 We have in this thread pushed a cleanup handler that will
796 cleanup what is needed. */
797 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
798 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
799 #endif
800 } else {
801 ERROR(0, "unexpected signal %d\n", signum);
805 /* install the signal handlers allowing e.g. vgdb to cleanup in
806 case of termination. */
807 static
808 void install_handlers(void)
810 struct sigaction action, oldaction;
812 action.sa_handler = received_signal;
813 sigemptyset(&action.sa_mask);
814 action.sa_flags = 0;
816 /* SIGINT: when user types C-c in gdb, this sends
817 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
818 The later is enough to wakeup the valgrind process. */
819 if (sigaction(SIGINT, &action, &oldaction) != 0)
820 XERROR(errno, "vgdb error sigaction SIGINT\n");
821 /* We might do something more intelligent than just
822 reporting this SIGINT E.g. behave similarly to the gdb: two
823 control-C without feedback from the debugged process would
824 mean to stop debugging it. */
826 /* SIGUSR1: this is used to facilitate automatic testing. When
827 vgdb receives this signal, it will simulate the user typing C-c. */
828 if (sigaction(SIGUSR1, &action, &oldaction) != 0)
829 XERROR(errno, "vgdb error sigaction SIGUSR1\n");
832 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
833 when detaching or similar. A clean shutdown will be done as both
834 the read and write side will detect an end of file. */
835 if (sigaction(SIGTERM, &action, &oldaction) != 0)
836 XERROR(errno, "vgdb error sigaction SIGTERM\n");
838 /* SIGPIPE: can receive this signal when gdb detaches or kill the
839 process debugged: gdb will close its pipes to vgdb. vgdb
840 must resist to this signal to allow a clean shutdown. */
841 if (sigaction(SIGPIPE, &action, &oldaction) != 0)
842 XERROR(errno, "vgdb error sigaction SIGPIPE\n");
844 /* SIGALRM: in case invoke thread is blocked, alarm is used
845 to cleanup. */
846 if (sigaction(SIGALRM, &action, &oldaction) != 0)
847 XERROR(errno, "vgdb error sigaction SIGALRM\n");
849 /* unmask all signals, in case the process that launched vgdb
850 masked some. */
851 if (sigprocmask(SIG_SETMASK, &action.sa_mask, NULL) != 0)
852 XERROR(errno, "vgdb error sigprocmask\n");
855 /* close the FIFOs provided connections, terminate the invoker thread. */
856 static
857 void close_connection(int to_pid, int from_pid)
859 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
860 sigint, sigterm, sighup, sigpipe);
861 /* Note that we do not forward sigterm to the valgrind process:
862 a sigterm signal is (probably) received from gdb if the user wants to
863 kill the debugged process. The kill instruction has been given to
864 the valgrind process, which should execute a clean exit. */
866 /* We first close the connection to pid. The pid will then
867 terminates its gdbserver work. We keep the from pid
868 fifo opened till the invoker thread is finished.
869 This allows the gdbserver to finish sending its last reply. */
870 if (close(to_pid) != 0)
871 ERROR(errno, "close to_pid\n");
873 /* if there is a task that was busy trying to wake up valgrind
874 process, we wait for it to be terminated otherwise threads
875 in the valgrind process can stay stopped if vgdb main
876 exits before the invoke thread had time to detach from
877 all valgrind threads. */
878 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
879 int join;
881 /* It is surprisingly complex to properly shutdown or exit the
882 valgrind process in which gdbserver has been invoked through
883 ptrace. In the normal case (gdb detaches from the process,
884 or process is continued), the valgrind process will reach the
885 breakpoint place. Using ptrace, vgdb will ensure the
886 previous activity of the process is resumed (e.g. restart a
887 blocking system call). The special case is when gdb asks the
888 valgrind process to exit (using either the "kill" command or
889 "monitor exit"). In such a case, the valgrind process will
890 call exit. But a ptraced process will be blocked in exit,
891 waiting for the ptracing process to detach or die. vgdb
892 cannot detach unconditionally as otherwise, in the normal
893 case, the valgrind process would stop abnormally with SIGSTOP
894 (as vgdb would not be there to catch it). vgdb can also not
895 die unconditionally otherwise again, similar problem. So, we
896 assume that most of the time, we arrive here in the normal
897 case, and so, the breakpoint has been encountered by the
898 valgrind process, so the invoker thread will exit and the
899 join will succeed. For the "kill" case, we cause an alarm
900 signal to be sent after a few seconds. This means that in the
901 normal case, the gdbserver code in valgrind process must have
902 returned the control in less than the alarm nr of seconds,
903 otherwise, valgrind will stop abnormally with SIGSTOP. */
904 (void) alarm(3);
906 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
907 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
908 if (join != 0)
909 XERROR
910 (join,
911 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
913 #if !defined(VGO_freebsd)
914 if (close(from_pid) != 0)
915 ERROR(errno, "close from_pid\n");
916 #endif
919 /* Returns an allocated hex-decoded string from the buf. Stops decoding
920 at end of buf (zero) or when seeing the delim char. */
921 static
922 char *decode_hexstring (const char *buf, size_t prefixlen, size_t len)
924 int buflen;
925 char *buf_print;
927 if (len)
928 buflen = len;
929 else
930 buflen = strlen(buf) - prefixlen;
932 buf_print = vmalloc (buflen/2 + 1);
934 for (int i = 0; i < buflen; i = i + 2) {
935 buf_print[i/2] = ((fromhex(buf[i+prefixlen]) << 4)
936 + fromhex(buf[i+prefixlen+1]));
938 buf_print[buflen/2] = '\0';
939 DEBUG(1, "decode_hexstring: %s\n", buf_print);
940 return buf_print;
943 static Bool
944 write_to_gdb (const char *m, size_t cnt)
946 size_t written = 0;
947 while (written < cnt) {
948 ssize_t res = write (to_gdb, m + written, cnt - written);
949 if (res < 0) {
950 if (errno == EINTR || errno == EAGAIN)
951 continue;
953 perror ("write_to_gdb");
954 return False;
956 written += res;
959 return True;
962 static Bool
963 write_checksum (const char *str)
965 unsigned char csum = 0;
966 int i = 0;
967 while (str[i] != 0)
968 csum += str[i++];
970 char p[2];
971 p[0] = tohex ((csum >> 4) & 0x0f);
972 p[1] = tohex (csum & 0x0f);
973 return write_to_gdb (p, 2);
976 static Bool
977 write_reply(const char *reply)
979 write_to_gdb ("$", 1);
980 write_to_gdb (reply, strlen (reply));
981 write_to_gdb ("#", 1);
982 return write_checksum (reply);
985 /* Creates a packet from a string message, caller needs to free. */
986 static char *
987 create_packet(const char *msg)
989 unsigned char csum = 0;
990 int i = 1;
991 char *p = vmalloc (strlen (msg) + 5); /* $ + msg + # + hexhex + 0 */
992 strcpy (&p[1], msg);
993 p[0] = '$';
994 while (p[i] != 0)
995 csum += p[i++];
996 p[i++] = '#';
997 p[i++] = tohex ((csum >> 4) & 0x0f);
998 p[i++] = tohex (csum & 0x0f);
999 p[i] = '\0';
1000 return p;
1003 static ssize_t read_one_char (char *c)
1005 ssize_t i;
1007 i = read (from_gdb, c, 1);
1008 while (i < 0 && (errno == EINTR || errno == EAGAIN));
1010 return i;
1013 static Bool
1014 send_packet(const char *reply, int noackmode)
1016 ssize_t ret;
1017 char c;
1019 send_packet_start:
1020 if (!write_reply(reply))
1021 return False;
1022 if (!noackmode) {
1023 // Look for '+' or '-'.
1024 // We must wait for "+" if !noackmode.
1025 do {
1026 ret = read_one_char(&c);
1027 if (ret <= 0)
1028 return False;
1029 // And if in !noackmode if we get "-" we should resent the packet.
1030 if (c == '-')
1031 goto send_packet_start;
1032 } while (c != '+');
1033 DEBUG(1, "sent packet to gdb got: %c\n",c);
1035 return True;
1038 // Reads one packet from_gdb starting with $ into buf.
1039 // Skipping any other characters.
1040 // Returns the size of the packet, 0 for end of input,
1041 // or -1 if no packet could be read.
1042 static ssize_t receive_packet(char *buf, int noackmode)
1044 size_t bufcnt = 0;
1045 ssize_t ret;
1046 char c;
1047 char c1 = '\0';
1048 char c2 = '\0';
1049 unsigned char csum = 0;
1051 // Look for first '$' (start of packet) or error.
1052 receive_packet_start:
1053 do {
1054 ret = read_one_char(&c);
1055 if (ret <= 0)
1056 return ret;
1057 } while (c != '$');
1059 // Found start of packet ('$')
1060 while (bufcnt < (PBUFSIZ+1)) {
1061 ret = read_one_char(&c);
1062 if (ret <= 0)
1063 return ret;
1064 if (c == '#') {
1065 if ((ret = read_one_char(&c1)) <= 0
1066 || (ret = read_one_char(&c2)) <= 0) {
1067 return ret;
1069 c1 = fromhex(c1);
1070 c2 = fromhex(c2);
1071 break;
1073 buf[bufcnt] = c;
1074 csum += buf[bufcnt];
1075 bufcnt++;
1078 // Packet complete, add terminator.
1079 buf[bufcnt] ='\0';
1081 if (!(csum == (c1 << 4) + c2)) {
1082 TSFPRINTF(stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1083 (c1 << 4) + c2, csum, buf);
1084 if (!noackmode)
1085 if (!write_to_gdb ("-", 1))
1086 return -1;
1087 /* Try again, gdb should resend the packet. */
1088 bufcnt = 0;
1089 csum = 0;
1090 goto receive_packet_start;
1093 if (!noackmode)
1094 if (!write_to_gdb ("+", 1))
1095 return -1;
1096 return bufcnt;
1099 // Returns a pointer to the char after the next delim char.
1100 static const char *next_delim_string (const char *buf, char delim)
1102 while (*buf) {
1103 if (*buf++ == delim)
1104 break;
1106 return buf;
1109 /* buf starts with the packet name followed by the delimiter, for example
1110 * vRun;2f62696e2f6c73, ";" is the delimiter here, or
1111 * qXfer:features:read:target.xml:0,1000, where the delimiter is ":".
1112 * The packet name is thrown away and the hex string is decoded and
1113 * is placed in decoded_string (the caller owns this and is responsible
1114 * for freeing it). */
1115 static int split_hexdecode(const char *buf, const char *string,
1116 const char *delim, char **decoded_string)
1118 const char *next_str = next_delim_string(buf, *delim);
1119 if (next_str) {
1120 *decoded_string = decode_hexstring (next_str, 0, 0);
1121 DEBUG(1, "split_hexdecode decoded %s\n", *decoded_string);
1122 return 1;
1123 } else {
1124 TSFPRINTF(stderr, "%s decoding error: finding the hex string in %s failed!\n", string, buf);
1125 return 0;
1129 static size_t count_delims(char delim, char *buf)
1131 size_t count = 0;
1132 char *ptr = buf;
1134 while (*ptr)
1135 count += *ptr++ == delim;
1136 return count;
1139 // Determine the length of the arguments.
1140 // This depends on the len array being initialized to -1 for each element.
1141 // We first skip the command (e.g. vRun;arg0;arg1)
1142 static void count_len(char delim, char *buf, size_t *len)
1144 int i = 0;
1145 char *ptr = buf;
1147 // Skip the command
1148 while (*ptr && *ptr != delim)
1149 ptr++;
1151 // Delimiter counts towards the first arg0
1152 if (*ptr == delim) {
1153 ptr++;
1154 len[i]++;
1157 // For each arg0... count chars (delim counts towards next arg)
1158 while (*ptr) {
1159 i += *ptr++ == delim;
1160 len[i]++;
1164 /* early_exit guesses if vgdb speaks with GDB by checking from_gdb is a FIFO
1165 (as GDB is likely the only program that would write data to vgdb stdin).
1166 If not speaking with GDB, early_exit will just call exit(exit_code).
1167 If speaking with GDB, early_exit will ensure the GDB user sees
1168 the error messages produced by vgdb:
1169 early_exit should be used when vgdb exits due to an early error i.e.
1170 error during arg processing, before it could successfully process the
1171 first packet from GDB.
1172 early_exit will then read the first packet send by GDB (i.e.
1173 the qSupported packet) and will reply to it with an error and then exit.
1174 This should ensure the vgdb error messages are made visible to the user. */
1175 static void early_exit (int exit_code, const char* exit_info)
1177 char buf[PBUFSIZ+1];
1178 ssize_t pkt_size;
1179 struct stat fdstat;
1181 if (fstat(from_gdb, &fdstat) != 0)
1182 XERROR(errno, "fstat\n");
1184 DEBUG(1, "early_exit %s ISFIFO %d\n", exit_info, S_ISFIFO(fdstat.st_mode));
1186 if (S_ISFIFO(fdstat.st_mode)) {
1187 /* We assume that we speak with GDB when stdin is a FIFO, so we expect
1188 to get a first packet from GDB. This should ensure the vgdb messages
1189 are made visible. In case the whole stuff is blocked for any reason or
1190 GDB does not send a package or ..., schedule an alarm to exit in max 5
1191 seconds anyway. */
1192 alarm(5);
1193 pkt_size = receive_packet(buf, 0);
1194 if (pkt_size <= 0)
1195 DEBUG(1, "early_exit receive_packet: %zd\n", pkt_size);
1196 else {
1197 DEBUG(1, "packet received: '%s'\n", buf);
1198 sprintf(buf, "E.%s", exit_info);
1199 send_packet(buf, 0);
1202 fflush(stdout);
1203 fflush(stderr);
1204 DEBUG(1, "early_exit exiting %d\n", exit_code);
1205 exit(exit_code);
1208 /* Declare here, will be used early, implementation follows later. */
1209 static void gdb_relay(int pid, int send_noack_mode, char *q_buf);
1211 /* Returns zero on success (and the pid of the valgrind process),
1212 or the errno from the child on failure. */
1213 static
1214 int fork_and_exec_valgrind (int argc, char **argv, const char *working_dir,
1215 int in_port, pid_t *pid)
1217 int err = 0;
1218 // We will use a pipe to track what the child does,
1219 // so we can report failure.
1220 int pipefd[2];
1221 #ifdef HAVE_PIPE2
1222 if (pipe2 (pipefd, O_CLOEXEC) == -1) {
1223 err = errno;
1224 perror ("pipe2 failed");
1225 return err;
1227 #else
1228 if (pipe (pipefd) == -1) {
1229 err = errno;
1230 perror ("pipe failed");
1231 return err;
1232 } else {
1233 if (fcntl (pipefd[0], F_SETFD, FD_CLOEXEC) == -1
1234 || fcntl (pipefd[1], F_SETFD, FD_CLOEXEC) == -1) {
1235 err = errno;
1236 perror ("fcntl failed");
1237 close (pipefd[0]);
1238 close (pipefd[1]);
1239 return err;
1242 #endif
1244 pid_t p = fork ();
1245 if (p < 0) {
1246 err = errno;
1247 perror ("fork failed");
1248 return err;
1249 } else if (p > 0) {
1250 // I am the parent (vgdb), p is the pid of the child (valgrind)
1251 // We only read from the child to see if everything is OK.
1252 // If the pipe closes, we get zero back, which is good.
1253 // An error reading the pipe is bad (and really shouldn't happen).
1254 // Otherwise the child sent us an errno code about what went wrong.
1255 close (pipefd[1]);
1257 size_t nr_read = 0;
1258 while (err == 0) {
1259 ssize_t r = read (pipefd[0], ((char *)&err) + nr_read,
1260 sizeof (int) - nr_read);
1261 if (r == 0) // end of file, good pipe closed after execve
1262 break;
1263 if (r == -1) {
1264 if (errno == EINTR || errno == EAGAIN)
1265 continue;
1266 else {
1267 err = errno;
1268 perror ("pipe read");
1273 close (pipefd[0]);
1274 if (err != 0)
1275 return err;
1276 else {
1277 *pid = p;
1278 return 0;
1280 } else {
1281 // p == 0, I am the child (will start valgrind)
1282 // We write success to the pipe, no need to read from it.
1283 close (pipefd[0]);
1285 if (working_dir != NULL && working_dir[0] != '\0') {
1286 if (chdir (working_dir) != 0) {
1287 err = errno;
1288 perror("chdir");
1289 // We try to write the result to the parent, but always exit.
1290 size_t written = 0;
1291 while (written < sizeof (int)) {
1292 int nrw = write (pipefd[1], ((char *)&err) + written,
1293 sizeof (int) - written);
1294 if (nrw == -1) {
1295 if (errno == EINTR || errno == EAGAIN)
1296 continue;
1297 break;
1299 written += nrw;
1301 _exit (-1);
1305 /* When in stdio mode (talking to gdb through stdin/stdout, not
1306 through a socket), redirect stdout to stderr and close stdin
1307 for the inferior. That way at least some output can be seen,
1308 but there will be no input. */
1309 if (in_port <= 0) {
1310 /* close stdin */
1311 close (0);
1312 /* open /dev/null as new stdin */
1313 (void)open ("/dev/null", O_RDONLY);
1314 /* redirect stdout as stderr */
1315 dup2 (2, 1);
1318 /* Try to launch valgrind. Add --vgdb-error=0 to stop immediately so we
1319 can attach and --launched-with-multi to let valgrind know it doesn't
1320 need to show a banner how to connect to gdb, we will do that
1321 automagically. And add --vgdb-shadow-registers=yes to make shadow
1322 registers available by default. Add any other valgrind arguments the
1323 user gave with --vargs. Then the rest of the arguments to valgrind are
1324 the program to exec plus its arguments. */
1325 const int extra_vargs = 3;
1326 /* vargv[0] == "valgrind",
1327 vargv[1..extra_vargs] == static valgrind arguments vgdb needs,
1328 vargv[extra_vargs+1..extra_vargs+1+cvargs] == user valgrind arguments,
1329 vargv[extra_vargs+1+cvargs..extra_vargs+1+cvargs+args] == prog + args,
1330 vargs[arguments - 1] = NULL */
1331 int arguments = 1 + extra_vargs + cvargs + argc + 1;
1332 // We combine const and non-const char[]. This is mildly annoying
1333 // since we then need a char *const * for execvp. So we strdup the
1334 // const char*. Not pretty :{
1335 char **vargv = vmalloc (arguments * sizeof (char *));
1336 vargv[0] = strdup ("valgrind");
1337 vargv[1] = strdup ("--vgdb-error=0");
1338 vargv[2] = strdup ("--launched-with-multi=yes");
1339 vargv[3] = strdup ("--vgdb-shadow-registers=yes");
1340 // Add --vargs
1341 for (int i = 0; i < cvargs; i++) {
1342 vargv[i + extra_vargs + 1] = vargs[i];
1344 // Add command and args
1345 for (int i = 0; i < argc; i++) {
1346 vargv[i + extra_vargs + 1 + cvargs] = argv[i];
1348 vargv[arguments - 1] = NULL;
1350 if (!valgrind_path) {
1351 // TODO use execvpe (or something else if not on GNU/Linux
1352 /* We want to make a copy of the environ on start. When we
1353 get a QEnvironmentReset we copy that back. If we get an
1354 EvironSet/Add/Remove we update the copy. */
1355 execvp ("valgrind", vargv);
1357 else {
1358 vargv[0] = valgrind_path;
1359 execvp (vargv[0], vargv);
1362 // We really shouldn't get here...
1363 err = errno;
1364 /* Note we are after fork and exec failed, we cannot really call
1365 perror or printf in this situation since they aren't async-safe. */
1366 // perror ("execvp valgrind");
1367 // printf ("execve returned??? confusing: %d\n", res);
1368 // We try to write the result to the parent, but always exit.
1369 size_t written = 0;
1370 while (written < sizeof (int)) {
1371 ssize_t nrw = write (pipefd[1], ((char *) &err) + written,
1372 sizeof (int) - written);
1373 if (nrw == -1) {
1374 if (errno == EINTR || errno == EAGAIN)
1375 continue;
1376 break;
1378 written += nrw;
1380 _exit (-1);
1383 abort (); // Impossible
1386 /* Do multi stuff. */
1387 static
1388 void do_multi_mode(int check_trials, int in_port)
1390 char *buf = vmalloc(PBUFSIZ+1);
1391 char *q_buf = vmalloc(PBUFSIZ+1); //save the qSupported packet sent by gdb
1392 //to send it to the valgrind gdbserver later
1393 q_buf[0] = '\0';
1394 int noackmode = 0, bad_unknown_packets = 0;
1395 ssize_t pkt_size = 0;
1396 char *string = NULL;
1397 char *working_dir = NULL;
1398 DEBUG(1, "doing multi stuff...\n");
1399 while (1){
1400 /* We get zero if the pipe was closed (EOF), or -1 on error reading from
1401 the pipe to gdb. */
1402 pkt_size = receive_packet(buf, noackmode);
1403 if (pkt_size <= 0) {
1404 DEBUG(1, "receive_packet: %zd\n", pkt_size);
1405 break;
1408 DEBUG(1, "packet received: '%s'\n", buf);
1410 #define QSUPPORTED "qSupported:"
1411 #define STARTNOACKMODE "QStartNoAckMode"
1412 #define QRCMD "qRcmd" // This is the monitor command in gdb
1413 #define VRUN "vRun"
1414 #define XFER "qXfer"
1415 #define QATTACHED "qAttached"
1416 #define QENVIRONMENTHEXENCODED "QEnvironmentHexEncoded"
1417 #define QENVIRONMENTRESET "QEnvironmentReset"
1418 #define QENVIRONMENTUNSET "QEnvironmentUnset"
1419 #define QSETWORKINGDIR "QSetWorkingDir"
1420 #define QTSTATUS "qTStatus"
1422 if (strncmp(QSUPPORTED, buf, strlen(QSUPPORTED)) == 0) {
1423 DEBUG(1, "CASE %s\n", QSUPPORTED);
1424 // And here is our reply.
1425 // XXX error handling? We don't check the arguments.
1426 char *reply;
1427 strcpy(q_buf, buf);
1428 // Keep this in sync with coregrind/m_gdbserver/server.c
1429 if (asprintf (&reply,
1430 "PacketSize=%x;"
1431 "QStartNoAckMode+;"
1432 "QPassSignals+;"
1433 "QCatchSyscalls+;"
1434 /* Just report support always. */
1435 "qXfer:auxv:read+;"
1436 /* We'll force --vgdb-shadow-registers=yes */
1437 "qXfer:features:read+;"
1438 "qXfer:exec-file:read+;"
1439 "qXfer:siginfo:read+;"
1440 /* Extra vgdb support before valgrind starts up. */
1441 "QEnvironmentHexEncoded+;"
1442 "QEnvironmentReset+;"
1443 "QEnvironmentUnset+;"
1444 "QSetWorkingDir+", (UInt)PBUFSIZ - 1) != -1) {
1445 send_packet(reply, noackmode);
1446 free (reply);
1447 } else {
1448 XERROR(errno, "asprintf failed\n");
1451 else if (strncmp(STARTNOACKMODE, buf, strlen(STARTNOACKMODE)) == 0) {
1452 // We have to ack this one
1453 send_packet("OK", 0);
1454 noackmode = 1;
1456 else if (buf[0] == '!') {
1457 send_packet("OK", noackmode);
1459 else if (buf[0] == '?') {
1460 send_packet("W00", noackmode);
1462 else if (strncmp("H", buf, strlen("H")) == 0) {
1463 // Set thread packet, but we are not running yet.
1464 send_packet("E01", noackmode);
1466 else if (strncmp("vMustReplyEmpty", buf, strlen("vMustReplyEmpty")) == 0) {
1467 send_packet ("", noackmode);
1469 else if (strncmp(QRCMD, buf, strlen(QRCMD)) == 0) {
1470 static const char *no_running_str =
1471 "No running target, monitor commands not available yet.\n";
1472 int str_count = strlen (no_running_str);
1473 char hex[2 * str_count + 1];
1474 hexify(hex, no_running_str, str_count);
1475 send_packet(hex, noackmode);
1477 char *decoded_string = decode_hexstring (buf, strlen (QRCMD) + 1, 0);
1478 DEBUG(1, "qRcmd decoded: %s\n", decoded_string);
1479 free (decoded_string);
1481 else if (strncmp(VRUN, buf, strlen(VRUN)) == 0) {
1482 // vRun;filename[;argument]*
1483 // vRun, filename and arguments are split on ';',
1484 // no ';' at the end.
1485 // If there are no arguments count is one (just the filename).
1486 // Otherwise it is the number of arguments plus one (the filename).
1487 // The filename must be there and starts after the first ';'.
1488 // TODO: Handle vRun;[;argument]*
1489 // https://www.sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
1490 // If filename is an empty string, the stub may use a default program
1491 // (e.g. the last program run).
1492 size_t count = count_delims(';', buf);
1493 size_t *len = vmalloc(count * sizeof(count));
1494 const char *delim = ";";
1495 const char *next_str = next_delim_string(buf, *delim);
1496 char **decoded_string = vmalloc(count * sizeof (char *));
1498 // Count the lenghts of each substring, init to -1 to compensate for
1499 // each substring starting with a delim char.
1500 for (size_t i = 0; i < count; i++)
1501 len[i] = -1;
1502 count_len(';', buf, len);
1503 if (next_str) {
1504 DEBUG(1, "vRun: next_str %s\n", next_str);
1505 for (size_t i = 0; i < count; i++) {
1506 /* Handle the case when the arguments
1507 * was specified to gdb's run command
1508 * but no remote exec-file was set,
1509 * so the first vRun argument is missing.
1510 * For example vRun;;6c. */
1511 if (*next_str == *delim) {
1512 next_str++;
1513 /* empty string that can be freed. */
1514 decoded_string[i] = strdup("");
1516 else {
1517 decoded_string[i] = decode_hexstring (next_str, 0, len[i]);
1518 if (i < count - 1)
1519 next_str = next_delim_string(next_str, *delim);
1521 DEBUG(1, "vRun decoded: %s, next_str %s, len[%zu] %zu\n",
1522 decoded_string[i], next_str, i, len[i]);
1525 /* If we didn't get any arguments or the filename is an empty
1526 string, valgrind won't know which program to run. */
1527 DEBUG (1, "count: %zu, len[0]: %zu\n", count, len[0]);
1528 if (! count || len[0] == 0) {
1529 free(len);
1530 for (size_t i = 0; i < count; i++)
1531 free (decoded_string[i]);
1532 free (decoded_string);
1533 send_packet ("E01", noackmode);
1534 continue;
1537 /* We have collected the decoded strings so we can use them to
1538 launch valgrind with the correct arguments... We then use the
1539 valgrind pid to start relaying packets. */
1540 pid_t valgrind_pid = -1;
1541 int res = fork_and_exec_valgrind ((int)count,
1542 decoded_string,
1543 working_dir,
1544 in_port,
1545 &valgrind_pid);
1547 if (res == 0) {
1548 // Lets report we Stopped with SIGTRAP (05).
1549 send_packet ("S05", noackmode);
1550 prepare_fifos_and_shared_mem(valgrind_pid, check_trials);
1551 DEBUG(1, "from_gdb_to_pid %s, to_gdb_from_pid %s\n",
1552 from_gdb_to_pid, to_gdb_from_pid);
1553 // gdb_relay is an endless loop till valgrind quits.
1554 shutting_down = False;
1556 gdb_relay (valgrind_pid, 1, q_buf);
1557 cleanup_fifos_and_shared_mem();
1558 DEBUG(1, "valgrind relay done\n");
1559 int status;
1560 pid_t p = waitpid (valgrind_pid, &status, 0);
1561 DEBUG(2, "waitpid: %d\n", (int) p);
1562 if (p == -1)
1563 DEBUG(1, "waitpid error %s\n", strerror (errno));
1564 else {
1565 if (WIFEXITED(status))
1566 DEBUG(1, "valgrind exited with %d\n",
1567 WEXITSTATUS(status));
1568 else if (WIFSIGNALED(status))
1569 DEBUG(1, "valgrind kill by signal %d\n",
1570 WTERMSIG(status));
1571 else
1572 DEBUG(1, "valgrind unexpectedly stopped or continued");
1574 } else {
1575 send_packet ("E01", noackmode);
1576 DEBUG(1, "OOPS! couldn't launch valgrind %s\n",
1577 strerror (res));
1580 free(len);
1581 for (size_t i = 0; i < count; i++)
1582 free (decoded_string[i]);
1583 free (decoded_string);
1584 } else {
1585 free(len);
1586 send_packet ("E01", noackmode);
1587 DEBUG(1, "vRun decoding error: no next_string!\n");
1588 continue;
1590 } else if (strncmp(QATTACHED, buf, strlen(QATTACHED)) == 0) {
1591 send_packet ("1", noackmode);
1592 DEBUG(1, "qAttached sent: '1'\n");
1593 const char *next_str = next_delim_string(buf, ':');
1594 if (next_str) {
1595 char *decoded_string = decode_hexstring (next_str, 0, 0);
1596 DEBUG(1, "qAttached decoded: %s, next_str %s\n", decoded_string, next_str);
1597 free (decoded_string);
1598 } else {
1599 DEBUG(1, "qAttached decoding error: strdup of %s failed!\n", buf);
1600 continue;
1602 } /* Reset the state of environment variables in the remote target
1603 before starting the inferior. In this context, reset means
1604 unsetting all environment variables that were previously set
1605 by the user (i.e., were not initially present in the environment). */
1606 else if (strncmp(QENVIRONMENTRESET, buf,
1607 strlen(QENVIRONMENTRESET)) == 0) {
1608 send_packet ("OK", noackmode);
1609 // TODO clear all environment strings. We're not using
1610 // environment strings now. But we should.
1611 } else if (strncmp(QENVIRONMENTHEXENCODED, buf,
1612 strlen(QENVIRONMENTHEXENCODED)) == 0) {
1613 send_packet ("OK", noackmode);
1614 if (!split_hexdecode(buf, QENVIRONMENTHEXENCODED, ":", &string))
1615 break;
1616 // TODO Collect all environment strings and add them to environ
1617 // before launching valgrind.
1618 free (string);
1619 string = NULL;
1620 } else if (strncmp(QENVIRONMENTUNSET, buf,
1621 strlen(QENVIRONMENTUNSET)) == 0) {
1622 send_packet ("OK", noackmode);
1623 if (!split_hexdecode(buf, QENVIRONMENTUNSET, ":", &string))
1624 break;
1625 // TODO Remove this environment string from the collection.
1626 free (string);
1627 string = NULL;
1628 } else if (strncmp(QSETWORKINGDIR, buf,
1629 strlen(QSETWORKINGDIR)) == 0) {
1630 // Silly, but we can only reply OK, even if the working directory is
1631 // bad. Errors will be reported when we try to execute the actual
1632 // process.
1633 send_packet ("OK", noackmode);
1634 // Free any previously set working_dir
1635 free (working_dir);
1636 working_dir = NULL;
1637 if (!split_hexdecode(buf, QSETWORKINGDIR, ":", &working_dir)) {
1638 continue; // We cannot report the error to gdb...
1640 DEBUG(1, "set working dir to: %s\n", working_dir);
1641 } else if (strncmp(XFER, buf, strlen(XFER)) == 0) {
1642 char *buf_dup = strdup(buf);
1643 DEBUG(1, "strdup: buf_dup %s\n", buf_dup);
1644 if (buf_dup) {
1645 const char *delim = ":";
1646 size_t count = count_delims(delim[0], buf);
1647 if (count < 4) {
1648 strsep(&buf_dup, delim);
1649 strsep(&buf_dup, delim);
1650 strsep(&buf_dup, delim);
1651 char *decoded_string = decode_hexstring (buf_dup, 0, 0);
1652 DEBUG(1, "qXfer decoded: %s, buf_dup %s\n", decoded_string, buf_dup);
1653 free (decoded_string);
1655 free (buf_dup);
1656 } else {
1657 DEBUG(1, "qXfer decoding error: strdup of %s failed!\n", buf);
1658 free (buf_dup);
1659 continue;
1661 // Whether we could decode it or not, we cannot handle it now. We
1662 // need valgrind gdbserver to properly reply. So error out here.
1663 send_packet ("E00", noackmode);
1664 } else if (strncmp(QTSTATUS, buf, strlen(QTSTATUS)) == 0) {
1665 // We don't support trace experiments
1666 DEBUG(1, "Got QTSTATUS\n");
1667 send_packet ("", noackmode);
1668 } else if (strcmp("qfThreadInfo", buf) == 0) {
1669 DEBUG(1, "Got qfThreadInfo\n");
1670 /* There are no threads yet, reply 'l' end of list. */
1671 send_packet ("l", noackmode);
1672 } else if (buf[0] != '\0') {
1673 // We didn't understand.
1674 DEBUG(1, "Unknown packet received: '%s'\n", buf);
1675 bad_unknown_packets++;
1676 if (bad_unknown_packets > 10) {
1677 DEBUG(1, "Too many bad/unknown packets received\n");
1678 break;
1680 send_packet ("", noackmode);
1683 DEBUG(1, "done doing multi stuff...\n");
1684 free(working_dir);
1685 free(buf);
1686 free(q_buf);
1688 shutting_down = True;
1689 close (to_gdb);
1690 close (from_gdb);
1693 /* Relay data between gdb and Valgrind gdbserver, till EOF or an error is
1694 encountered. q_buf is the qSupported packet received from gdb. */
1695 static
1696 void gdb_relay(int pid, int send_noack_mode, char *q_buf)
1698 int from_pid = -1; /* fd to read from pid */
1699 int to_pid = -1; /* fd to write to pid */
1701 int shutdown_loop = 0;
1702 TSFPRINTF(stderr, "relaying data between gdb and process %d\n", pid);
1704 if (max_invoke_ms > 0)
1705 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1706 invoke_gdbserver_in_valgrind, (void *) &pid);
1707 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1708 acquire_lock(shared_mem_fd, pid);
1710 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
1711 "read mode from pid");
1713 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1715 Bool waiting_for_noack_mode = False;
1716 Bool waiting_for_qsupported = False;
1717 if(send_noack_mode) {
1718 DEBUG(1, "gdb_relay: to_pid %d, from_pid: %d\n", to_pid, from_pid);
1719 write_buf(to_pid, "$QStartNoAckMode#b0", 19,
1720 "write start no ack mode",
1721 /* notify */ True);
1722 waiting_for_noack_mode = True;
1725 while (1) {
1726 ConnectionKind ck;
1727 int ret;
1728 struct pollfd pollfds[NumConnectionKind];
1730 /* watch data written by gdb, watch POLLERR on both gdb fd */
1731 pollfds[FROM_GDB].fd = from_gdb;
1732 pollfds[FROM_GDB].events = POLLIN;
1733 pollfds[FROM_GDB].revents = 0;
1734 pollfds[TO_GDB].fd = to_gdb;
1735 pollfds[TO_GDB].events = 0;
1736 pollfds[TO_GDB].revents = 0;
1738 /* watch data written by pid, watch POLLERR on both pid fd */
1739 pollfds[FROM_PID].fd = from_pid;
1740 pollfds[FROM_PID].events = POLLIN;
1741 pollfds[FROM_PID].revents = 0;
1742 pollfds[TO_PID].fd = to_pid;
1743 pollfds[TO_PID].events = 0;
1744 pollfds[TO_PID].revents = 0;
1746 ret = poll(pollfds,
1747 NumConnectionKind,
1748 (shutting_down ?
1749 1 /* one second */
1750 : -1 /* infinite */));
1751 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1753 /* check for unexpected error */
1754 if (ret <= 0 && errno != EINTR) {
1755 ERROR(errno, "unexpected poll ret %d\n", ret);
1756 shutting_down = True;
1757 break;
1760 /* check for data to read */
1761 for (ck = 0; ck < NumConnectionKind; ck ++) {
1762 if (pollfds[ck].revents & POLLIN) {
1763 switch (ck) {
1764 case FROM_GDB:
1765 if (waiting_for_noack_mode || waiting_for_qsupported)
1766 break; /* Don't add any messages while vgdb is talking. */
1767 if (!read_from_gdb_write_to_pid(to_pid))
1768 shutting_down = True;
1769 break;
1770 case FROM_PID:
1771 // First handle any messages from vgdb
1772 if (waiting_for_noack_mode) {
1773 char buf[PBUFSIZ+1]; // +1 for trailing \0
1774 size_t buflen;
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 %zu, buf %s\n",
1779 buflen, buf);
1780 else
1781 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1783 waiting_for_noack_mode = False;
1785 /* Propagate qSupported to valgrind, we already replied. */
1786 if (q_buf != NULL && q_buf[0] != '\0') {
1787 char *pkt = create_packet (q_buf);
1788 write_buf(to_pid, pkt, strlen(pkt),
1789 "write qSupported", /* notify */ True);
1790 free(pkt);
1791 waiting_for_qsupported = True;
1793 } else if (waiting_for_qsupported) {
1794 char buf[PBUFSIZ+1]; // +1 for trailing \0
1795 size_t buflen;
1796 buflen = getpkt(buf, from_pid, to_pid);
1797 /* Should we sanity check the result? */
1798 if (buflen > 0) {
1799 waiting_for_qsupported = False;
1800 } else {
1801 ERROR(0, "Unexpected getpkt for qSupported reply: %zu\n",
1802 buflen);
1804 } else if (!read_from_pid_write_to_gdb(from_pid))
1805 shutting_down = True;
1806 break;
1807 default: XERROR(0, "unexpected POLLIN on %s\n",
1808 ppConnectionKind(ck));
1813 /* check for an fd being in error condition */
1814 for (ck = 0; ck < NumConnectionKind; ck ++) {
1815 if (pollfds[ck].revents & POLLERR) {
1816 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1817 ppConnectionKind(ck), pollfds[ck].fd);
1818 invoker_valgrind_dying();
1819 shutting_down = True;
1821 if (pollfds[ck].revents & POLLHUP) {
1822 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1823 ppConnectionKind(ck), pollfds[ck].fd);
1824 invoker_valgrind_dying();
1825 shutting_down = True;
1827 if (pollfds[ck].revents & POLLNVAL) {
1828 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1829 ppConnectionKind(ck), pollfds[ck].fd);
1830 invoker_valgrind_dying();
1831 shutting_down = True;
1835 if (shutting_down) {
1836 /* we let some time to the final packets to be transferred */
1837 shutdown_loop++;
1838 if (shutdown_loop > 3)
1839 break;
1842 close_connection(to_pid, from_pid);
1845 static int packet_len_for_command(char *cmd)
1847 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1848 return 7+ 2*strlen(cmd) +3 + 1;
1851 /* hyper-minimal protocol implementation that
1852 sends the provided commands (using qRcmd packets)
1853 and read and display their replies. */
1854 static
1855 void standalone_send_commands(int pid,
1856 int last_command,
1857 char *commands[] )
1859 int from_pid = -1; /* fd to read from pid */
1860 int to_pid = -1; /* fd to write to pid */
1862 int i;
1863 size_t hi;
1864 char hex[3];
1865 unsigned char cksum;
1866 char *hexcommand;
1867 char buf[PBUFSIZ+1]; // +1 for trailing \0
1868 int buflen;
1869 int nc;
1872 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
1873 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1874 invoke_gdbserver_in_valgrind, (void *) &pid);
1876 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1877 acquire_lock(shared_mem_fd, pid);
1879 /* first send a C-c \003 to pid, so that it wakes up the process
1880 After that, we can open the fifo from the pid in read mode
1881 We then start to wait for packets (normally first a resume reply)
1882 At that point, we send our command and expect replies */
1883 buf[0] = '\003';
1884 i = 0;
1885 while (!write_buf(to_pid, buf, 1,
1886 "write \\003 to wake up", /* notify */ True)) {
1887 /* If write fails, retries up to 10 times every 0.5 seconds
1888 This aims at solving the race condition described in
1889 remote-utils.c remote_finish function. */
1890 usleep(500*1000);
1891 i++;
1892 if (i >= 10)
1893 XERROR(errno, "failed to send wake up char after 10 trials\n");
1895 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1896 "read cmd result from pid");
1898 /* Enable no ack mode. */
1899 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
1900 /* notify */ True);
1901 buflen = getpkt(buf, from_pid, to_pid);
1902 if (buflen != 2 || strcmp(buf, "OK") != 0) {
1903 if (buflen != 2)
1904 ERROR(0, "no ack mode: unexpected buflen %d\n", buflen);
1905 else
1906 ERROR(0, "no ack mode: unexpected packet %s\n", buf);
1909 for (nc = 0; nc <= last_command; nc++) {
1910 TSFPRINTF(stderr, "sending command %s to pid %d\n", commands[nc], pid);
1912 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1913 hexcommand = vmalloc(packet_len_for_command(commands[nc]));
1914 hexcommand[0] = 0;
1915 strcat(hexcommand, "$qRcmd,");
1916 for (size_t nci = 0; nci < strlen(commands[nc]); nci++) {
1917 sprintf(hex, "%02x", (unsigned char) commands[nc][nci]);
1918 // Need to use unsigned char, to avoid sign extension.
1919 strcat(hexcommand, hex);
1921 /* checksum (but without the $) */
1922 cksum = 0;
1923 for (hi = 1; hi < strlen(hexcommand); hi++)
1924 cksum+=hexcommand[hi];
1925 strcat(hexcommand, "#");
1926 sprintf(hex, "%02x", cksum);
1927 strcat(hexcommand, hex);
1928 write_buf(to_pid, hexcommand, strlen(hexcommand),
1929 "writing hex command to pid", /* notify */ True);
1931 /* we exit of the below loop explicitly when the command has
1932 been handled or because a signal handler will set
1933 shutting_down. */
1934 while (!shutting_down) {
1935 buflen = getpkt(buf, from_pid, to_pid);
1936 if (buflen < 0) {
1937 ERROR(0, "error reading packet\n");
1938 if (buflen == -2)
1939 invoker_valgrind_dying();
1940 break;
1942 if (strlen(buf) == 0) {
1943 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1944 break;
1946 if (strcmp(buf, "OK") == 0) {
1947 DEBUG(1, "OK packet rcvd\n");
1948 break;
1950 if (buf[0] == 'E') {
1951 DEBUG(0,
1952 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1953 buf);
1954 break;
1956 if (buf[0] == 'W') {
1957 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1958 break;
1960 if (buf[0] == 'T') {
1961 DEBUG(1, "T resume reply packet received: %s\n", buf);
1962 continue;
1965 /* must be here an O packet with hex encoded string reply
1966 => decode and print it */
1967 if (buf[0] != 'O') {
1968 DEBUG(0, "expecting O packet, received: %s\n", buf);
1969 continue;
1972 char buf_print[buflen/2 + 1];
1973 for (i = 1; i < buflen; i = i + 2)
1974 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1975 + fromhex(*(buf+i+1));
1976 buf_print[buflen/2] = 0;
1977 printf("%s", buf_print);
1978 fflush(stdout);
1981 free(hexcommand);
1983 shutting_down = True;
1985 close_connection(to_pid, from_pid);
1988 /* report to user the existence of a vgdb-able valgrind process
1989 with given pid.
1990 Note: this function does not use XERROR if an error is encountered
1991 while producing the command line for pid, as this is not critical
1992 and at least on MacOS, reading cmdline is not available. */
1993 static
1994 void report_pid(int pid, Bool on_stdout)
1996 char cmdline_file[50]; // large enough
1997 int fd;
1998 size_t i;
1999 FILE *out = on_stdout ? stdout : stderr;
2001 TSFPRINTF(out, "use --pid=%d for ", pid);
2003 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
2004 fd = open(cmdline_file, O_RDONLY | O_CLOEXEC);
2005 if (fd == -1) {
2006 DEBUG(1, "error opening cmdline file %s %s\n",
2007 cmdline_file, strerror(errno));
2008 fprintf(out, "(could not open process command line)\n");
2009 } else {
2010 #define MAX_CMDLINE 4096
2011 char cmdline[MAX_CMDLINE];
2012 size_t nr_read = 0;
2013 while (nr_read < MAX_CMDLINE - 1) {
2014 ssize_t sz = read(fd, cmdline, MAX_CMDLINE - nr_read - 1);
2015 if (sz == 0)
2016 break;
2017 if (sz < 0) {
2018 if (errno == EINTR || errno == EAGAIN)
2019 continue;
2020 else {
2021 DEBUG(1, "error reading cmdline file %s %s\n",
2022 cmdline_file, strerror(errno));
2023 fprintf(out, "(error reading process command line)\n");
2024 close (fd);
2025 return;
2028 nr_read += sz;
2031 for (i = 0; i < nr_read; i++)
2032 if (cmdline[i] == 0)
2033 cmdline[i] = ' ';
2034 cmdline[nr_read] = 0;
2036 fprintf(out, "%s", cmdline);
2037 fprintf(out, "\n");
2038 close(fd);
2040 fflush(out);
2043 static
2044 void usage(void)
2046 fprintf(stderr,
2047 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
2048 "vgdb (valgrind gdb) has two usages\n"
2049 " 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
2050 " The OPTION(s) must be followed by the command to send\n"
2051 " To send more than one command, separate the commands with -c\n"
2052 " 2. relay application between gdb and a Valgrind gdbserver.\n"
2053 " Only OPTION(s) can be given.\n"
2054 "\n"
2055 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
2056 " [--wait=<number>] [--max-invoke-ms=<number>]\n"
2057 " [--port=<portnr>\n"
2058 " [--cmd-time-out=<number>] [-l] [-T] [-D] [-d]\n"
2059 " [--multi] [--valgrind=<valgrind-exe>] [--vargs ...]\n"
2060 " \n"
2061 " --pid arg must be given if multiple Valgrind gdbservers are found.\n"
2062 " --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
2063 " if you want to change the prefix (default %s) for the FIFOs communication\n"
2064 " between the Valgrind gdbserver and vgdb.\n"
2065 " --wait (default 0) tells vgdb to check during the specified number\n"
2066 " of seconds if a Valgrind gdbserver can be found.\n"
2067 " --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
2068 " will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
2069 " process is blocked in a system call).\n"
2070 " --port instructs vgdb to listen for gdb on the specified port nr.\n"
2071 " --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
2072 " gdbserver has not processed a command after number seconds\n"
2073 " --multi start in extended-remote mode, wait for gdb to tell us what to run\n"
2074 " --valgrind, pass the path to valgrind to use. If not specified, the system valgrind will be launched.\n"
2075 " --vargs everything that follows is an argument for valgrind.\n"
2076 " -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
2077 " -T arg tells to add timestamps to vgdb information messages.\n"
2078 " -D arg tells to show shared mem status and then exit.\n"
2079 " -d arg tells to show debug info. Multiple -d args for more debug info\n"
2080 "\n"
2081 " -h --help shows this message\n"
2082 #ifdef VG_GDBSCRIPTS_DIR
2083 " The GDB python code defining GDB front end valgrind commands is:\n %s\n"
2084 #endif
2085 " To get help from the Valgrind gdbserver, use vgdb help\n"
2086 "\n", vgdb_prefix_default()
2087 #ifdef VG_GDBSCRIPTS_DIR
2088 , VG_GDBSCRIPTS_DIR "/valgrind-monitor.py"
2089 #endif
2091 invoker_restrictions_msg();
2094 /* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
2095 and then exits.
2097 else if arg_pid == -1, waits maximum check_trials seconds to discover
2098 a valgrind pid appearing.
2100 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2101 with gdbserver activated.
2103 Returns the pid to work with
2104 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2106 static
2107 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
2109 int i;
2110 int pid = -1;
2112 if (arg_pid == 0 || arg_pid < -1) {
2113 TSFPRINTF(stderr, "vgdb error: invalid pid %d given\n", arg_pid);
2114 early_exit(1, "vgdb error: invalid pid given");
2115 } else {
2116 /* search for a matching named fifo.
2117 If we have been given a pid, we will check that the matching FIFO is
2118 there (or wait the nr of check_trials for this to appear).
2119 If no pid has been given, then if we find only one FIFO,
2120 we will use this to build the pid to use.
2121 If we find multiple processes with valid FIFO, we report them and will
2122 exit with an error. */
2123 DIR *vgdb_dir;
2124 char *vgdb_dir_name = vmalloc(strlen (vgdb_prefix) + 3);
2125 struct dirent *f;
2126 int is;
2127 int nr_valid_pid = 0;
2128 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
2129 char *vgdb_format = vmalloc(strlen(vgdb_prefix) + strlen(suffix) + 1);
2131 strcpy(vgdb_format, vgdb_prefix);
2132 strcat(vgdb_format, suffix);
2134 if (strchr(vgdb_prefix, '/') != NULL) {
2135 strcpy(vgdb_dir_name, vgdb_prefix);
2136 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
2137 if (vgdb_dir_name[is] == '/') {
2138 vgdb_dir_name[is+1] = '\0';
2139 break;
2141 } else {
2142 strcpy(vgdb_dir_name, "");
2145 DEBUG(1, "searching pid in directory %s format %s\n",
2146 vgdb_dir_name, vgdb_format);
2148 /* try to find FIFOs with valid pid.
2149 On exit of the loop, pid is set to:
2150 the last pid found if show_list (or -1 if no process was listed)
2151 -1 if no FIFOs matching a running process is found
2152 -2 if multiple FIFOs of running processes are found
2153 otherwise it is set to the (only) pid found that can be debugged
2155 for (i = 0; i < check_trials; i++) {
2156 DEBUG(1, "check_trial %d \n", i);
2157 if (i > 0)
2158 /* wait one second before checking again */
2159 sleep(1);
2161 vgdb_dir = opendir(strlen(vgdb_dir_name) ? vgdb_dir_name : "./");
2162 if (vgdb_dir == NULL)
2163 XERROR(errno,
2164 "vgdb error: opening directory %s searching vgdb fifo\n",
2165 vgdb_dir_name);
2167 errno = 0; /* avoid complain if vgdb_dir is empty */
2168 while ((f = readdir(vgdb_dir))) {
2169 struct stat st;
2170 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
2171 char *wrongpid;
2172 int newpid;
2174 strcpy(pathname, vgdb_dir_name);
2175 strcat(pathname, f->d_name);
2176 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
2177 if (stat(pathname, &st) != 0) {
2178 if (debuglevel >= 3)
2179 ERROR(errno, "vgdb error: stat %s searching vgdb fifo\n",
2180 pathname);
2181 } else if (S_ISFIFO(st.st_mode)) {
2182 DEBUG(3, "trying FIFO %s\n", pathname);
2183 if (strncmp(pathname, vgdb_format,
2184 strlen(vgdb_format)) == 0) {
2185 newpid = strtol(pathname + strlen(vgdb_format),
2186 &wrongpid, 10);
2187 if (*wrongpid == '-' && newpid > 0
2188 && kill(newpid, 0) == 0) {
2189 nr_valid_pid++;
2190 if (show_list) {
2191 report_pid(newpid, /*on_stdout*/ True);
2192 pid = newpid;
2193 } else if (arg_pid != -1) {
2194 if (arg_pid == newpid) {
2195 pid = newpid;
2197 } else if (nr_valid_pid > 1) {
2198 if (nr_valid_pid == 2) {
2199 TSFPRINTF
2200 (stderr,
2201 "no --pid= arg given"
2202 " and multiple valgrind pids found:\n");
2203 report_pid(pid, /*on_stdout*/ False);
2205 pid = -2;
2206 report_pid(newpid, /*on_stdout*/ False);
2207 } else {
2208 pid = newpid;
2213 errno = 0; /* avoid complain if at the end of vgdb_dir */
2215 if (f == NULL && errno != 0) {
2216 ERROR(errno, "vgdb error: reading directory %s for vgdb fifo\n",
2217 vgdb_dir_name);
2218 early_exit(1, "vgdb error reading vgdb fifo directory");
2221 closedir(vgdb_dir);
2222 if (pid != -1)
2223 break;
2226 free(vgdb_dir_name);
2227 free(vgdb_format);
2230 if (show_list) {
2231 exit(1);
2232 } else if (pid == -1) {
2233 if (arg_pid == -1) {
2234 TSFPRINTF(stderr, "vgdb error: no FIFO found and no pid given\n");
2235 early_exit(1, "vgdb error: no FIFO found and no pid given");
2236 } else {
2237 TSFPRINTF(stderr, "vgdb error: no FIFO found matching pid %d\n",
2238 arg_pid);
2239 early_exit(1, "vgdb error: no FIFO found matching the give pid");
2242 else if (pid == -2) {
2243 early_exit(1, "no --pid= arg_pid given and multiple valgrind pids found.");
2245 else {
2246 return pid;
2249 abort (); // Impossible
2252 /* return true if the numeric value of an option of the
2253 form --xxxxxxxxx=<number> could properly be extracted
2254 from arg. If True is returned, *value contains the
2255 extracted value.*/
2256 static
2257 Bool numeric_val(char* arg, int *value)
2259 const char *eq_pos = strchr(arg, '=');
2260 char *wrong;
2261 long long int long_value;
2263 if (eq_pos == NULL)
2264 return False;
2266 long_value = strtoll(eq_pos+1, &wrong, 10);
2267 if (long_value < 0 || long_value > INT_MAX)
2268 return False;
2269 if (*wrong)
2270 return False;
2272 *value = (int) long_value;
2273 return True;
2276 /* true if arg matches the provided option */
2277 static
2278 Bool is_opt(char* arg, const char *option)
2280 int option_len = strlen(option);
2281 if (option[option_len-1] == '=')
2282 return (0 == strncmp(option, arg, option_len));
2283 else
2284 return (0 == strcmp(option, arg));
2287 /* Parse command lines options. If error(s), exits.
2288 Otherwise returns the options in *p_... args.
2289 commands must be big enough for the commands extracted from argv.
2290 On return, *p_last_command gives the position in commands where
2291 the last command has been allocated (using vmalloc). */
2292 static
2293 void parse_options(int argc, char** argv,
2294 Bool *p_show_shared_mem,
2295 Bool *p_show_list,
2296 Bool *p_multi_mode,
2297 int *p_arg_pid,
2298 int *p_check_trials,
2299 int *p_port,
2300 int *p_last_command,
2301 char *commands[])
2303 Bool show_shared_mem = False;
2304 Bool show_list = False;
2305 Bool multi_mode = False;
2306 int arg_pid = -1;
2307 int check_trials = 1;
2308 int last_command = -1;
2309 int int_port = 0;
2311 int i;
2312 int arg_errors = 0;
2314 for (i = 1; i < argc; i++) {
2315 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2316 usage();
2317 early_exit(0, "--help requested");
2318 } else if (is_opt(argv[i], "-d")) {
2319 debuglevel++;
2320 } else if (is_opt(argv[i], "-D")) {
2321 show_shared_mem = True;
2322 } else if (is_opt(argv[i], "-l")) {
2323 show_list = True;
2324 } else if (is_opt(argv[i], "--multi")) {
2325 multi_mode = True;
2326 } else if (is_opt(argv[i], "-T")) {
2327 timestamp = True;
2328 } else if (is_opt(argv[i], "--pid=")) {
2329 int newpid;
2330 if (!numeric_val(argv[i], &newpid)) {
2331 TSFPRINTF(stderr, "invalid --pid argument %s\n", argv[i]);
2332 arg_errors++;
2333 } else if (arg_pid != -1) {
2334 TSFPRINTF(stderr, "multiple --pid arguments given\n");
2335 arg_errors++;
2336 } else {
2337 arg_pid = newpid;
2339 } else if (is_opt(argv[i], "--wait=")) {
2340 if (!numeric_val(argv[i], &check_trials)) {
2341 TSFPRINTF(stderr, "invalid --wait argument %s\n", argv[i]);
2342 arg_errors++;
2344 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2345 if (!numeric_val(argv[i], &max_invoke_ms)) {
2346 TSFPRINTF(stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
2347 arg_errors++;
2349 } else if (is_opt(argv[i], "--cmd-time-out=")) {
2350 if (!numeric_val(argv[i], &cmd_time_out)) {
2351 TSFPRINTF(stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
2352 arg_errors++;
2354 } else if (is_opt(argv[i], "--port=")) {
2355 if (!numeric_val(argv[i], &int_port)) {
2356 TSFPRINTF(stderr, "invalid --port argument %s\n", argv[i]);
2357 arg_errors++;
2359 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2360 if (vgdb_prefix) {
2361 // was specified more than once on the command line
2362 // ignore earlier uses
2363 free(vgdb_prefix);
2365 vgdb_prefix = strdup (argv[i] + 14);
2366 } else if (is_opt(argv[i], "--valgrind=")) {
2367 char *path = argv[i] + 11;
2368 /* Compute the absolute path. */
2369 valgrind_path = realpath(path, NULL);
2370 if (!valgrind_path) {
2371 TSFPRINTF(stderr, "%s is not a correct path. %s, exiting.\n",
2372 path, strerror (errno));
2373 early_exit(1, "incorrect valgrind path");
2375 DEBUG(2, "valgrind's real path: %s\n", valgrind_path);
2376 } else if (is_opt(argv[i], "--vargs")) {
2377 // Everything that follows now is an argument for valgrind
2378 // No other options (or commands) can follow
2379 // argc - i is the number of left over arguments
2380 // allocate enough space, put all args in it.
2381 cvargs = argc - i - 1;
2382 vargs = vmalloc (cvargs * sizeof(*vargs));
2383 i++;
2384 for (int j = 0; i < argc; i++) {
2385 vargs[j] = argv[i];
2386 j++;
2388 } else if (is_opt(argv[i], "-c")) {
2389 last_command++;
2390 commands[last_command] = vmalloc(1);
2391 commands[last_command][0] = '\0';
2392 } else if (0 == strncmp(argv[i], "-", 1)) {
2393 TSFPRINTF(stderr, "unknown or invalid argument %s\n", argv[i]);
2394 arg_errors++;
2395 } else {
2396 int len;
2397 if (last_command == -1) {
2398 /* only one command, no -c command indicator */
2399 last_command++;
2400 commands[last_command] = vmalloc(1);
2401 commands[last_command][0] = '\0';
2403 len = strlen(commands[last_command]);
2404 commands[last_command] = vrealloc(commands[last_command],
2405 len + 1 + strlen(argv[i]) + 1);
2406 if (len > 0)
2407 strcat(commands[last_command], " ");
2408 strcat(commands[last_command], argv[i]);
2409 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2410 TSFPRINTF(stderr, "command %s too long\n", commands[last_command]);
2411 arg_errors++;
2417 if (vgdb_prefix == NULL)
2418 vgdb_prefix = vgdb_prefix_default();
2420 if (multi_mode
2421 && (show_shared_mem
2422 || show_list
2423 || last_command != -1)) {
2424 arg_errors++;
2425 TSFPRINTF(stderr,
2426 "Cannot use -D, -l or COMMANDs when using --multi mode\n");
2429 if (isatty(from_gdb)
2430 && !show_shared_mem
2431 && !show_list
2432 && int_port == 0
2433 && last_command == -1) {
2434 arg_errors++;
2435 TSFPRINTF(stderr,
2436 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2439 if (show_shared_mem && show_list) {
2440 arg_errors++;
2441 TSFPRINTF(stderr,
2442 "Can't use both -D and -l options\n");
2445 if (max_invoke_ms > 0
2446 && cmd_time_out != NEVER
2447 && (cmd_time_out * 1000) <= max_invoke_ms) {
2448 arg_errors++;
2449 TSFPRINTF(stderr,
2450 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2453 if (show_list && arg_pid != -1) {
2454 arg_errors++;
2455 TSFPRINTF(stderr,
2456 "Can't use both --pid and -l options\n");
2459 if (int_port > 0 && last_command != -1) {
2460 arg_errors++;
2461 TSFPRINTF(stderr,
2462 "Can't use --port to send commands\n");
2465 if (arg_errors > 0) {
2466 TSFPRINTF(stderr, "args error. Try `vgdb --help` for more information\n");
2467 early_exit(1, "invalid args given to vgdb");
2470 *p_show_shared_mem = show_shared_mem;
2471 *p_show_list = show_list;
2472 *p_multi_mode = multi_mode;
2473 *p_arg_pid = arg_pid;
2474 *p_check_trials = check_trials;
2475 *p_port = int_port;
2476 *p_last_command = last_command;
2479 int main(int argc, char** argv)
2481 int i;
2482 int pid;
2484 Bool show_shared_mem;
2485 Bool show_list;
2486 Bool multi_mode;
2487 int arg_pid;
2488 int check_trials;
2489 int in_port;
2490 int last_command;
2491 char *commands[argc]; // we will never have more commands than args.
2493 parse_options(argc, argv,
2494 &show_shared_mem,
2495 &show_list,
2496 &multi_mode,
2497 &arg_pid,
2498 &check_trials,
2499 &in_port,
2500 &last_command,
2501 commands);
2503 /* when we are working as a relay for gdb, handle some signals by
2504 only reporting them (according to debug level). Also handle these
2505 when ptrace will be used: vgdb must clean up the ptrace effect before
2506 dying. */
2507 if (max_invoke_ms > 0 || last_command == -1)
2508 install_handlers();
2510 if (!multi_mode) {
2511 pid = search_arg_pid(arg_pid, check_trials, show_list);
2513 /* We pass 1 for check_trials here, because search_arg_pid already waited. */
2514 prepare_fifos_and_shared_mem(pid, 1);
2515 } else {
2516 pid = 0;
2519 if (in_port > 0)
2520 wait_for_gdb_connect(in_port);
2522 if (show_shared_mem) {
2523 TSFPRINTF(stderr,
2524 "vgdb %d "
2525 "written_by_vgdb %d "
2526 "seen_by_valgrind %d\n",
2527 VS_vgdb_pid,
2528 VS_written_by_vgdb,
2529 VS_seen_by_valgrind);
2530 TSFPRINTF(stderr, "vgdb pid %d\n", VS_vgdb_pid);
2531 early_exit(0, "-D arg to show shared memory and exit given.");
2534 if (multi_mode) {
2535 /* check_trials is the --wait argument in seconds, defaulting to 1
2536 * if not given. */
2537 do_multi_mode (check_trials, in_port);
2538 } else if (last_command >= 0) {
2539 standalone_send_commands(pid, last_command, commands);
2540 } else {
2541 gdb_relay(pid, 0, NULL);
2544 free(vgdb_prefix);
2545 free(valgrind_path);
2546 if (!multi_mode)
2547 cleanup_fifos_and_shared_mem();
2549 for (i = 0; i <= last_command; i++)
2550 free(commands[i]);
2551 return 0;