blob: f546011c71998966c5c05459424550c3f7caf4ff [file] [log] [blame]
sewardj3b290482011-05-06 21:02:55 +00001/*--------------------------------------------------------------------*/
2/*--- Relay between gdb and gdbserver embedded in valgrind vgdb.c ---*/
3/*--------------------------------------------------------------------*/
4
5/*
6 This file is part of Valgrind, a dynamic binary instrumentation
7 framework.
8
sewardjb3a1e4b2015-08-21 11:32:26 +00009 Copyright (C) 2011-2015 Philippe Waroquiers
sewardj3b290482011-05-06 21:02:55 +000010
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.
15
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.
20
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
24 02111-1307, USA.
25
26 The GNU General Public License is contained in the file COPYING.
27*/
sewardj0ba37c92011-07-12 11:46:24 +000028
philippe3c761f02013-12-01 14:56:28 +000029#include "vgdb.h"
30
florianb985e2d2011-09-29 03:03:45 +000031#include "config.h"
sewardjcbe38502011-07-12 11:59:11 +000032
philippe3c761f02013-12-01 14:56:28 +000033#include <assert.h>
34#include <dirent.h>
35#include <errno.h>
36#include <fcntl.h>
sewardj30b3eca2011-06-28 08:20:39 +000037#include <limits.h>
sewardj3b290482011-05-06 21:02:55 +000038#include <poll.h>
39#include <pthread.h>
philippe3c761f02013-12-01 14:56:28 +000040#include <signal.h>
sewardj3b290482011-05-06 21:02:55 +000041#include <stdlib.h>
42#include <stdio.h>
philippe3c761f02013-12-01 14:56:28 +000043#include <string.h>
44#include <unistd.h>
45#include <netinet/in.h>
46#include <sys/mman.h>
47#include <sys/socket.h>
sewardj3b290482011-05-06 21:02:55 +000048#include <sys/stat.h>
49#include <sys/time.h>
philippe3c761f02013-12-01 14:56:28 +000050
sewardj3b290482011-05-06 21:02:55 +000051/* vgdb has two usages:
52 1. relay application between gdb and the gdbserver embedded in valgrind.
53 2. standalone to send monitor commands to a running valgrind-ified process
54
55 It is made of a main program which reads arguments. If no
56 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
57 assumed.
58
59 As relay application, vgdb reads bytes from gdb on stdin and
60 writes these bytes to valgrind. Bytes read from valgrind are
61 written to gdb on stdout. Read/Write from/to valgrind is done
62 using FIFOs. There is one thread reading from stdin, writing to
63 valgrind on a FIFO. There is one thread reading from valgrind on a
64 FIFO, writing to gdb on stdout
65
66 As a standalone utility, vgdb builds command packets to write to valgrind,
67 sends it and reads the reply. The same two threads are used to write/read.
68 Once all the commands are sent and their replies received, vgdb will exit.
sewardj3b290482011-05-06 21:02:55 +000069*/
70
philippe3c761f02013-12-01 14:56:28 +000071int debuglevel;
72struct timeval dbgtv;
florianb985e2d2011-09-29 03:03:45 +000073static char *vgdb_prefix = NULL;
sewardj3b290482011-05-06 21:02:55 +000074
75/* Will be set to True when any condition indicating we have to shutdown
76 is encountered. */
philippe3c761f02013-12-01 14:56:28 +000077Bool shutting_down = False;
sewardj3b290482011-05-06 21:02:55 +000078
philippe3c761f02013-12-01 14:56:28 +000079VgdbShared32 *shared32;
80VgdbShared64 *shared64;
sewardj3b290482011-05-06 21:02:55 +000081#define VS_written_by_vgdb (shared32 != NULL ? \
82 shared32->written_by_vgdb \
83 : shared64->written_by_vgdb)
84#define VS_seen_by_valgrind (shared32 != NULL ? \
85 shared32->seen_by_valgrind \
86 : shared64->seen_by_valgrind)
87
88#define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
89
sewardj3b290482011-05-06 21:02:55 +000090void *vmalloc(size_t size)
91{
92 void * mem = malloc(size);
93 if (mem == NULL)
94 XERROR (errno, "can't allocate memory\n");
95 return mem;
96}
97
sewardj3b290482011-05-06 21:02:55 +000098void *vrealloc(void *ptr,size_t size)
99{
100 void * mem = realloc(ptr, size);
101 if (mem == NULL)
102 XERROR (errno, "can't reallocate memory\n");
103 return mem;
104}
105
florianb985e2d2011-09-29 03:03:45 +0000106/* Return the name of a directory for temporary files. */
107static
108const char *vgdb_tmpdir(void)
109{
110 const char *tmpdir;
111
112 tmpdir = getenv("TMPDIR");
philippeae52a932012-01-13 21:36:46 +0000113 if (tmpdir == NULL || *tmpdir == '\0')
114 tmpdir = VG_TMPDIR;
115 if (tmpdir == NULL || *tmpdir == '\0')
116 tmpdir = "/tmp"; /* fallback */
florianb985e2d2011-09-29 03:03:45 +0000117
118 return tmpdir;
119}
120
philippeae52a932012-01-13 21:36:46 +0000121/* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
florianb985e2d2011-09-29 03:03:45 +0000122 to communicate with valgrind */
123static
124char *vgdb_prefix_default(void)
125{
philippeae52a932012-01-13 21:36:46 +0000126 static HChar *prefix;
florianb985e2d2011-09-29 03:03:45 +0000127
philippeae52a932012-01-13 21:36:46 +0000128 if (prefix == NULL) {
129 const char *tmpdir = vgdb_tmpdir();
130 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
131 strcpy(prefix, tmpdir);
132 strcat(prefix, "/vgdb-pipe");
133 }
florianb985e2d2011-09-29 03:03:45 +0000134 return prefix;
135}
136
sewardj3b290482011-05-06 21:02:55 +0000137/* add nrw to the written_by_vgdb field of shared32 or shared64 */
138static
139void add_written(int nrw)
140{
141 if (shared32 != NULL)
142 shared32->written_by_vgdb += nrw;
143 else if (shared64 != NULL)
144 shared64->written_by_vgdb += nrw;
145 else
146 assert(0);
147}
148
149static int shared_mem_fd = -1;
150static
151void map_vgdbshared (char* shared_mem)
152{
153 struct stat fdstat;
154 void **s;
155 shared_mem_fd = open(shared_mem, O_RDWR);
156 /* shared_mem_fd will not be closed till vgdb exits. */
157
158 if (shared_mem_fd == -1)
159 XERROR (errno, "error opening %s shared memory file\n", shared_mem);
160
161 if (fstat(shared_mem_fd, &fdstat) != 0)
162 XERROR (errno, "fstat");
163
164 if (fdstat.st_size == sizeof(VgdbShared64))
165 s = (void*) &shared64;
166 else if (fdstat.st_size == sizeof(VgdbShared32))
167 s = (void*) &shared32;
168 else
169#if VEX_HOST_WORDSIZE == 8
170 XERROR (0,
171 "error size shared memory file %s.\n"
172 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
173 shared_mem,
174 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
175 (long int)fdstat.st_size);
176#elif VEX_HOST_WORDSIZE == 4
177 XERROR (0,
178 "error size shared memory file %s.\n"
179 "expecting size %d (32bits) got %ld.\n",
180 shared_mem,
181 (int) sizeof(VgdbShared32),
182 fdstat.st_size);
183#else
184# error "unexpected wordsize"
185#endif
186
187#if VEX_HOST_WORDSIZE == 4
188 if (shared64 != NULL)
189 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
190 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
191#endif
192
193 *s = (void*) mmap (NULL, fdstat.st_size,
194 PROT_READ|PROT_WRITE, MAP_SHARED,
195 shared_mem_fd, 0);
196
197 if (*s == (void *) -1)
198 XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
199
200}
201
sewardj3b290482011-05-06 21:02:55 +0000202/* This function loops till shutting_down becomes true. In this loop,
203 it verifies if valgrind process is reading the characters written
204 by vgdb. The verification is done every max_invoke_ms ms. If
philippe3c761f02013-12-01 14:56:28 +0000205 valgrind is not reading characters, it will use invoker_invoke_gdbserver
206 to ensure that the gdbserver code is called soon by valgrind. */
sewardj3b290482011-05-06 21:02:55 +0000207static int max_invoke_ms = 100;
sewardj30b3eca2011-06-28 08:20:39 +0000208#define NEVER 99999999
209static int cmd_time_out = NEVER;
sewardj3b290482011-05-06 21:02:55 +0000210static
211void *invoke_gdbserver_in_valgrind(void *v_pid)
212{
sewardj30b3eca2011-06-28 08:20:39 +0000213 struct timeval cmd_max_end_time;
214 Bool cmd_started = False;
215 struct timeval invoke_time;
216
sewardj3b290482011-05-06 21:02:55 +0000217 int pid = *(int *)v_pid;
218 int written_by_vgdb_before_sleep;
219 int seen_by_valgrind_before_sleep;
220
221 int invoked_written = -1;
sewardj30b3eca2011-06-28 08:20:39 +0000222 unsigned int usecs;
sewardj3b290482011-05-06 21:02:55 +0000223
philippe3c761f02013-12-01 14:56:28 +0000224 pthread_cleanup_push(invoker_cleanup_restore_and_detach, v_pid);
sewardj3b290482011-05-06 21:02:55 +0000225
226 while (!shutting_down) {
227 written_by_vgdb_before_sleep = VS_written_by_vgdb;
228 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
229 DEBUG(3,
230 "written_by_vgdb_before_sleep %d "
231 "seen_by_valgrind_before_sleep %d\n",
232 written_by_vgdb_before_sleep,
233 seen_by_valgrind_before_sleep);
sewardj30b3eca2011-06-28 08:20:39 +0000234 if (cmd_time_out != NEVER
235 && !cmd_started
236 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
237 /* A command was started. Record the time at which it was started. */
238 DEBUG(1, "IO for command started\n");
239 gettimeofday(&cmd_max_end_time, NULL);
240 cmd_max_end_time.tv_sec += cmd_time_out;
241 cmd_started = True;
242 }
243 if (max_invoke_ms > 0) {
244 usecs = 1000 * max_invoke_ms;
245 gettimeofday(&invoke_time, NULL);
246 invoke_time.tv_sec += max_invoke_ms / 1000;
247 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
248 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
249 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
250 } else {
251 usecs = 0;
252 }
253 if (cmd_started) {
254 // 0 usecs here means the thread just has to check gdbserver eats
255 // the characters in <= cmd_time_out seconds.
256 // We will just wait by 1 second max at a time.
257 if (usecs == 0 || usecs > 1000 * 1000)
258 usecs = 1000 * 1000;
259 }
sewardj992d3cc2011-10-22 20:38:08 +0000260 usleep(usecs);
261
sewardj30b3eca2011-06-28 08:20:39 +0000262 /* If nothing happened during our sleep, let's try to wake up valgrind
263 or check for cmd time out. */
sewardj3b290482011-05-06 21:02:55 +0000264 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
265 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
266 && VS_written_by_vgdb > VS_seen_by_valgrind) {
sewardj30b3eca2011-06-28 08:20:39 +0000267 struct timeval now;
268 gettimeofday(&now, NULL);
sewardj3b290482011-05-06 21:02:55 +0000269 DEBUG(2,
270 "after sleep "
271 "written_by_vgdb %d "
272 "seen_by_valgrind %d "
273 "invoked_written %d\n",
274 VS_written_by_vgdb,
275 VS_seen_by_valgrind,
276 invoked_written);
277 /* if the pid does not exist anymore, we better stop */
278 if (kill(pid, 0) != 0)
279 XERROR (errno,
280 "invoke_gdbserver_in_valgrind: "
281 "check for pid %d existence failed\n", pid);
sewardj30b3eca2011-06-28 08:20:39 +0000282 if (cmd_started) {
283 if (timercmp (&now, &cmd_max_end_time, >))
284 XERROR (0,
285 "pid %d did not handle a command in %d seconds\n",
286 pid, cmd_time_out);
sewardj3b290482011-05-06 21:02:55 +0000287 }
sewardj30b3eca2011-06-28 08:20:39 +0000288 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
sewardj30b3eca2011-06-28 08:20:39 +0000289 /* only need to wake up if the nr written has changed since
290 last invoke. */
291 if (invoked_written != written_by_vgdb_before_sleep) {
philippe3c761f02013-12-01 14:56:28 +0000292 if (invoker_invoke_gdbserver(pid)) {
florianad4e9792015-07-05 21:53:33 +0000293 /* If invoke successful, no need to invoke again
sewardj30b3eca2011-06-28 08:20:39 +0000294 for the same value of written_by_vgdb_before_sleep. */
295 invoked_written = written_by_vgdb_before_sleep;
296 }
297 }
sewardj30b3eca2011-06-28 08:20:39 +0000298 }
299 } else {
300 // Something happened => restart timer check.
301 if (cmd_time_out != NEVER) {
302 DEBUG(2, "some IO was done => restart command\n");
303 cmd_started = False;
304 }
sewardj3b290482011-05-06 21:02:55 +0000305 }
306 }
307 pthread_cleanup_pop(0);
308 return NULL;
309}
310
311static
florian6bd9dc12012-11-23 16:17:43 +0000312int open_fifo (const char* name, int flags, const char* desc)
sewardj3b290482011-05-06 21:02:55 +0000313{
314 int fd;
315 DEBUG(1, "opening %s %s\n", name, desc);
316 fd = open(name, flags);
317 if (fd == -1)
318 XERROR (errno, "error opening %s %s\n", name, desc);
319
320 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
321 return fd;
322}
323
324/* acquire a lock on the first byte of the given fd. If not successful,
325 exits with error.
326 This allows to avoid having two vgdb speaking with the same Valgrind
327 gdbserver as this causes serious headaches to the protocol. */
328static
329void acquire_lock (int fd, int valgrind_pid)
330{
sewardj992d3cc2011-10-22 20:38:08 +0000331 struct flock fl;
332 fl.l_type = F_WRLCK;
333 fl.l_whence = SEEK_SET;
334 fl.l_start = 0;
335 fl.l_len = 1;
336 if (fcntl(fd, F_SETLK, &fl) < 0) {
sewardj3b290482011-05-06 21:02:55 +0000337 if (errno == EAGAIN || errno == EACCES) {
338 XERROR(errno,
339 "Cannot acquire lock.\n"
340 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
341 VS_vgdb_pid,
342 valgrind_pid);
343 } else {
344 XERROR(errno, "cannot acquire lock.\n");
345 }
346 }
347
348 /* Here, we have the lock. It will be released when fd will be closed. */
349 /* We indicate our pid to Valgrind gdbserver */
350 if (shared32 != NULL)
351 shared32->vgdb_pid = getpid();
352 else if (shared64 != NULL)
353 shared64->vgdb_pid = getpid();
354 else
355 assert(0);
356}
357
358#define PBUFSIZ 16384 /* keep in sync with server.h */
359
360/* read some characters from fd.
361 Returns the nr of characters read, -1 if error.
362 desc is a string used in tracing */
363static
florian6bd9dc12012-11-23 16:17:43 +0000364int read_buf (int fd, char* buf, const char* desc)
sewardj3b290482011-05-06 21:02:55 +0000365{
366 int nrread;
367 DEBUG(2, "reading %s\n", desc);
368 nrread = read(fd, buf, PBUFSIZ);
369 if (nrread == -1) {
370 ERROR (errno, "error reading %s\n", desc);
371 return -1;
372 }
373 buf[nrread] = '\0';
374 DEBUG(2, "read %s %s\n", desc, buf);
375 return nrread;
376}
377
378/* write size bytes from buf to fd.
379 desc is a description of the action for which the write is done.
380 If notify, then add size to the shared cntr indicating to the
381 valgrind process that there is new data.
382 Returns True if write is ok, False if there was a problem. */
383static
Elliott Hughesa0664b92017-04-18 17:46:52 -0700384Bool write_buf(int fd, const char* buf, int size, const char* desc, Bool notify)
sewardj3b290482011-05-06 21:02:55 +0000385{
386 int nrwritten;
387 int nrw;
philippe66bc6e52012-10-31 15:07:39 +0000388 DEBUG(2, "writing %s len %d %.*s notify: %d\n", desc, size,
389 size, buf, notify);
sewardj3b290482011-05-06 21:02:55 +0000390 nrwritten = 0;
391 while (nrwritten < size) {
392 nrw = write (fd, buf+nrwritten, size - nrwritten);
393 if (nrw == -1) {
394 ERROR(errno, "error write %s\n", desc);
395 return False;
396 }
397 nrwritten = nrwritten + nrw;
398 if (notify)
399 add_written(nrw);
400 }
401 return True;
402}
403
404typedef enum {
405 FROM_GDB,
406 TO_GDB,
407 FROM_PID,
408 TO_PID } ConnectionKind;
409static const int NumConnectionKind = TO_PID+1;
410static
florian6bd9dc12012-11-23 16:17:43 +0000411const char *ppConnectionKind (ConnectionKind con)
sewardj3b290482011-05-06 21:02:55 +0000412{
413 switch (con) {
414 case FROM_GDB: return "FROM_GDB";
415 case TO_GDB: return "TO_GDB";
416 case FROM_PID: return "FROM_PID";
417 case TO_PID: return "TO_PID";
418 default: return "invalid connection kind";
419 }
420}
421
422static char *shared_mem;
423
sewardj992d3cc2011-10-22 20:38:08 +0000424static int from_gdb = 0; /* stdin by default, changed if --port is given. */
sewardj3b290482011-05-06 21:02:55 +0000425static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
426/* Returns True in case read/write operations were done properly.
427 Returns False in case of error.
428 to_pid is the file descriptor to write to the process pid. */
429static
430Bool read_from_gdb_write_to_pid(int to_pid)
431{
philippe1d76a802011-12-26 21:21:37 +0000432 char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +0000433 int nrread;
434
435 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
436 if (nrread <= 0) {
437 if (nrread == 0)
438 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
439 else
440 DEBUG(1, "error reading bytes from gdb\n");
441 close (from_gdb);
442 shutting_down = True;
443 return False;
444 }
445 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
446}
447
sewardj992d3cc2011-10-22 20:38:08 +0000448static int to_gdb = 1; /* stdout by default, changed if --port is given. */
sewardj3b290482011-05-06 21:02:55 +0000449static char *to_gdb_from_pid; /* fifo name to read pid replies */
450/* Returns True in case read/write operations were done properly.
451 Returns False in case of error.
452 from_pid is the file descriptor to read data from the process pid. */
453static
454Bool read_from_pid_write_to_gdb(int from_pid)
455{
philippe1d76a802011-12-26 21:21:37 +0000456 char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +0000457 int nrread;
458
459 nrread = read_buf(from_pid, buf, "from pid");
460 if (nrread <= 0) {
461 if (nrread == 0)
462 DEBUG(1, "read 0 bytes from pid => assume exit\n");
463 else
464 DEBUG(1, "error reading bytes from pid\n");
465 close (from_pid);
466 shutting_down = True;
467 return False;
468 }
469 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
470}
471
sewardj992d3cc2011-10-22 20:38:08 +0000472static
473void wait_for_gdb_connect (int in_port)
474{
475 struct sockaddr_in addr;
476
477 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
478 int gdb_connect;
479
480 if (-1 == listen_gdb) {
481 XERROR(errno, "cannot create socket");
482 }
483
484 memset(&addr, 0, sizeof(addr));
485
486 addr.sin_family = AF_INET;
487 addr.sin_port = htons((unsigned short int)in_port);
488 addr.sin_addr.s_addr = INADDR_ANY;
489
490 if (-1 == bind(listen_gdb,(struct sockaddr *)&addr, sizeof(addr))) {
491 XERROR(errno, "bind failed");
492 }
493 fprintf(stderr, "listening on port %d ...", in_port);
494 fflush(stderr);
495 if (-1 == listen(listen_gdb, 1)) {
496 XERROR(errno, "error listen failed");
497 }
498
499 gdb_connect = accept(listen_gdb, NULL, NULL);
500 if (gdb_connect < 0) {
501 XERROR(errno, "accept failed");
502 }
503 fprintf(stderr, "connected.\n");
504 fflush(stderr);
505 close(listen_gdb);
506 from_gdb = gdb_connect;
507 to_gdb = gdb_connect;
508}
509
sewardj3b290482011-05-06 21:02:55 +0000510/* prepares the FIFOs filenames, map the shared memory. */
511static
512void prepare_fifos_and_shared_mem(int pid)
513{
florianab8630f2011-09-29 21:20:49 +0000514 const HChar *user, *host;
515 unsigned len;
516
517 user = getenv("LOGNAME");
518 if (user == NULL) user = getenv("USER");
519 if (user == NULL) user = "???";
florian511df4e2014-09-12 19:52:32 +0000520 if (strchr(user, '/')) user = "???";
florianab8630f2011-09-29 21:20:49 +0000521
522 host = getenv("HOST");
523 if (host == NULL) host = getenv("HOSTNAME");
524 if (host == NULL) host = "???";
florian511df4e2014-09-12 19:52:32 +0000525 if (strchr(host, '/')) host = "???";
florianab8630f2011-09-29 21:20:49 +0000526
527 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
528 from_gdb_to_pid = vmalloc (len);
529 to_gdb_from_pid = vmalloc (len);
530 shared_mem = vmalloc (len);
sewardj3b290482011-05-06 21:02:55 +0000531 /* below 3 lines must match the equivalent in remote-utils.c */
florianab8630f2011-09-29 21:20:49 +0000532 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
533 pid, user, host);
534 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
535 pid, user, host);
536 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
537 pid, user, host);
sewardj3b290482011-05-06 21:02:55 +0000538 DEBUG (1, "vgdb: using %s %s %s\n",
539 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
540
541 map_vgdbshared(shared_mem);
542}
543
544/* Convert hex digit A to a number. */
545
546static int
547fromhex (int a)
548{
549 if (a >= '0' && a <= '9')
550 return a - '0';
551 else if (a >= 'a' && a <= 'f')
552 return a - 'a' + 10;
553 else
554 XERROR(0, "Reply contains invalid hex digit %c\n", a);
555 return 0;
556}
557
558/* Returns next char from fd. -1 if error, -2 if EOF.
559 NB: must always call it with the same fd */
560static int
561readchar (int fd)
562{
philippeadfb8a72012-11-01 17:00:12 +0000563 static char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +0000564 static int bufcnt = 0;
philippeadfb8a72012-11-01 17:00:12 +0000565 static unsigned char *bufp;
566 // unsigned bufp to e.g. avoid having 255 converted to int -1
sewardj3b290482011-05-06 21:02:55 +0000567
568 if (bufcnt-- > 0)
569 return *bufp++;
570
philippe1d76a802011-12-26 21:21:37 +0000571 bufcnt = read_buf (fd, buf, "static buf readchar");
sewardj3b290482011-05-06 21:02:55 +0000572
573 if (bufcnt <= 0) {
574 if (bufcnt == 0) {
575 fprintf (stderr, "readchar: Got EOF\n");
576 return -2;
577 } else {
578 ERROR (errno, "readchar\n");
579 return -1;
580 }
581 }
582
philippeadfb8a72012-11-01 17:00:12 +0000583 bufp = (unsigned char *)buf;
sewardj3b290482011-05-06 21:02:55 +0000584 bufcnt--;
585 return *bufp++;
586}
587
588/* Read a packet from fromfd, with error checking,
Elliott Hughesa0664b92017-04-18 17:46:52 -0700589 and store it in BUF.
590 If checksum incorrect, writes a - on ackfd.
591 Returns length of packet, or -1 if error or -2 if EOF. */
sewardj3b290482011-05-06 21:02:55 +0000592static int
593getpkt (char *buf, int fromfd, int ackfd)
594{
595 char *bp;
596 unsigned char csum, c1, c2;
597 int c;
598
599 while (1) {
600 csum = 0;
601
602 while (1) {
603 c = readchar (fromfd);
604 if (c == '$')
605 break;
606 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
607 if (c < 0)
608 return c;
609 }
610
611 bp = buf;
612 while (1) {
613 c = readchar (fromfd);
614 if (c < 0)
615 return c;
616 if (c == '#')
617 break;
618 if (c == '*') {
619 int repeat;
620 int r;
621 int prev;
622 prev = *(bp-1);
623 csum += c;
624 repeat = readchar (fromfd);
625 csum += repeat;
626 for (r = 0; r < repeat - 29; r ++)
627 *bp++ = prev;
628 } else {
629 *bp++ = c;
630 csum += c;
631 }
632 }
633 *bp = 0;
634
635 c1 = fromhex (readchar (fromfd));
636 c2 = fromhex (readchar (fromfd));
637
638 if (csum == (c1 << 4) + c2)
639 break;
640
641 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
642 (c1 << 4) + c2, csum, buf);
643 if (write (ackfd, "-", 1) != 1)
644 ERROR(0, "error when writing - (nack)\n");
645 else
646 add_written(1);
647 }
648
Elliott Hughesa0664b92017-04-18 17:46:52 -0700649 DEBUG(2, "getpkt (\"%s\"); [no ack] \n", buf);
sewardj3b290482011-05-06 21:02:55 +0000650 return bp - buf;
651}
652
653static int sigint = 0;
654static int sigterm = 0;
655static int sigpipe = 0;
656static int sighup = 0;
657static int sigusr1 = 0;
658static int sigalrm = 0;
659static int sigusr1_fd = -1;
660static pthread_t invoke_gdbserver_in_valgrind_thread;
661
662static
663void received_signal (int signum)
664{
665 if (signum == SIGINT)
666 sigint++;
667 else if (signum == SIGUSR1) {
668 sigusr1++;
669 if (sigusr1_fd >= 0) {
670 char control_c = '\003';
671 write_buf(sigusr1_fd, &control_c, 1,
672 "write \\003 on SIGUSR1", /* notify */ True);
673 }
674 }
675 else if (signum == SIGTERM) {
676 shutting_down = True;
677 sigterm++;
678 } else if (signum == SIGHUP) {
679 shutting_down = True;
680 sighup++;
681 } else if (signum == SIGPIPE) {
682 sigpipe++;
683 } else if (signum == SIGALRM) {
684 sigalrm++;
Elliott Hughesa0664b92017-04-18 17:46:52 -0700685#if defined(VGPV_amd64_linux_android) \
686 || defined(VGPV_arm_linux_android) \
687 || defined(VGPV_x86_linux_android) \
688 || defined(VGPV_mips32_linux_android) \
689 || defined(VGPV_arm64_linux_android)
sewardj992d3cc2011-10-22 20:38:08 +0000690 /* Android has no pthread_cancel. As it also does not have
philippe3c761f02013-12-01 14:56:28 +0000691 an invoker implementation, there is no need for cleanup action.
sewardj992d3cc2011-10-22 20:38:08 +0000692 So, we just do nothing. */
693 DEBUG(1, "sigalrm received, no action on android\n");
694#else
sewardj3b290482011-05-06 21:02:55 +0000695 /* Note: we cannot directly invoke restore_and_detach : this must
696 be done by the thread that has attached.
697 We have in this thread pushed a cleanup handler that will
698 cleanup what is needed. */
sewardj992d3cc2011-10-22 20:38:08 +0000699 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
sewardj3b290482011-05-06 21:02:55 +0000700 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
sewardj992d3cc2011-10-22 20:38:08 +0000701#endif
sewardj3b290482011-05-06 21:02:55 +0000702 } else {
703 ERROR(0, "unexpected signal %d\n", signum);
704 }
705}
706
707/* install the signal handlers allowing e.g. vgdb to cleanup in
708 case of termination. */
709static
710void install_handlers(void)
711{
712 struct sigaction action, oldaction;
713
714 action.sa_handler = received_signal;
715 sigemptyset (&action.sa_mask);
716 action.sa_flags = 0;
717
718 /* SIGINT: when user types C-c in gdb, this sends
719 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
720 The later is enough to wakeup the valgrind process. */
721 if (sigaction (SIGINT, &action, &oldaction) != 0)
722 XERROR (errno, "vgdb error sigaction SIGINT\n");
723 /* We might do something more intelligent than just
724 reporting this SIGINT E.g. behave similarly to the gdb: two
725 control-C without feedback from the debugged process would
726 mean to stop debugging it. */
727
728 /* SIGUSR1: this is used to facilitate automatic testing. When
729 vgdb receives this signal, it will simulate the user typing C-c. */
730 if (sigaction (SIGUSR1, &action, &oldaction) != 0)
731 XERROR (errno, "vgdb error sigaction SIGUSR1\n");
732
733
734 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
735 when detaching or similar. A clean shutdown will be done as both
736 the read and write side will detect an end of file. */
737 if (sigaction (SIGTERM, &action, &oldaction) != 0)
738 XERROR (errno, "vgdb error sigaction SIGTERM\n");
739
740 /* SIGPIPE: can receive this signal when gdb detaches or kill the
741 process debugged: gdb will close its pipes to vgdb. vgdb
742 must resist to this signal to allow a clean shutdown. */
743 if (sigaction (SIGPIPE, &action, &oldaction) != 0)
744 XERROR (errno, "vgdb error sigaction SIGPIPE\n");
745
746 /* SIGALRM: in case invoke thread is blocked, alarm is used
747 to cleanup. */
748 if (sigaction (SIGALRM, &action, &oldaction) != 0)
749 XERROR (errno, "vgdb error sigaction SIGALRM\n");
philippee6460fa2014-11-04 20:28:36 +0000750
751 /* unmask all signals, in case the process that launched vgdb
752 masked some. */
753 if (sigprocmask (SIG_SETMASK, &action.sa_mask, NULL) != 0)
754 XERROR (errno, "vgdb error sigprocmask");
sewardj3b290482011-05-06 21:02:55 +0000755}
756
757/* close the FIFOs provided connections, terminate the invoker thread. */
758static
759void close_connection(int to_pid, int from_pid)
760{
761 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
762 sigint, sigterm, sighup, sigpipe);
763 /* Note that we do not forward sigterm to the valgrind process:
764 a sigterm signal is (probably) received from gdb if the user wants to
765 kill the debugged process. The kill instruction has been given to
766 the valgrind process, which should execute a clean exit. */
767
768 /* We first close the connection to pid. The pid will then
769 terminates its gdbserver work. We keep the from pid
770 fifo opened till the invoker thread is finished.
771 This allows the gdbserver to finish sending its last reply. */
772 if (close(to_pid) != 0)
773 ERROR(errno, "close to_pid\n");
774
775 /* if there is a task that was busy trying to wake up valgrind
776 process, we wait for it to be terminated otherwise threads
777 in the valgrind process can stay stopped if vgdb main
778 exits before the invoke thread had time to detach from
779 all valgrind threads. */
sewardj30b3eca2011-06-28 08:20:39 +0000780 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
sewardj3b290482011-05-06 21:02:55 +0000781 int join;
782
783 /* It is surprisingly complex to properly shutdown or exit the
784 valgrind process in which gdbserver has been invoked through
785 ptrace. In the normal case (gdb detaches from the process,
786 or process is continued), the valgrind process will reach the
787 breakpoint place. Using ptrace, vgdb will ensure the
788 previous activity of the process is resumed (e.g. restart a
789 blocking system call). The special case is when gdb asks the
790 valgrind process to exit (using either the "kill" command or
791 "monitor exit"). In such a case, the valgrind process will
792 call exit. But a ptraced process will be blocked in exit,
793 waiting for the ptracing process to detach or die. vgdb
794 cannot detach unconditionally as otherwise, in the normal
sewardjb2572b52011-06-26 09:36:38 +0000795 case, the valgrind process would stop abnormally with SIGSTOP
sewardj3b290482011-05-06 21:02:55 +0000796 (as vgdb would not be there to catch it). vgdb can also not
797 die unconditionally otherwise again, similar problem. So, we
798 assume that most of the time, we arrive here in the normal
799 case, and so, the breakpoint has been encountered by the
800 valgrind process, so the invoker thread will exit and the
801 join will succeed. For the "kill" case, we cause an alarm
802 signal to be sent after a few seconds. This means that in the
803 normal case, the gdbserver code in valgrind process must have
804 returned the control in less than the alarm nr of seconds,
sewardjb2572b52011-06-26 09:36:38 +0000805 otherwise, valgrind will stop abnormally with SIGSTOP. */
sewardj3b290482011-05-06 21:02:55 +0000806 (void) alarm (3);
807
808 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
809 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
810 if (join != 0)
811 XERROR
812 (join,
813 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
814 }
815 if (close(from_pid) != 0)
816 ERROR(errno, "close from_pid\n");
817}
818
819/* Relay data between gdb and Valgrind gdbserver, till EOF or an
820 error is encountered. */
821static
822void gdb_relay (int pid)
823{
824 int from_pid = -1; /* fd to read from pid */
825 int to_pid = -1; /* fd to write to pid */
826
827 int shutdown_loop = 0;
828 fprintf (stderr, "relaying data between gdb and process %d\n", pid);
829 fflush (stderr);
830
831 if (max_invoke_ms > 0)
832 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
833 invoke_gdbserver_in_valgrind, (void *) &pid);
834 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
835 acquire_lock (shared_mem_fd, pid);
836
837 from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
838 "read mode from pid");
839
840 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
841
842 while (1) {
843 ConnectionKind ck;
844 int ret;
845 struct pollfd pollfds[NumConnectionKind];
846
847 /* watch data written by gdb, watch POLLERR on both gdb fd */
848 pollfds[FROM_GDB].fd = from_gdb;
849 pollfds[FROM_GDB].events = POLLIN;
850 pollfds[FROM_GDB].revents = 0;
851 pollfds[TO_GDB].fd = to_gdb;
852 pollfds[TO_GDB].events = 0;
853 pollfds[TO_GDB].revents = 0;
854
855 /* watch data written by pid, watch POLLERR on both pid fd */
856 pollfds[FROM_PID].fd = from_pid;
857 pollfds[FROM_PID].events = POLLIN;
858 pollfds[FROM_PID].revents = 0;
859 pollfds[TO_PID].fd = to_pid;
860 pollfds[TO_PID].events = 0;
861 pollfds[TO_PID].revents = 0;
862
863 ret = poll(pollfds,
864 NumConnectionKind,
865 (shutting_down ?
866 1 /* one second */
867 : -1 /* infinite */));
868 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
869
870 /* check for unexpected error */
871 if (ret <= 0 && errno != EINTR) {
872 ERROR (errno, "unexpected poll ret %d\n", ret);
873 shutting_down = True;
874 break;
875 }
876
877 /* check for data to read */
878 for (ck = 0; ck < NumConnectionKind; ck ++) {
879 if (pollfds[ck].revents & POLLIN) {
880 switch (ck) {
881 case FROM_GDB:
882 if (!read_from_gdb_write_to_pid(to_pid))
883 shutting_down = True;
884 break;
philippe1d76a802011-12-26 21:21:37 +0000885 case FROM_PID:
886 if (!read_from_pid_write_to_gdb(from_pid))
887 shutting_down = True;
888 break;
sewardj3b290482011-05-06 21:02:55 +0000889 default: XERROR(0, "unexpected POLLIN on %s\n",
890 ppConnectionKind(ck));
891 }
892 }
893 }
894
895 /* check for an fd being in error condition */
896 for (ck = 0; ck < NumConnectionKind; ck ++) {
897 if (pollfds[ck].revents & POLLERR) {
898 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
899 ppConnectionKind(ck), pollfds[ck].fd);
philippe3c761f02013-12-01 14:56:28 +0000900 invoker_valgrind_dying();
sewardj3b290482011-05-06 21:02:55 +0000901 shutting_down = True;
902 }
903 if (pollfds[ck].revents & POLLHUP) {
904 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
905 ppConnectionKind(ck), pollfds[ck].fd);
philippe3c761f02013-12-01 14:56:28 +0000906 invoker_valgrind_dying();
sewardj3b290482011-05-06 21:02:55 +0000907 shutting_down = True;
908 }
909 if (pollfds[ck].revents & POLLNVAL) {
910 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
911 ppConnectionKind(ck), pollfds[ck].fd);
philippe3c761f02013-12-01 14:56:28 +0000912 invoker_valgrind_dying();
sewardj3b290482011-05-06 21:02:55 +0000913 shutting_down = True;
914 }
915 }
916
917 if (shutting_down) {
918 /* we let some time to the final packets to be transferred */
919 shutdown_loop++;
920 if (shutdown_loop > 3)
921 break;
922 }
923 }
924 close_connection(to_pid, from_pid);
925}
926
927static int packet_len_for_command(char *cmd)
928{
929 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
930 return 7+ 2*strlen(cmd) +3 + 1;
931}
932
933/* hyper-minimal protocol implementation that
934 sends the provided commands (using qRcmd packets)
935 and read and display their replies. */
936static
937void standalone_send_commands(int pid,
938 int last_command,
939 char *commands[] )
940{
941 int from_pid = -1; /* fd to read from pid */
942 int to_pid = -1; /* fd to write to pid */
943
944 int i;
945 int hi;
philippeadfb8a72012-11-01 17:00:12 +0000946 char hex[3];
sewardj3b290482011-05-06 21:02:55 +0000947 unsigned char cksum;
philippeadfb8a72012-11-01 17:00:12 +0000948 char *hexcommand;
949 char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +0000950 int buflen;
951 int nc;
952
953
sewardj30b3eca2011-06-28 08:20:39 +0000954 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
sewardj3b290482011-05-06 21:02:55 +0000955 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
956 invoke_gdbserver_in_valgrind, (void *) &pid);
957
958 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
959 acquire_lock (shared_mem_fd, pid);
960
961 /* first send a C-c \003 to pid, so that it wakes up the process
962 After that, we can open the fifo from the pid in read mode
963 We then start to wait for packets (normally first a resume reply)
964 At that point, we send our command and expect replies */
965 buf[0] = '\003';
philippedef5aae2014-07-08 22:28:26 +0000966 i = 0;
967 while (!write_buf(to_pid, buf, 1,
968 "write \\003 to wake up", /* notify */ True)) {
969 /* If write fails, retries up to 10 times every 0.5 seconds
970 This aims at solving the race condition described in
971 remote-utils.c remote_finish function. */
972 usleep(500*1000);
973 i++;
974 if (i >= 10)
975 XERROR (errno, "failed to send wake up char after 10 trials\n");
976 }
sewardj3b290482011-05-06 21:02:55 +0000977 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
978 "read cmd result from pid");
Elliott Hughesa0664b92017-04-18 17:46:52 -0700979
980 /* Enable no ack mode. */
981 write_buf(to_pid, "$QStartNoAckMode#b0", 19, "write start no ack mode",
982 /* notify */ True);
983 buflen = getpkt(buf, from_pid, to_pid);
984 if (buflen != 2 || strcmp(buf, "OK") != 0) {
985 if (buflen != 2)
986 ERROR (0, "no ack mode: unexpected buflen %d\n", buflen);
987 else
988 ERROR (0, "no ack mode: unexpected packet %s\n", buf);
989 }
sewardj3b290482011-05-06 21:02:55 +0000990
991 for (nc = 0; nc <= last_command; nc++) {
992 fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
993 fflush (stderr);
994
995 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
996 hexcommand = vmalloc (packet_len_for_command(commands[nc]));
997 hexcommand[0] = 0;
998 strcat (hexcommand, "$qRcmd,");
999 for (i = 0; i < strlen(commands[nc]); i++) {
philippeadfb8a72012-11-01 17:00:12 +00001000 sprintf(hex, "%02x", (unsigned char) commands[nc][i]);
1001 // Need to use unsigned char, to avoid sign extension.
sewardj3b290482011-05-06 21:02:55 +00001002 strcat (hexcommand, hex);
1003 }
1004 /* checksum (but without the $) */
1005 cksum = 0;
1006 for (hi = 1; hi < strlen(hexcommand); hi++)
1007 cksum+=hexcommand[hi];
1008 strcat(hexcommand, "#");
1009 sprintf(hex, "%02x", cksum);
1010 strcat(hexcommand, hex);
1011 write_buf(to_pid, hexcommand, strlen(hexcommand),
1012 "writing hex command to pid", /* notify */ True);
1013
1014 /* we exit of the below loop explicitely when the command has
1015 been handled or because a signal handler will set
1016 shutting_down. */
1017 while (!shutting_down) {
1018 buflen = getpkt(buf, from_pid, to_pid);
1019 if (buflen < 0) {
1020 ERROR (0, "error reading packet\n");
1021 if (buflen == -2)
philippe3c761f02013-12-01 14:56:28 +00001022 invoker_valgrind_dying();
sewardj3b290482011-05-06 21:02:55 +00001023 break;
1024 }
1025 if (strlen(buf) == 0) {
1026 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1027 break;
1028 }
1029 if (strcmp(buf, "OK") == 0) {
1030 DEBUG(1, "OK packet rcvd\n");
1031 break;
1032 }
1033 if (buf[0] == 'E') {
1034 DEBUG(0,
1035 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1036 buf);
1037 break;
1038 }
1039 if (buf[0] == 'W') {
1040 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1041 break;
1042 }
1043 if (buf[0] == 'T') {
1044 DEBUG(1, "T resume reply packet received: %s\n", buf);
1045 continue;
1046 }
1047
1048 /* must be here an O packet with hex encoded string reply
1049 => decode and print it */
1050 if (buf[0] != 'O') {
1051 DEBUG(0, "expecting O packet, received: %s\n", buf);
1052 continue;
1053 }
1054 {
1055 char buf_print[buflen/2 + 1];
1056 for (i = 1; i < buflen; i = i + 2)
1057 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1058 + fromhex(*(buf+i+1));
1059 buf_print[buflen/2] = 0;
1060 printf("%s", buf_print);
1061 fflush(stdout);
1062 }
1063 }
1064 free (hexcommand);
1065 }
1066 shutting_down = True;
1067
1068 close_connection(to_pid, from_pid);
1069}
1070
1071/* report to user the existence of a vgdb-able valgrind process
philippe345affe2014-12-21 17:31:54 +00001072 with given pid.
philippe5cbcd622014-12-21 17:53:42 +00001073 Note: this function does not use XERROR if an error is encountered
philippe345affe2014-12-21 17:31:54 +00001074 while producing the command line for pid, as this is not critical
1075 and at least on MacOS, reading cmdline is not available. */
sewardj3b290482011-05-06 21:02:55 +00001076static
sewardj30b3eca2011-06-28 08:20:39 +00001077void report_pid (int pid, Bool on_stdout)
sewardj3b290482011-05-06 21:02:55 +00001078{
florianb7742ab2014-12-19 20:25:46 +00001079 char cmdline_file[50]; // large enough
1080 int fd, i;
1081 FILE *out = on_stdout ? stdout : stderr;
sewardj3b290482011-05-06 21:02:55 +00001082
philippe345affe2014-12-21 17:31:54 +00001083 fprintf(out, "use --pid=%d for ", pid);
1084
sewardj3b290482011-05-06 21:02:55 +00001085 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1086 fd = open (cmdline_file, O_RDONLY);
1087 if (fd == -1) {
1088 DEBUG(1, "error opening cmdline file %s %s\n",
1089 cmdline_file, strerror(errno));
philippe345affe2014-12-21 17:31:54 +00001090 fprintf(out, "(could not open process command line)\n");
sewardj3b290482011-05-06 21:02:55 +00001091 } else {
florianb7742ab2014-12-19 20:25:46 +00001092 char cmdline[100];
1093 ssize_t sz;
florianb7742ab2014-12-19 20:25:46 +00001094 while ((sz = read(fd, cmdline, sizeof cmdline - 1)) != 0) {
philippe345affe2014-12-21 17:31:54 +00001095 for (i = 0; i < sz; i++)
1096 if (cmdline[i] == 0)
1097 cmdline[i] = ' ';
1098 cmdline[sz] = 0;
1099 fprintf(out, "%s", cmdline);
1100 }
1101 if (sz == -1) {
1102 DEBUG(1, "error reading cmdline file %s %s\n",
1103 cmdline_file, strerror(errno));
1104 fprintf(out, "(error reading process command line)");
philippe36c01ef2013-01-15 23:09:41 +00001105 }
florianb7742ab2014-12-19 20:25:46 +00001106 fprintf(out, "\n");
sewardjd8c12f12011-05-11 22:54:57 +00001107 close (fd);
sewardj3b290482011-05-06 21:02:55 +00001108 }
florianb7742ab2014-12-19 20:25:46 +00001109 fflush(out);
sewardj3b290482011-05-06 21:02:55 +00001110}
1111
sewardj3b290482011-05-06 21:02:55 +00001112static
1113void usage(void)
1114{
1115 fprintf(stderr,
1116"Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1117"vgdb (valgrind gdb) has two usages\n"
1118" 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1119" The OPTION(s) must be followed by the command to send\n"
1120" To send more than one command, separate the commands with -c\n"
1121" 2. relay application between gdb and a Valgrind gdbserver.\n"
1122" Only OPTION(s) can be given.\n"
1123"\n"
1124" OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
sewardj30b3eca2011-06-28 08:20:39 +00001125" [--wait=<number>] [--max-invoke-ms=<number>]\n"
sewardj992d3cc2011-10-22 20:38:08 +00001126" [--port=<portnr>\n"
sewardj30b3eca2011-06-28 08:20:39 +00001127" [--cmd-time-out=<number>] [-l] [-D] [-d]\n"
1128" \n"
sewardj3b290482011-05-06 21:02:55 +00001129" --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1130" --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
philippe5507d222013-08-06 20:45:20 +00001131" if you want to change the prefix (default %s) for the FIFOs communication\n"
sewardj3b290482011-05-06 21:02:55 +00001132" between the Valgrind gdbserver and vgdb.\n"
sewardj30b3eca2011-06-28 08:20:39 +00001133" --wait (default 0) tells vgdb to check during the specified number\n"
sewardj3b290482011-05-06 21:02:55 +00001134" of seconds if a Valgrind gdbserver can be found.\n"
sewardj30b3eca2011-06-28 08:20:39 +00001135" --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
1136" will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
1137" process is blocked in a system call).\n"
sewardj992d3cc2011-10-22 20:38:08 +00001138" --port instructs vgdb to listen for gdb on the specified port nr.\n"
sewardj30b3eca2011-06-28 08:20:39 +00001139" --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
1140" gdbserver has not processed a command after number seconds\n"
sewardjd142f992011-05-17 17:15:07 +00001141" -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
sewardj30b3eca2011-06-28 08:20:39 +00001142" -D arg tells to show shared mem status and then exit.\n"
1143" -d arg tells to show debug info. Multiple -d args for more debug info\n"
sewardjd142f992011-05-17 17:15:07 +00001144"\n"
1145" -h --help shows this message\n"
1146" To get help from the Valgrind gdbserver, use vgdb help\n"
philippe5507d222013-08-06 20:45:20 +00001147"\n", vgdb_prefix_default()
sewardj3b290482011-05-06 21:02:55 +00001148 );
philippe3c761f02013-12-01 14:56:28 +00001149 invoker_restrictions_msg();
sewardj3b290482011-05-06 21:02:55 +00001150}
1151
sewardj30b3eca2011-06-28 08:20:39 +00001152/* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
sewardjd142f992011-05-17 17:15:07 +00001153 and then exits.
1154
1155 else if arg_pid == -1, waits maximum check_trials seconds to discover
sewardj3b290482011-05-06 21:02:55 +00001156 a valgrind pid appearing.
sewardjd142f992011-05-17 17:15:07 +00001157
sewardj3b290482011-05-06 21:02:55 +00001158 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1159 with gdbserver activated.
1160
1161 Returns the pid to work with
1162 or exits in case of error (e.g. no pid found corresponding to arg_pid */
1163
1164static
sewardjd142f992011-05-17 17:15:07 +00001165int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
sewardj3b290482011-05-06 21:02:55 +00001166{
1167 int i;
1168 int pid = -1;
1169
1170 if (arg_pid == 0 || arg_pid < -1) {
1171 fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1172 exit (1);
1173 } else {
1174 /* search for a matching named fifo.
1175 If we have been given a pid, we will check that the matching FIFO is
1176 there (or wait the nr of check_trials for this to appear).
1177 If no pid has been given, then if we find only one FIFO,
1178 we will use this to build the pid to use.
1179 If we find multiple processes with valid FIFO, we report them and will
1180 exit with an error. */
1181 DIR *vgdb_dir;
1182 char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
1183 struct dirent *f;
1184 int is;
1185 int nr_valid_pid = 0;
1186 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1187 char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
1188
1189 strcpy (vgdb_format, vgdb_prefix);
1190 strcat (vgdb_format, suffix);
1191
philippe5507d222013-08-06 20:45:20 +00001192 if (strchr(vgdb_prefix, '/') != NULL) {
1193 strcpy (vgdb_dir_name, vgdb_prefix);
1194 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1195 if (vgdb_dir_name[is] == '/') {
1196 vgdb_dir_name[is+1] = '\0';
1197 break;
1198 }
1199 } else {
1200 strcpy (vgdb_dir_name, "");
1201 }
sewardj3b290482011-05-06 21:02:55 +00001202
1203 DEBUG(1, "searching pid in directory %s format %s\n",
1204 vgdb_dir_name, vgdb_format);
1205
1206 /* try to find FIFOs with valid pid.
1207 On exit of the loop, pid is set to:
sewardjd142f992011-05-17 17:15:07 +00001208 the last pid found if show_list (or -1 if no process was listed)
sewardj3b290482011-05-06 21:02:55 +00001209 -1 if no FIFOs matching a running process is found
1210 -2 if multiple FIFOs of running processes are found
1211 otherwise it is set to the (only) pid found that can be debugged
1212 */
1213 for (i = 0; i < check_trials; i++) {
1214 DEBUG(1, "check_trial %d \n", i);
1215 if (i > 0)
1216 /* wait one second before checking again */
1217 sleep(1);
1218
philippe5507d222013-08-06 20:45:20 +00001219 vgdb_dir = opendir (strlen (vgdb_dir_name) ? vgdb_dir_name : "./");
sewardj3b290482011-05-06 21:02:55 +00001220 if (vgdb_dir == NULL)
1221 XERROR (errno,
1222 "vgdb error: opening directory %s searching vgdb fifo\n",
1223 vgdb_dir_name);
1224
1225 errno = 0; /* avoid complain if vgdb_dir is empty */
1226 while ((f = readdir (vgdb_dir))) {
1227 struct stat st;
philippebb4827b2012-04-06 11:51:04 +00001228 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
sewardj3b290482011-05-06 21:02:55 +00001229 char *wrongpid;
1230 int newpid;
1231
1232 strcpy (pathname, vgdb_dir_name);
1233 strcat (pathname, f->d_name);
philippebb4827b2012-04-06 11:51:04 +00001234 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
sewardj3b290482011-05-06 21:02:55 +00001235 if (stat (pathname, &st) != 0) {
1236 if (debuglevel >= 3)
1237 ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n",
1238 pathname);
1239 } else if (S_ISFIFO (st.st_mode)) {
philippebb4827b2012-04-06 11:51:04 +00001240 DEBUG(3, "trying FIFO %s\n", pathname);
sewardj3b290482011-05-06 21:02:55 +00001241 if (strncmp (pathname, vgdb_format,
1242 strlen (vgdb_format)) == 0) {
1243 newpid = strtol(pathname + strlen (vgdb_format),
1244 &wrongpid, 10);
florianab8630f2011-09-29 21:20:49 +00001245 if (*wrongpid == '-' && newpid > 0
sewardj3b290482011-05-06 21:02:55 +00001246 && kill (newpid, 0) == 0) {
1247 nr_valid_pid++;
sewardjd142f992011-05-17 17:15:07 +00001248 if (show_list) {
sewardj30b3eca2011-06-28 08:20:39 +00001249 report_pid (newpid, /*on_stdout*/ True);
sewardjd142f992011-05-17 17:15:07 +00001250 pid = newpid;
1251 } else if (arg_pid != -1) {
sewardj3b290482011-05-06 21:02:55 +00001252 if (arg_pid == newpid) {
1253 pid = newpid;
1254 }
1255 } else if (nr_valid_pid > 1) {
1256 if (nr_valid_pid == 2) {
1257 fprintf
1258 (stderr,
1259 "no --pid= arg given"
1260 " and multiple valgrind pids found:\n");
sewardj30b3eca2011-06-28 08:20:39 +00001261 report_pid (pid, /*on_stdout*/ False);
sewardj3b290482011-05-06 21:02:55 +00001262 }
1263 pid = -2;
sewardj30b3eca2011-06-28 08:20:39 +00001264 report_pid (newpid, /*on_stdout*/ False);
sewardj3b290482011-05-06 21:02:55 +00001265 } else {
1266 pid = newpid;
1267 }
1268 }
1269 }
1270 }
1271 errno = 0; /* avoid complain if at the end of vgdb_dir */
1272 }
1273 if (f == NULL && errno != 0)
1274 XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n",
1275 vgdb_dir_name);
1276
1277 closedir (vgdb_dir);
1278 if (pid != -1)
1279 break;
1280 }
1281
1282 free (vgdb_dir_name);
1283 free (vgdb_format);
1284 }
sewardjd142f992011-05-17 17:15:07 +00001285
1286 if (show_list) {
1287 exit (1);
1288 } else if (pid == -1) {
sewardj3b290482011-05-06 21:02:55 +00001289 if (arg_pid == -1)
1290 fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
1291 else
1292 fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n",
1293 arg_pid);
1294 exit (1);
1295 }
1296 else if (pid == -2) {
1297 /* no arg_pid given, multiple FIFOs found */
1298 exit (1);
1299 }
1300 else {
1301 return pid;
1302 }
1303}
1304
1305/* return true if the numeric value of an option of the
1306 form --xxxxxxxxx=<number> could properly be extracted
1307 from arg. If True is returned, *value contains the
1308 extracted value.*/
1309static
1310Bool numeric_val(char* arg, int *value)
1311{
1312 const char *eq_pos = strchr(arg, '=');
1313 char *wrong;
sewardj30b3eca2011-06-28 08:20:39 +00001314 long long int long_value;
sewardj3b290482011-05-06 21:02:55 +00001315
1316 if (eq_pos == NULL)
1317 return False;
1318
sewardj30b3eca2011-06-28 08:20:39 +00001319 long_value = strtoll(eq_pos+1, &wrong, 10);
1320 if (long_value < 0 || long_value > INT_MAX)
1321 return False;
sewardj3b290482011-05-06 21:02:55 +00001322 if (*wrong)
1323 return False;
1324
sewardj30b3eca2011-06-28 08:20:39 +00001325 *value = (int) long_value;
sewardj3b290482011-05-06 21:02:55 +00001326 return True;
1327}
1328
1329/* true if arg matches the provided option */
1330static
florian6bd9dc12012-11-23 16:17:43 +00001331Bool is_opt(char* arg, const char *option)
sewardj3b290482011-05-06 21:02:55 +00001332{
1333 int option_len = strlen(option);
1334 if (option[option_len-1] == '=')
1335 return (0 == strncmp(option, arg, option_len));
1336 else
1337 return (0 == strcmp(option, arg));
1338}
1339
1340/* Parse command lines options. If error(s), exits.
1341 Otherwise returns the options in *p_... args.
1342 commands must be big enough for the commands extracted from argv.
1343 On return, *p_last_command gives the position in commands where
1344 the last command has been allocated (using vmalloc). */
1345static
1346void parse_options(int argc, char** argv,
1347 Bool *p_show_shared_mem,
sewardjd142f992011-05-17 17:15:07 +00001348 Bool *p_show_list,
sewardj3b290482011-05-06 21:02:55 +00001349 int *p_arg_pid,
1350 int *p_check_trials,
sewardj992d3cc2011-10-22 20:38:08 +00001351 int *p_port,
sewardj3b290482011-05-06 21:02:55 +00001352 int *p_last_command,
1353 char *commands[])
1354{
1355 Bool show_shared_mem = False;
sewardjd142f992011-05-17 17:15:07 +00001356 Bool show_list = False;
sewardj3b290482011-05-06 21:02:55 +00001357 int arg_pid = -1;
1358 int check_trials = 1;
1359 int last_command = -1;
sewardj992d3cc2011-10-22 20:38:08 +00001360 int int_port = 0;
sewardj3b290482011-05-06 21:02:55 +00001361
1362 int i;
1363 int arg_errors = 0;
1364
1365 for (i = 1; i < argc; i++) {
1366 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
1367 usage();
1368 exit(0);
1369 } else if (is_opt(argv[i], "-d")) {
1370 debuglevel++;
1371 } else if (is_opt(argv[i], "-D")) {
1372 show_shared_mem = True;
sewardjd142f992011-05-17 17:15:07 +00001373 } else if (is_opt(argv[i], "-l")) {
1374 show_list = True;
sewardj3b290482011-05-06 21:02:55 +00001375 } else if (is_opt(argv[i], "--pid=")) {
1376 int newpid;
1377 if (!numeric_val(argv[i], &newpid)) {
sewardj30b3eca2011-06-28 08:20:39 +00001378 fprintf (stderr, "invalid --pid argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00001379 arg_errors++;
1380 } else if (arg_pid != -1) {
sewardj30b3eca2011-06-28 08:20:39 +00001381 fprintf (stderr, "multiple --pid arguments given\n");
sewardj3b290482011-05-06 21:02:55 +00001382 arg_errors++;
1383 } else {
1384 arg_pid = newpid;
1385 }
1386 } else if (is_opt(argv[i], "--wait=")) {
1387 if (!numeric_val(argv[i], &check_trials)) {
sewardj30b3eca2011-06-28 08:20:39 +00001388 fprintf (stderr, "invalid --wait argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00001389 arg_errors++;
1390 }
1391 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
1392 if (!numeric_val(argv[i], &max_invoke_ms)) {
sewardj30b3eca2011-06-28 08:20:39 +00001393 fprintf (stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
1394 arg_errors++;
1395 }
1396 } else if (is_opt(argv[i], "--cmd-time-out=")) {
1397 if (!numeric_val(argv[i], &cmd_time_out)) {
1398 fprintf (stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00001399 arg_errors++;
1400 }
sewardj992d3cc2011-10-22 20:38:08 +00001401 } else if (is_opt(argv[i], "--port=")) {
1402 if (!numeric_val(argv[i], &int_port)) {
1403 fprintf (stderr, "invalid --port argument %s\n", argv[i]);
1404 arg_errors++;
1405 }
sewardj3b290482011-05-06 21:02:55 +00001406 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
1407 vgdb_prefix = argv[i] + 14;
1408 } else if (is_opt(argv[i], "-c")) {
1409 last_command++;
1410 commands[last_command] = vmalloc (1);
1411 commands[last_command][0] = '\0';
1412 } else if (0 == strncmp(argv[i], "-", 1)) {
1413 fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
1414 arg_errors++;
1415 } else {
1416 int len;
1417 if (last_command == -1) {
1418 /* only one command, no -c command indicator */
1419 last_command++;
1420 commands[last_command] = vmalloc (1);
1421 commands[last_command][0] = '\0';
1422 }
1423 len = strlen(commands[last_command]);
1424 commands[last_command] = vrealloc (commands[last_command],
1425 len + 1 + strlen(argv[i]) + 1);
1426 if (len > 0)
1427 strcat (commands[last_command], " ");
1428 strcat (commands[last_command], argv[i]);
1429 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
1430 fprintf (stderr, "command %s too long\n", commands[last_command]);
1431 arg_errors++;
1432 }
1433
1434 }
1435 }
sewardjd142f992011-05-17 17:15:07 +00001436
florianb985e2d2011-09-29 03:03:45 +00001437 if (vgdb_prefix == NULL)
1438 vgdb_prefix = vgdb_prefix_default();
1439
sewardjd142f992011-05-17 17:15:07 +00001440 if (isatty(0)
1441 && !show_shared_mem
1442 && !show_list
sewardj992d3cc2011-10-22 20:38:08 +00001443 && int_port == 0
sewardjd142f992011-05-17 17:15:07 +00001444 && last_command == -1) {
1445 arg_errors++;
1446 fprintf (stderr,
1447 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
1448 }
1449
1450 if (show_shared_mem && show_list) {
1451 arg_errors++;
1452 fprintf (stderr,
1453 "Can't use both -D and -l options\n");
1454 }
1455
sewardj30b3eca2011-06-28 08:20:39 +00001456 if (max_invoke_ms > 0
1457 && cmd_time_out != NEVER
1458 && (cmd_time_out * 1000) <= max_invoke_ms) {
1459 arg_errors++;
1460 fprintf (stderr,
1461 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
1462 }
1463
sewardjd142f992011-05-17 17:15:07 +00001464 if (show_list && arg_pid != -1) {
1465 arg_errors++;
1466 fprintf (stderr,
1467 "Can't use both --pid and -l options\n");
1468 }
1469
sewardj992d3cc2011-10-22 20:38:08 +00001470 if (int_port > 0 && last_command != -1) {
1471 arg_errors++;
1472 fprintf (stderr,
1473 "Can't use --port to send commands\n");
1474 }
1475
sewardj3b290482011-05-06 21:02:55 +00001476 if (arg_errors > 0) {
1477 fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
1478 exit(1);
1479 }
1480
1481 *p_show_shared_mem = show_shared_mem;
sewardjd142f992011-05-17 17:15:07 +00001482 *p_show_list = show_list;
sewardj3b290482011-05-06 21:02:55 +00001483 *p_arg_pid = arg_pid;
1484 *p_check_trials = check_trials;
sewardj992d3cc2011-10-22 20:38:08 +00001485 *p_port = int_port;
sewardj3b290482011-05-06 21:02:55 +00001486 *p_last_command = last_command;
1487}
1488
1489int main(int argc, char** argv)
1490{
1491 int i;
1492 int pid;
1493
1494 Bool show_shared_mem;
sewardjd142f992011-05-17 17:15:07 +00001495 Bool show_list;
sewardj3b290482011-05-06 21:02:55 +00001496 int arg_pid;
1497 int check_trials;
sewardj992d3cc2011-10-22 20:38:08 +00001498 int in_port;
sewardj3b290482011-05-06 21:02:55 +00001499 int last_command;
1500 char *commands[argc]; // we will never have more commands than args.
1501
1502 parse_options(argc, argv,
1503 &show_shared_mem,
sewardjd142f992011-05-17 17:15:07 +00001504 &show_list,
sewardj3b290482011-05-06 21:02:55 +00001505 &arg_pid,
1506 &check_trials,
sewardj992d3cc2011-10-22 20:38:08 +00001507 &in_port,
sewardj3b290482011-05-06 21:02:55 +00001508 &last_command,
1509 commands);
1510
1511 /* when we are working as a relay for gdb, handle some signals by
1512 only reporting them (according to debug level). Also handle these
1513 when ptrace will be used: vgdb must clean up the ptrace effect before
1514 dying. */
1515 if (max_invoke_ms > 0 || last_command == -1)
1516 install_handlers();
1517
sewardjd142f992011-05-17 17:15:07 +00001518 pid = search_arg_pid (arg_pid, check_trials, show_list);
sewardj3b290482011-05-06 21:02:55 +00001519
1520 prepare_fifos_and_shared_mem(pid);
1521
sewardj992d3cc2011-10-22 20:38:08 +00001522 if (in_port > 0)
1523 wait_for_gdb_connect(in_port);
1524
sewardj3b290482011-05-06 21:02:55 +00001525 if (show_shared_mem) {
1526 fprintf(stderr,
1527 "vgdb %d "
1528 "written_by_vgdb %d "
1529 "seen_by_valgrind %d\n"
1530 "vgdb pid %d\n",
1531 VS_vgdb_pid,
1532 VS_written_by_vgdb,
1533 VS_seen_by_valgrind,
1534 VS_vgdb_pid);
1535 exit (0);
1536 }
1537
1538 if (last_command >= 0) {
1539 standalone_send_commands(pid, last_command, commands);
1540 } else {
1541 gdb_relay(pid);
1542 }
1543
1544
1545 free (from_gdb_to_pid);
1546 free (to_gdb_from_pid);
1547 free (shared_mem);
1548
1549 for (i = 0; i <= last_command; i++)
1550 free (commands[i]);
1551 return 0;
1552}