blob: 06e37e6792523294f1c8700942a93fbe4b891fb1 [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
sewardj1568e172011-06-18 08:28:04 +00009 Copyright (C) 2011-2011 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
sewardjcbe38502011-07-12 11:59:11 +000029#include "pub_core_basics.h"
30#include "pub_core_vki.h"
31#include "pub_core_libcsetjmp.h"
32#include "pub_core_threadstate.h"
33#include "pub_core_gdbserver.h"
florianb985e2d2011-09-29 03:03:45 +000034#include "config.h"
sewardjcbe38502011-07-12 11:59:11 +000035
sewardj30b3eca2011-06-28 08:20:39 +000036#include <limits.h>
sewardj56501b62011-07-12 17:28:39 +000037#include <unistd.h>
sewardj3b290482011-05-06 21:02:55 +000038#include <string.h>
39#include <poll.h>
40#include <pthread.h>
41#include <stdlib.h>
42#include <stdio.h>
43#include <fcntl.h>
44#include <dirent.h>
45#include <sys/stat.h>
46#include <sys/time.h>
47#include <errno.h>
sewardje7f8f3f2011-07-12 17:41:50 +000048#include <signal.h>
sewardj992d3cc2011-10-22 20:38:08 +000049#include <sys/types.h>
50#include <sys/socket.h>
51#include <netinet/in.h>
52#include <arpa/inet.h>
sewardj3b290482011-05-06 21:02:55 +000053#include <sys/mman.h>
54#include <sys/ptrace.h>
55#include <sys/wait.h>
sewardjcbe38502011-07-12 11:59:11 +000056#include <assert.h>
sewardj3b290482011-05-06 21:02:55 +000057/* vgdb has two usages:
58 1. relay application between gdb and the gdbserver embedded in valgrind.
59 2. standalone to send monitor commands to a running valgrind-ified process
60
61 It is made of a main program which reads arguments. If no
62 arguments are given or only --pid and --vgdb-prefix, then usage 1 is
63 assumed.
64
65 As relay application, vgdb reads bytes from gdb on stdin and
66 writes these bytes to valgrind. Bytes read from valgrind are
67 written to gdb on stdout. Read/Write from/to valgrind is done
68 using FIFOs. There is one thread reading from stdin, writing to
69 valgrind on a FIFO. There is one thread reading from valgrind on a
70 FIFO, writing to gdb on stdout
71
72 As a standalone utility, vgdb builds command packets to write to valgrind,
73 sends it and reads the reply. The same two threads are used to write/read.
74 Once all the commands are sent and their replies received, vgdb will exit.
75
76*/
77
78/* define PTRACEINVOKER to compile the ptrace related code
79 which ensures a valgrind process blocked in a system call
80 can be "waken up". PTRACEINVOKER implies some architecture
81 specific code and/or some OS specific code. */
82#if defined(VGA_arm) || defined(VGA_x86) || defined(VGA_amd64) \
83 || defined(VGA_ppc32) || defined(VGA_ppc64) || defined(VGA_s390x)
84#define PTRACEINVOKER
85#else
86I_die_here : (PTRACEINVOKER) architecture missing in vgdb.c
87#endif
88
89/* Some darwin specific stuff is needed as ptrace is not
90 fully supported on MacOS. Till we find someone courageous
91 having access to Darwin, there is no PTRACEINVOKER. */
92#if defined(VGO_darwin)
93#undef PTRACEINVOKER
94#endif
95
sewardj992d3cc2011-10-22 20:38:08 +000096#if defined(VGPV_arm_linux_android)
97#undef PTRACEINVOKER
98#endif
99
100#if defined(PTRACEINVOKER)
101#include <sys/user.h>
102#if defined(VGO_linux)
103# include <sys/prctl.h>
104# include <linux/ptrace.h>
105#endif
106#endif
107
108
sewardj30b3eca2011-06-28 08:20:39 +0000109// Outputs information for the user about ptrace_scope protection
110// or ptrace not working.
111static void ptrace_restrictions_msg(void);
112
sewardj3b290482011-05-06 21:02:55 +0000113static int debuglevel;
114static struct timeval dbgtv;
115/* if level <= debuglevel, print timestamp, then print provided by debug info */
116#define DEBUG(level, ...) (level <= debuglevel ? \
117 gettimeofday(&dbgtv, NULL), \
118 fprintf(stderr, "%ld.%6.6ld ", \
119 (long int)dbgtv.tv_sec, \
120 (long int)dbgtv.tv_usec), \
121 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
122 : 0)
123
124/* same as DEBUG but does not print time stamp info */
125#define PDEBUG(level, ...) (level <= debuglevel ? \
126 fprintf(stderr, __VA_ARGS__),fflush(stderr) \
127 : 0)
128
129/* if errno != 0,
130 report the errno and fprintf the ... varargs on stderr. */
131#define ERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
132 fprintf(stderr, __VA_ARGS__), \
133 fflush(stderr))
134/* same as ERROR, but also exits with status 1 */
135#define XERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
136 fprintf(stderr, __VA_ARGS__), \
137 fflush(stderr), \
138 exit(1))
139
florianb985e2d2011-09-29 03:03:45 +0000140static char *vgdb_prefix = NULL;
sewardj3b290482011-05-06 21:02:55 +0000141
142/* Will be set to True when any condition indicating we have to shutdown
143 is encountered. */
144static Bool shutting_down = False;
145
146static VgdbShared32 *shared32;
147static VgdbShared64 *shared64;
148#define VS_written_by_vgdb (shared32 != NULL ? \
149 shared32->written_by_vgdb \
150 : shared64->written_by_vgdb)
151#define VS_seen_by_valgrind (shared32 != NULL ? \
152 shared32->seen_by_valgrind \
153 : shared64->seen_by_valgrind)
154
155#define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
156
157/* Calls malloc (size). Exits if memory can't be allocated. */
158static
159void *vmalloc(size_t size)
160{
161 void * mem = malloc(size);
162 if (mem == NULL)
163 XERROR (errno, "can't allocate memory\n");
164 return mem;
165}
166
167/* Calls realloc (size). Exits if memory can't be allocated. */
168static
169void *vrealloc(void *ptr,size_t size)
170{
171 void * mem = realloc(ptr, size);
172 if (mem == NULL)
173 XERROR (errno, "can't reallocate memory\n");
174 return mem;
175}
176
florianb985e2d2011-09-29 03:03:45 +0000177/* Return the name of a directory for temporary files. */
178static
179const char *vgdb_tmpdir(void)
180{
181 const char *tmpdir;
182
183 tmpdir = getenv("TMPDIR");
philippeae52a932012-01-13 21:36:46 +0000184 if (tmpdir == NULL || *tmpdir == '\0')
185 tmpdir = VG_TMPDIR;
186 if (tmpdir == NULL || *tmpdir == '\0')
187 tmpdir = "/tmp"; /* fallback */
florianb985e2d2011-09-29 03:03:45 +0000188
189 return tmpdir;
190}
191
philippeae52a932012-01-13 21:36:46 +0000192/* Return the default path prefix for the named pipes (FIFOs) used by vgdb/gdb
florianb985e2d2011-09-29 03:03:45 +0000193 to communicate with valgrind */
194static
195char *vgdb_prefix_default(void)
196{
philippeae52a932012-01-13 21:36:46 +0000197 static HChar *prefix;
florianb985e2d2011-09-29 03:03:45 +0000198
philippeae52a932012-01-13 21:36:46 +0000199 if (prefix == NULL) {
200 const char *tmpdir = vgdb_tmpdir();
201 prefix = vmalloc(strlen(tmpdir) + strlen("/vgdb-pipe") + 1);
202 strcpy(prefix, tmpdir);
203 strcat(prefix, "/vgdb-pipe");
204 }
florianb985e2d2011-09-29 03:03:45 +0000205 return prefix;
206}
207
sewardj3b290482011-05-06 21:02:55 +0000208/* add nrw to the written_by_vgdb field of shared32 or shared64 */
209static
210void add_written(int nrw)
211{
212 if (shared32 != NULL)
213 shared32->written_by_vgdb += nrw;
214 else if (shared64 != NULL)
215 shared64->written_by_vgdb += nrw;
216 else
217 assert(0);
218}
219
220static int shared_mem_fd = -1;
221static
222void map_vgdbshared (char* shared_mem)
223{
224 struct stat fdstat;
225 void **s;
226 shared_mem_fd = open(shared_mem, O_RDWR);
227 /* shared_mem_fd will not be closed till vgdb exits. */
228
229 if (shared_mem_fd == -1)
230 XERROR (errno, "error opening %s shared memory file\n", shared_mem);
231
232 if (fstat(shared_mem_fd, &fdstat) != 0)
233 XERROR (errno, "fstat");
234
235 if (fdstat.st_size == sizeof(VgdbShared64))
236 s = (void*) &shared64;
237 else if (fdstat.st_size == sizeof(VgdbShared32))
238 s = (void*) &shared32;
239 else
240#if VEX_HOST_WORDSIZE == 8
241 XERROR (0,
242 "error size shared memory file %s.\n"
243 "expecting size %d (64bits) or %d (32bits) got %ld.\n",
244 shared_mem,
245 (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32),
246 (long int)fdstat.st_size);
247#elif VEX_HOST_WORDSIZE == 4
248 XERROR (0,
249 "error size shared memory file %s.\n"
250 "expecting size %d (32bits) got %ld.\n",
251 shared_mem,
252 (int) sizeof(VgdbShared32),
253 fdstat.st_size);
254#else
255# error "unexpected wordsize"
256#endif
257
258#if VEX_HOST_WORDSIZE == 4
259 if (shared64 != NULL)
260 XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
261 /* But we can use a 64 bits vgdb with a 32 bits valgrind */
262#endif
263
264 *s = (void*) mmap (NULL, fdstat.st_size,
265 PROT_READ|PROT_WRITE, MAP_SHARED,
266 shared_mem_fd, 0);
267
268 if (*s == (void *) -1)
269 XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
270
271}
272
273#if VEX_HOST_WORDSIZE == 8
274typedef Addr64 CORE_ADDR;
275typedef Addr64 PTRACE_XFER_TYPE;
276typedef void* PTRACE_ARG3_TYPE;
277#elif VEX_HOST_WORDSIZE == 4
278typedef Addr32 CORE_ADDR;
279typedef Addr32 PTRACE_XFER_TYPE;
280typedef void* PTRACE_ARG3_TYPE;
281#else
282# error "unexpected wordsize"
283#endif
284
285static Bool pid_of_save_regs_continued = False;
286// True if we have continued pid_of_save_regs after PTRACE_ATTACH
287
288static Bool dying = False;
289// Set to True when loss of connection indicating that the Valgrind
290// process is dying.
291
292/* To be called when connection with valgrind is lost. In case we
293have lost the connection, it means that Valgrind has closed the
294connection and is busy exiting. We can't and don't have to stop it in
295this case. */
296static
297void valgrind_dying(void)
298{
299 pid_of_save_regs_continued = False;
300 dying = True;
301}
302
303
304#ifdef PTRACEINVOKER
305/* ptrace_(read|write)_memory are modified extracts of linux-low.c
306 from gdb 6.6. Copyrighted FSF */
307/* Copy LEN bytes from inferior's memory starting at MEMADDR
308 to debugger memory starting at MYADDR. */
309
310static
311int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
312 unsigned char *myaddr, int len)
313{
314 register int i;
315 /* Round starting address down to longword boundary. */
316 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
317 /* Round ending address up; get number of longwords that makes. */
318 register int count
319 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
320 / sizeof (PTRACE_XFER_TYPE);
321 /* Allocate buffer of that many longwords. */
322 register PTRACE_XFER_TYPE *buffer
323 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
324
325 /* Read all the longwords */
326 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
327 errno = 0;
328 buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
329 (PTRACE_ARG3_TYPE) addr, 0);
330 if (errno)
331 return errno;
332 }
333
334 /* Copy appropriate bytes out of the buffer. */
335 memcpy (myaddr,
336 (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
337
338 return 0;
339}
340
341/* Copy LEN bytes of data from debugger memory at MYADDR
342 to inferior's memory at MEMADDR.
343 On failure (cannot write the inferior)
344 returns the value of errno. */
345
346static
347int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr,
348 const unsigned char *myaddr, int len)
349{
350 register int i;
351 /* Round starting address down to longword boundary. */
352 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
353 /* Round ending address up; get number of longwords that makes. */
354 register int count
355 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
356 / sizeof (PTRACE_XFER_TYPE);
357 /* Allocate buffer of that many longwords. */
358 register PTRACE_XFER_TYPE *buffer
359 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
360
361 if (debuglevel >= 1) {
362 DEBUG (1, "Writing ");
363 for (i = 0; i < len; i++)
364 PDEBUG (1, "%02x", (unsigned)myaddr[i]);
365 PDEBUG(1, " to %p\n", (void *) memaddr);
366 }
367
368 /* Fill start and end extra bytes of buffer with existing memory data. */
369
370 buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
371 (PTRACE_ARG3_TYPE) addr, 0);
372
373 if (count > 1) {
374 buffer[count - 1]
375 = ptrace (PTRACE_PEEKTEXT, inferior_pid,
376 (PTRACE_ARG3_TYPE) (addr + (count - 1)
377 * sizeof (PTRACE_XFER_TYPE)),
378 0);
379 }
380
381 /* Copy data to be written over corresponding part of buffer */
382
383 memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
384 myaddr, len);
385
386 /* Write the entire buffer. */
387
388 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
389 errno = 0;
390 ptrace (PTRACE_POKETEXT, inferior_pid,
391 (PTRACE_ARG3_TYPE) addr, buffer[i]);
392 if (errno)
393 return errno;
394 }
395
396 return 0;
397}
398
399/* subset of VG_(threads) needed for vgdb ptrace.
400 This is initialized when process is attached. */
401typedef struct {
402 ThreadStatus status;
403 Int lwpid;
404}
405VgdbThreadState;
406static VgdbThreadState vgdb_threads[VG_N_THREADS];
407
408static const
409HChar* name_of_ThreadStatus ( ThreadStatus status )
410{
411 switch (status) {
412 case VgTs_Empty: return "VgTs_Empty";
413 case VgTs_Init: return "VgTs_Init";
414 case VgTs_Runnable: return "VgTs_Runnable";
415 case VgTs_WaitSys: return "VgTs_WaitSys";
416 case VgTs_Yielding: return "VgTs_Yielding";
417 case VgTs_Zombie: return "VgTs_Zombie";
418 default: return "VgTs_???";
419 }
420}
421
422static
423char *status_image (int status)
424{
425 static char result[256];
426 int sz = 0;
427#define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
428
429 result[0] = 0;
430
431 if (WIFEXITED(status))
432 APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
433
434 if (WIFSIGNALED(status)) {
435 APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
436 if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
437 }
438
439 if (WIFSTOPPED(status))
440 APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
441
442 if (WIFCONTINUED(status))
443 APPEND ("WIFCONTINUED ");
444
445 return result;
446#undef APPEND
447}
448
449/* Wait till the process pid is reported as stopped with signal_expected.
450 If other signal(s) than signal_expected are received, waitstopped
451 will pass them to pid, waiting for signal_expected to stop pid.
452 Returns True when process is in stopped state with signal_expected.
453 Returns False if a problem was encountered while waiting for pid
454 to be stopped.
455
456 If pid is reported as being dead/exited, waitstopped will return False.
457*/
458static
459Bool waitstopped (int pid, int signal_expected, char *msg)
460{
461 pid_t p;
462 int status = 0;
463 int signal_received;
464 int res;
465
466 while (1) {
467 DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
468 msg, signal_expected);
469 p = waitpid(pid, &status, __WALL);
470 DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p,
471 status, status_image (status));
472 if (p != pid) {
473 ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n",
474 msg, pid, p, status, status_image (status));
475 return False;
476 }
477
478 if (WIFEXITED(status)) {
479 shutting_down = True;
480 return False;
481 }
482
483 assert (WIFSTOPPED(status));
484 signal_received = WSTOPSIG(status);
485 if (signal_received == signal_expected)
486 break;
487
488 /* pid received a signal which is not the signal we are waiting for.
489 We continue pid, transmitting this signal. */
490 DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
491 res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
492 if (res != 0) {
493 ERROR(errno, "waitstopped PTRACE_CONT\n");
494 return False;
495 }
496 }
497
498 return True;
499}
500
501/* Stops the given pid, wait for the process to be stopped.
502 Returns True if succesful, False otherwise.
503 msg is used in tracing and error reporting. */
504static
505Bool stop (int pid, char *msg)
506{
507 long res;
508
509 DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
510 res = kill (pid, SIGSTOP);
511 if (res != 0) {
512 ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
513 return False;
514 }
515
516 return waitstopped (pid, SIGSTOP, msg);
517
518}
519
520/* Attaches to given pid, wait for the process to be stopped.
521 Returns True if succesful, False otherwise.
522 msg is used in tracing and error reporting. */
523static
524Bool attach (int pid, char *msg)
525{
526 long res;
sewardj30b3eca2011-06-28 08:20:39 +0000527 static Bool output_error = True;
528 static Bool initial_attach = True;
529 // For a ptrace_scope protected system, we do not want to output
530 // repetitively attach error. We will output once an error
531 // for the initial_attach. Once the 1st attach has succeeded, we
532 // again show all errors.
sewardj3b290482011-05-06 21:02:55 +0000533
534 DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
535 res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
536 if (res != 0) {
sewardj30b3eca2011-06-28 08:20:39 +0000537 if (output_error || debuglevel > 0) {
538 ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
539 if (initial_attach)
540 output_error = False;
541 }
sewardj3b290482011-05-06 21:02:55 +0000542 return False;
543 }
544
sewardj30b3eca2011-06-28 08:20:39 +0000545 initial_attach = False;
546 output_error = True;
sewardj3b290482011-05-06 21:02:55 +0000547 return waitstopped(pid, SIGSTOP, msg);
548}
549
550/* once we are attached to the pid, get the list of threads and stop
551 them all.
552 Returns True if all threads properly suspended, False otherwise. */
553static
554Bool acquire_and_suspend_threads(int pid)
555{
556 int i;
557 int rw;
558 Bool pid_found = False;
559 Addr vgt;
560 int sz_tst;
561 int off_status;
562 int off_lwpid;
563 int nr_live_threads = 0;
564
565 if (shared32 != NULL) {
566 vgt = shared32->threads;
567 sz_tst = shared32->sizeof_ThreadState;
568 off_status = shared32->offset_status;
569 off_lwpid = shared32->offset_lwpid;
570 }
571 else if (shared64 != NULL) {
572 vgt = shared64->threads;
573 sz_tst = shared64->sizeof_ThreadState;
574 off_status = shared64->offset_status;
575 off_lwpid = shared64->offset_lwpid;
576 } else {
577 assert (0);
578 }
579
580 /* note: the entry 0 is unused */
581 for (i = 1; i < VG_N_THREADS; i++) {
582 vgt += sz_tst;
583 rw = ptrace_read_memory(pid, vgt+off_status,
584 (unsigned char *)&(vgdb_threads[i].status),
585 sizeof(ThreadStatus));
586 if (rw != 0) {
587 ERROR(rw, "status ptrace_read_memory\n");
588 return False;
589 }
590
591 rw = ptrace_read_memory(pid, vgt+off_lwpid,
592 (unsigned char *)&(vgdb_threads[i].lwpid),
593 sizeof(Int));
594 if (rw != 0) {
595 ERROR(rw, "lwpid ptrace_read_memory\n");
596 return False;
597 }
598
599 if (vgdb_threads[i].status != VgTs_Empty) {
600 DEBUG(1, "found tid %d status %s lwpid %d\n",
601 i, name_of_ThreadStatus(vgdb_threads[i].status),
602 vgdb_threads[i].lwpid);
603 nr_live_threads++;
604 if (vgdb_threads[i].lwpid <= 1) {
605 if (vgdb_threads[i].lwpid == 0
606 && vgdb_threads[i].status == VgTs_Init) {
607 DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
608 i, name_of_ThreadStatus(vgdb_threads[i].status),
609 vgdb_threads[i].lwpid);
610 } else {
611 ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
612 i, name_of_ThreadStatus(vgdb_threads[i].status),
613 vgdb_threads[i].lwpid);
614 }
615 /* in case we have a VtTs_Init thread with lwpid not yet set,
616 we try again later. */
617 return False;
618 }
619 if (vgdb_threads[i].lwpid == pid) {
620 assert (!pid_found);
621 assert (i == 1);
622 pid_found = True;
623 } else {
624 if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
625 ERROR(0, "ERROR attach pid %d tid %d\n",
626 vgdb_threads[i].lwpid, i);
627 return False;
628 }
629 }
630 }
631 }
632 /* If we found no thread, it means the process is stopping, and
633 we better do not force anything to happen during that. */
634 if (nr_live_threads > 0)
635 return True;
636 else
637 return False;
638}
639
640static
641void detach_from_all_threads(int pid)
642{
643 int i;
644 long res;
645 Bool pid_found = False;
646
647 /* detach from all the threads */
648 for (i = 1; i < VG_N_THREADS; i++) {
649 if (vgdb_threads[i].status != VgTs_Empty) {
650 if (vgdb_threads[i].status == VgTs_Init
651 && vgdb_threads[i].lwpid == 0) {
652 DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
653 vgdb_threads[i].lwpid, i,
654 name_of_ThreadStatus (vgdb_threads[i].status));
655 } else {
656 if (vgdb_threads[i].lwpid == pid) {
657 assert (!pid_found);
658 pid_found = True;
659 }
660 DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
661 vgdb_threads[i].lwpid, i,
662 name_of_ThreadStatus (vgdb_threads[i].status));
663 res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
664 if (res != 0) {
665 ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n",
666 vgdb_threads[i].lwpid, i,
667 name_of_ThreadStatus (vgdb_threads[i].status),
668 res);
669 }
670 }
671 }
672 }
673
674 if (!pid_found && pid) {
675 /* No threads are live. Process is busy stopping.
676 We need to detach from pid explicitely. */
677 DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
678 res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
679 if (res != 0)
680 ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
681 }
682}
683
684// if > 0, pid for which registers have to be restored.
685static int pid_of_save_regs = 0;
686static struct user user_save;
687
sewardjeefeeb72011-05-10 11:01:07 +0000688// The below indicates if ptrace_getregs (and ptrace_setregs) can be used.
689// Note that some linux versions are defining PTRACE_GETREGS but using
690// it gives back EIO.
691// has_working_ptrace_getregs can take the following values:
692// -1 : PTRACE_GETREGS is defined
693// runtime check not yet done.
694// 0 : PTRACE_GETREGS runtime check has failed.
695// 1 : PTRACE_GETREGS defined and runtime check ok.
696#ifdef PTRACE_GETREGS
697static int has_working_ptrace_getregs = -1;
698#endif
699
sewardj3b290482011-05-06 21:02:55 +0000700/* Get the registers from pid into regs.
sewardjeefeeb72011-05-10 11:01:07 +0000701 regs_bsz value gives the length of *regs.
sewardj3b290482011-05-06 21:02:55 +0000702 Returns True if all ok, otherwise False. */
703static
sewardjeefeeb72011-05-10 11:01:07 +0000704Bool getregs (int pid, void *regs, long regs_bsz)
sewardj3b290482011-05-06 21:02:55 +0000705{
sewardjeefeeb72011-05-10 11:01:07 +0000706 DEBUG(1, "getregs regs_bsz %ld\n", regs_bsz);
707# ifdef PTRACE_GETREGS
708 if (has_working_ptrace_getregs) {
709 // Platforms having GETREGS
710 long res;
711 DEBUG(1, "getregs PTRACE_GETREGS\n");
712 res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
713 if (res == 0) {
714 if (has_working_ptrace_getregs == -1) {
715 // First call to PTRACE_GETREGS succesful =>
716 has_working_ptrace_getregs = 1;
717 DEBUG(1, "detected a working PTRACE_GETREGS\n");
718 }
719 assert (has_working_ptrace_getregs == 1);
720 return True;
721 }
722 else if (has_working_ptrace_getregs == 1) {
723 // We had a working call, but now it fails.
724 // This is unexpected.
725 ERROR(errno, "PTRACE_GETREGS %ld\n", res);
sewardj3b290482011-05-06 21:02:55 +0000726 return False;
sewardjeefeeb72011-05-10 11:01:07 +0000727 } else {
728 // Check this is the first call:
729 assert (has_working_ptrace_getregs == -1);
730 if (errno == EIO) {
731 DEBUG(1, "detected a broken PTRACE_GETREGS with EIO\n");
732 has_working_ptrace_getregs = 0;
733 // Fall over to the PTRACE_PEEKUSER case.
734 } else {
735 ERROR(errno, "broken PTRACE_GETREGS unexpected errno %ld\n", res);
736 return False;
737 }
sewardj3b290482011-05-06 21:02:55 +0000738 }
739 }
sewardj3b290482011-05-06 21:02:55 +0000740# endif
sewardjeefeeb72011-05-10 11:01:07 +0000741
742 // We assume PTRACE_PEEKUSER is defined everywhere.
743 {
744# ifdef PT_ENDREGS
745 long peek_bsz = PT_ENDREGS;
746 assert (peek_bsz <= regs_bsz);
747# else
748 long peek_bsz = regs_bsz-1;
749# endif
750 char *pregs = (char *) regs;
751 long offset;
752 errno = 0;
753 DEBUG(1, "getregs PTRACE_PEEKUSER(s) peek_bsz %ld\n", peek_bsz);
754 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
755 *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
756 if (errno != 0) {
757 ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
758 return False;
759 }
760 }
761 return True;
762 }
763
764 // If neither PTRACE_GETREGS not PTRACE_PEEKUSER have returned,
765 // then we are in serious trouble.
766 assert (0);
sewardj3b290482011-05-06 21:02:55 +0000767}
768
769/* Set the registers of pid to regs.
sewardjeefeeb72011-05-10 11:01:07 +0000770 regs_bsz value gives the length of *regs.
sewardj3b290482011-05-06 21:02:55 +0000771 Returns True if all ok, otherwise False. */
772static
sewardjeefeeb72011-05-10 11:01:07 +0000773Bool setregs (int pid, void *regs, long regs_bsz)
sewardj3b290482011-05-06 21:02:55 +0000774{
sewardjeefeeb72011-05-10 11:01:07 +0000775 DEBUG(1, "setregs regs_bsz %ld\n", regs_bsz);
776// Note : the below is checking for GETREGS, not SETREGS
777// as if one is defined and working, the other one should also work.
778# ifdef PTRACE_GETREGS
779 if (has_working_ptrace_getregs) {
780 // Platforms having SETREGS
781 long res;
782 // setregs can never be called before getregs has done a runtime check.
783 assert (has_working_ptrace_getregs == 1);
784 DEBUG(1, "setregs PTRACE_SETREGS\n");
785 res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
786 if (res != 0) {
787 ERROR(errno, "PTRACE_SETREGS %ld\n", res);
sewardj3b290482011-05-06 21:02:55 +0000788 return False;
789 }
sewardjeefeeb72011-05-10 11:01:07 +0000790 return True;
sewardj3b290482011-05-06 21:02:55 +0000791 }
sewardj3b290482011-05-06 21:02:55 +0000792# endif
sewardjeefeeb72011-05-10 11:01:07 +0000793
794 {
795 char *pregs = (char *) regs;
796 long offset;
797 long res;
798# ifdef PT_ENDREGS
799 long peek_bsz = PT_ENDREGS;
800 assert (peek_bsz <= regs_bsz);
801# else
802 long peek_bsz = regs_bsz-1;
803# endif
804 errno = 0;
805 DEBUG(1, "setregs PTRACE_POKEUSER(s) %ld\n", peek_bsz);
806 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
807 res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
808 if (errno != 0) {
809 ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
810 return False;
811 }
812 }
813 return True;
814 }
815
816 // If neither PTRACE_SETREGS not PTRACE_POKEUSER have returned,
817 // then we are in serious trouble.
818 assert (0);
sewardj3b290482011-05-06 21:02:55 +0000819}
820
821/* Restore the registers to the saved value, then detaches from all threads */
822static
823void restore_and_detach(int pid)
824{
825 if (pid_of_save_regs) {
826 /* In case the 'main pid' has been continued, we need to stop it
827 before resetting the registers. */
828 if (pid_of_save_regs_continued) {
829 pid_of_save_regs_continued = False;
830 if (!stop(pid_of_save_regs, "sigstop before reset regs"))
831 DEBUG(0, "Could not sigstop before reset");
832 }
833
834 DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
sewardjeefeeb72011-05-10 11:01:07 +0000835 if (!setregs(pid_of_save_regs, &user_save.regs, sizeof(user_save.regs))) {
sewardj3b290482011-05-06 21:02:55 +0000836 ERROR(errno, "setregs restore registers pid %d after cont\n",
837 pid_of_save_regs);
838 }
839 pid_of_save_regs = 0;
840 } else {
841 DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
842 }
843 detach_from_all_threads(pid);
844}
845
846/* Ensures that the gdbserver code is invoked by pid.
847 If an error occurs, resets to the valgrind process
848 to the state it has before being ptrace-d.
849 Returns True if invoke successful, False otherwise.
850*/
851static
852Bool invoke_gdbserver (int pid)
853{
sewardj30b3eca2011-06-28 08:20:39 +0000854 static Bool ptrace_restrictions_msg_given = False;
sewardj3b290482011-05-06 21:02:55 +0000855 long res;
856 Bool stopped;
857 struct user user_mod;
858 Addr sp;
859 /* A specific int value is passed to invoke_gdbserver, to check
860 everything goes according to the plan. */
861 const int check = 0x8BADF00D; // ate bad food.
862
863 const Addr bad_return = 0;
864 // A bad return address will be pushed on the stack.
865 // The function invoke_gdbserver cannot return. If ever it returns, a NULL
866 // address pushed on the stack should ensure this is detected.
867
868 /* Not yet attached. If problem, vgdb can abort,
869 no cleanup needed.
870
871 On Ubuntu>= 10.10, a /proc setting can disable ptrace.
872 So, Valgrind has to SET_PTRACER this vgdb. Once this
873 is done, this vgdb can ptrace the valgrind process. */
874
875 DEBUG(1, "attach to 'main' pid %d\n", pid);
876 if (!attach(pid, "attach main pid")) {
sewardj30b3eca2011-06-28 08:20:39 +0000877 if (!ptrace_restrictions_msg_given) {
878 ptrace_restrictions_msg_given = True;
879 ERROR(0, "error attach main pid %d\n", pid);
880 ptrace_restrictions_msg();
881 }
sewardj3b290482011-05-06 21:02:55 +0000882 return False;
883 }
884
885 /* Now, we are attached. If problem, detach and return. */
886
887 if (!acquire_and_suspend_threads(pid)) {
888 detach_from_all_threads(pid);
889 /* if the pid does not exist anymore, we better stop */
890 if (kill(pid, 0) != 0)
891 XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
892 pid);
893 return False;
894 }
895
sewardjeefeeb72011-05-10 11:01:07 +0000896 if (!getregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
sewardj3b290482011-05-06 21:02:55 +0000897 detach_from_all_threads(pid);
898 return False;
899 }
900 user_save = user_mod;
901
902#if defined(VGA_x86)
903 sp = user_mod.regs.esp;
904#elif defined(VGA_amd64)
905 sp = user_mod.regs.rsp;
906 if (shared32 != NULL) {
907 /* 64bit vgdb speaking with a 32bit executable.
908 To have system call restart properly, we need to sign extend rax.
909 For more info:
910 web search '[patch] Fix syscall restarts for amd64->i386 biarch'
911 e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
912 *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
913 DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
914 user_mod.regs.rax, user_save.regs.rax);
915 }
916#elif defined(VGA_arm)
917 sp = user_mod.regs.uregs[13];
918#elif defined(VGA_ppc32)
919 sp = user_mod.regs.gpr[1];
920#elif defined(VGA_ppc64)
921 sp = user_mod.regs.gpr[1];
922#elif defined(VGA_s390x)
923 sp = user_mod.regs.gprs[15];
924#else
925 I_die_here : (sp) architecture missing in vgdb.c
926#endif
927
928
929 // the magic below is derived from spying what gdb sends to
930 // the (classical) gdbserver when invoking a C function.
931 if (shared32 != NULL) {
932 // vgdb speaking with a 32bit executable.
933#if defined(VGA_x86) || defined(VGA_amd64)
934 const int regsize = 4;
935 int rw;
936 /* push check arg on the stack */
937 sp = sp - regsize;
938 DEBUG(1, "push check arg ptrace_write_memory\n");
939 assert(regsize == sizeof(check));
940 rw = ptrace_write_memory(pid, sp,
941 (unsigned char *) &check,
942 regsize);
943 if (rw != 0) {
944 ERROR(rw, "push check arg ptrace_write_memory");
945 detach_from_all_threads(pid);
946 return False;
947 }
948
949 sp = sp - regsize;
950 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
951 // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
952 // are written.
953 rw = ptrace_write_memory(pid, sp,
954 (unsigned char *) &bad_return,
955 regsize);
956 if (rw != 0) {
957 ERROR(rw, "push bad_return return address ptrace_write_memory");
958 detach_from_all_threads(pid);
959 return False;
960 }
961#if defined(VGA_x86)
962 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
963 // compiled in 32bits, speaking with a 32bits exe
964 user_mod.regs.ebp = sp; // bp set to sp
965 user_mod.regs.esp = sp;
966 user_mod.regs.eip = shared32->invoke_gdbserver;
967 user_mod.regs.orig_eax = -1L;
968#elif defined(VGA_amd64)
969 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
970 // compiled in 64bits, speaking with a 32bits exe
971 user_mod.regs.rbp = sp; // bp set to sp
972 user_mod.regs.rsp = sp;
973 user_mod.regs.rip = shared32->invoke_gdbserver;
974 user_mod.regs.orig_rax = -1L;
975#else
976 I_die_here : not x86 or amd64 in x86/amd64 section/
977#endif
978
979#elif defined(VGA_ppc32) || defined(VGA_ppc64)
980 user_mod.regs.nip = shared32->invoke_gdbserver;
981 user_mod.regs.trap = -1L;
982 /* put check arg in register 3 */
983 user_mod.regs.gpr[3] = check;
984 /* put NULL return address in Link Register */
985 user_mod.regs.link = bad_return;
986
987#elif defined(VGA_arm)
988 /* put check arg in register 0 */
989 user_mod.regs.uregs[0] = check;
990 /* put NULL return address in Link Register */
991 user_mod.regs.uregs[14] = bad_return;
992 user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
993
994#elif defined(VGA_s390x)
995 XERROR(0, "(fn32) s390x has no 32bits implementation");
996#else
997 I_die_here : architecture missing in vgdb.c
998#endif
999 }
1000
1001 else if (shared64 != NULL) {
1002#if defined(VGA_x86)
1003 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
1004#elif defined(VGA_amd64)
1005 // vgdb speaking with a 64 bit executable.
1006 const int regsize = 8;
1007 int rw;
1008
1009 /* give check arg in rdi */
1010 user_mod.regs.rdi = check;
1011
1012 /* push return address on stack : return to breakaddr */
1013 sp = sp - regsize;
1014 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
1015 rw = ptrace_write_memory(pid, sp,
1016 (unsigned char *) &bad_return,
1017 sizeof(bad_return));
1018 if (rw != 0) {
1019 ERROR(rw, "push bad_return return address ptrace_write_memory");
1020 detach_from_all_threads(pid);
1021 return False;
1022 }
1023
1024 /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
1025 user_mod.regs.rbp = sp; // bp set to sp
1026 user_mod.regs.rsp = sp;
1027 user_mod.regs.rip = shared64->invoke_gdbserver;
1028 user_mod.regs.orig_rax = -1L;
1029
1030#elif defined(VGA_arm)
1031 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
1032#elif defined(VGA_ppc32)
1033 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
1034#elif defined(VGA_ppc64)
1035 Addr64 func_addr;
1036 Addr64 toc_addr;
1037 int rw;
1038 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
1039 (unsigned char *)&func_addr,
1040 sizeof(Addr64));
1041 if (rw != 0) {
1042 ERROR(rw, "ppc64 read func_addr\n");
1043 detach_from_all_threads(pid);
1044 return False;
1045 }
1046 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
1047 (unsigned char *)&toc_addr,
1048 sizeof(Addr64));
1049 if (rw != 0) {
1050 ERROR(rw, "ppc64 read toc_addr\n");
1051 detach_from_all_threads(pid);
1052 return False;
1053 }
1054 // We are not pushing anything on the stack, so it is not
1055 // very clear why the sp has to be decreased, but it seems
1056 // needed. The ppc64 ABI might give some lights on this ?
1057 user_mod.regs.gpr[1] = sp - 220;
1058 user_mod.regs.gpr[2] = toc_addr;
1059 user_mod.regs.nip = func_addr;
1060 user_mod.regs.trap = -1L;
1061 /* put check arg in register 3 */
1062 user_mod.regs.gpr[3] = check;
1063 /* put bad_return return address in Link Register */
1064 user_mod.regs.link = bad_return;
1065#elif defined(VGA_s390x)
1066 /* put check arg in register r2 */
1067 user_mod.regs.gprs[2] = check;
1068 /* bad_return Return address is in r14 */
1069 user_mod.regs.gprs[14] = bad_return;
1070 /* minimum stack frame */
1071 sp = sp - 160;
1072 user_mod.regs.gprs[15] = sp;
1073 /* set program counter */
1074 user_mod.regs.psw.addr = shared64->invoke_gdbserver;
1075#else
1076 I_die_here: architecture missing in vgdb.c
1077#endif
1078 }
1079 else {
1080 assert(0);
1081 }
1082
sewardjeefeeb72011-05-10 11:01:07 +00001083 if (!setregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
sewardj3b290482011-05-06 21:02:55 +00001084 detach_from_all_threads(pid);
1085 return False;
1086 }
1087 /* Now that we have modified the registers, we set
1088 pid_of_save_regs to indicate that restore_and_detach
1089 must restore the registers in case of cleanup. */
1090 pid_of_save_regs = pid;
1091 pid_of_save_regs_continued = False;
1092
1093
1094 /* We PTRACE_CONT-inue pid.
1095 Either gdbserver will be invoked directly (if all
1096 threads are interruptible) or gdbserver will be
1097 called soon by the scheduler. In the first case,
1098 pid will stop on the break inserted above when
1099 gdbserver returns. In the 2nd case, the break will
1100 be encountered directly. */
1101 DEBUG(1, "PTRACE_CONT to invoke\n");
1102 res = ptrace (PTRACE_CONT, pid, NULL, NULL);
1103 if (res != 0) {
1104 ERROR(errno, "PTRACE_CONT\n");
1105 restore_and_detach(pid);
1106 return False;
1107 }
1108 pid_of_save_regs_continued = True;
sewardjb2572b52011-06-26 09:36:38 +00001109 /* Wait for SIGSTOP generated by m_gdbserver.c give_control_back_to_vgdb */
1110 stopped = waitstopped (pid, SIGSTOP,
sewardj3b290482011-05-06 21:02:55 +00001111 "waitpid status after PTRACE_CONT to invoke");
1112 if (stopped) {
1113 /* Here pid has properly stopped on the break. */
1114 pid_of_save_regs_continued = False;
1115 restore_and_detach(pid);
1116 return True;
1117 } else {
1118 /* Whatever kind of problem happened. We shutdown */
1119 shutting_down = True;
1120 return False;
1121 }
1122}
1123#endif
1124
1125static
1126void cleanup_restore_and_detach(void *v_pid)
1127{
1128 DEBUG(1, "cleanup_restore_and_detach dying: %d\n", dying);
1129#ifdef PTRACEINVOKER
1130 if (!dying)
1131 restore_and_detach(*(int*)v_pid);
1132#endif
1133}
1134
1135/* This function loops till shutting_down becomes true. In this loop,
1136 it verifies if valgrind process is reading the characters written
1137 by vgdb. The verification is done every max_invoke_ms ms. If
1138 valgrind is not reading characters, it will use invoke_gdbserver
1139 (if PTRACE_INVOKER is defined) to ensure that the gdbserver code is
1140 called soon by valgrind. */
1141static int max_invoke_ms = 100;
sewardj30b3eca2011-06-28 08:20:39 +00001142#define NEVER 99999999
1143static int cmd_time_out = NEVER;
sewardj3b290482011-05-06 21:02:55 +00001144static
1145void *invoke_gdbserver_in_valgrind(void *v_pid)
1146{
sewardj30b3eca2011-06-28 08:20:39 +00001147 struct timeval cmd_max_end_time;
1148 Bool cmd_started = False;
1149 struct timeval invoke_time;
1150
sewardj3b290482011-05-06 21:02:55 +00001151 int pid = *(int *)v_pid;
1152 int written_by_vgdb_before_sleep;
1153 int seen_by_valgrind_before_sleep;
1154
1155 int invoked_written = -1;
sewardj30b3eca2011-06-28 08:20:39 +00001156 unsigned int usecs;
sewardj3b290482011-05-06 21:02:55 +00001157
1158 pthread_cleanup_push(cleanup_restore_and_detach, v_pid);
1159
1160 while (!shutting_down) {
1161 written_by_vgdb_before_sleep = VS_written_by_vgdb;
1162 seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
1163 DEBUG(3,
1164 "written_by_vgdb_before_sleep %d "
1165 "seen_by_valgrind_before_sleep %d\n",
1166 written_by_vgdb_before_sleep,
1167 seen_by_valgrind_before_sleep);
sewardj30b3eca2011-06-28 08:20:39 +00001168 if (cmd_time_out != NEVER
1169 && !cmd_started
1170 && written_by_vgdb_before_sleep > seen_by_valgrind_before_sleep) {
1171 /* A command was started. Record the time at which it was started. */
1172 DEBUG(1, "IO for command started\n");
1173 gettimeofday(&cmd_max_end_time, NULL);
1174 cmd_max_end_time.tv_sec += cmd_time_out;
1175 cmd_started = True;
1176 }
1177 if (max_invoke_ms > 0) {
1178 usecs = 1000 * max_invoke_ms;
1179 gettimeofday(&invoke_time, NULL);
1180 invoke_time.tv_sec += max_invoke_ms / 1000;
1181 invoke_time.tv_usec += 1000 * (max_invoke_ms % 1000);
1182 invoke_time.tv_sec += invoke_time.tv_usec / (1000 * 1000);
1183 invoke_time.tv_usec = invoke_time.tv_usec % (1000 * 1000);
1184 } else {
1185 usecs = 0;
1186 }
1187 if (cmd_started) {
1188 // 0 usecs here means the thread just has to check gdbserver eats
1189 // the characters in <= cmd_time_out seconds.
1190 // We will just wait by 1 second max at a time.
1191 if (usecs == 0 || usecs > 1000 * 1000)
1192 usecs = 1000 * 1000;
1193 }
sewardj992d3cc2011-10-22 20:38:08 +00001194 usleep(usecs);
1195
sewardj30b3eca2011-06-28 08:20:39 +00001196 /* If nothing happened during our sleep, let's try to wake up valgrind
1197 or check for cmd time out. */
sewardj3b290482011-05-06 21:02:55 +00001198 if (written_by_vgdb_before_sleep == VS_written_by_vgdb
1199 && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
1200 && VS_written_by_vgdb > VS_seen_by_valgrind) {
sewardj30b3eca2011-06-28 08:20:39 +00001201 struct timeval now;
1202 gettimeofday(&now, NULL);
sewardj3b290482011-05-06 21:02:55 +00001203 DEBUG(2,
1204 "after sleep "
1205 "written_by_vgdb %d "
1206 "seen_by_valgrind %d "
1207 "invoked_written %d\n",
1208 VS_written_by_vgdb,
1209 VS_seen_by_valgrind,
1210 invoked_written);
1211 /* if the pid does not exist anymore, we better stop */
1212 if (kill(pid, 0) != 0)
1213 XERROR (errno,
1214 "invoke_gdbserver_in_valgrind: "
1215 "check for pid %d existence failed\n", pid);
sewardj30b3eca2011-06-28 08:20:39 +00001216 if (cmd_started) {
1217 if (timercmp (&now, &cmd_max_end_time, >))
1218 XERROR (0,
1219 "pid %d did not handle a command in %d seconds\n",
1220 pid, cmd_time_out);
sewardj3b290482011-05-06 21:02:55 +00001221 }
sewardj30b3eca2011-06-28 08:20:39 +00001222 if (max_invoke_ms > 0 && timercmp (&now, &invoke_time, >=)) {
1223 #if defined(PTRACEINVOKER)
1224 /* only need to wake up if the nr written has changed since
1225 last invoke. */
1226 if (invoked_written != written_by_vgdb_before_sleep) {
1227 if (invoke_gdbserver(pid)) {
1228 /* If invoke succesful, no need to invoke again
1229 for the same value of written_by_vgdb_before_sleep. */
1230 invoked_written = written_by_vgdb_before_sleep;
1231 }
1232 }
1233 #else
1234 DEBUG(2, "invoke_gdbserver via ptrace not (yet) implemented\n");
1235 #endif
1236 }
1237 } else {
1238 // Something happened => restart timer check.
1239 if (cmd_time_out != NEVER) {
1240 DEBUG(2, "some IO was done => restart command\n");
1241 cmd_started = False;
1242 }
sewardj3b290482011-05-06 21:02:55 +00001243 }
1244 }
1245 pthread_cleanup_pop(0);
1246 return NULL;
1247}
1248
1249static
1250int open_fifo (char* name, int flags, char* desc)
1251{
1252 int fd;
1253 DEBUG(1, "opening %s %s\n", name, desc);
1254 fd = open(name, flags);
1255 if (fd == -1)
1256 XERROR (errno, "error opening %s %s\n", name, desc);
1257
1258 DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
1259 return fd;
1260}
1261
1262/* acquire a lock on the first byte of the given fd. If not successful,
1263 exits with error.
1264 This allows to avoid having two vgdb speaking with the same Valgrind
1265 gdbserver as this causes serious headaches to the protocol. */
1266static
1267void acquire_lock (int fd, int valgrind_pid)
1268{
sewardj992d3cc2011-10-22 20:38:08 +00001269 struct flock fl;
1270 fl.l_type = F_WRLCK;
1271 fl.l_whence = SEEK_SET;
1272 fl.l_start = 0;
1273 fl.l_len = 1;
1274 if (fcntl(fd, F_SETLK, &fl) < 0) {
sewardj3b290482011-05-06 21:02:55 +00001275 if (errno == EAGAIN || errno == EACCES) {
1276 XERROR(errno,
1277 "Cannot acquire lock.\n"
1278 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
1279 VS_vgdb_pid,
1280 valgrind_pid);
1281 } else {
1282 XERROR(errno, "cannot acquire lock.\n");
1283 }
1284 }
1285
1286 /* Here, we have the lock. It will be released when fd will be closed. */
1287 /* We indicate our pid to Valgrind gdbserver */
1288 if (shared32 != NULL)
1289 shared32->vgdb_pid = getpid();
1290 else if (shared64 != NULL)
1291 shared64->vgdb_pid = getpid();
1292 else
1293 assert(0);
1294}
1295
1296#define PBUFSIZ 16384 /* keep in sync with server.h */
1297
1298/* read some characters from fd.
1299 Returns the nr of characters read, -1 if error.
1300 desc is a string used in tracing */
1301static
1302int read_buf (int fd, char* buf, char* desc)
1303{
1304 int nrread;
1305 DEBUG(2, "reading %s\n", desc);
1306 nrread = read(fd, buf, PBUFSIZ);
1307 if (nrread == -1) {
1308 ERROR (errno, "error reading %s\n", desc);
1309 return -1;
1310 }
1311 buf[nrread] = '\0';
1312 DEBUG(2, "read %s %s\n", desc, buf);
1313 return nrread;
1314}
1315
1316/* write size bytes from buf to fd.
1317 desc is a description of the action for which the write is done.
1318 If notify, then add size to the shared cntr indicating to the
1319 valgrind process that there is new data.
1320 Returns True if write is ok, False if there was a problem. */
1321static
1322Bool write_buf(int fd, char* buf, int size, char* desc, Bool notify)
1323{
1324 int nrwritten;
1325 int nrw;
1326 DEBUG(2, "writing %s len %d %s notify: %d\n", desc, size, buf, notify);
1327 nrwritten = 0;
1328 while (nrwritten < size) {
1329 nrw = write (fd, buf+nrwritten, size - nrwritten);
1330 if (nrw == -1) {
1331 ERROR(errno, "error write %s\n", desc);
1332 return False;
1333 }
1334 nrwritten = nrwritten + nrw;
1335 if (notify)
1336 add_written(nrw);
1337 }
1338 return True;
1339}
1340
1341typedef enum {
1342 FROM_GDB,
1343 TO_GDB,
1344 FROM_PID,
1345 TO_PID } ConnectionKind;
1346static const int NumConnectionKind = TO_PID+1;
1347static
1348char *ppConnectionKind (ConnectionKind con)
1349{
1350 switch (con) {
1351 case FROM_GDB: return "FROM_GDB";
1352 case TO_GDB: return "TO_GDB";
1353 case FROM_PID: return "FROM_PID";
1354 case TO_PID: return "TO_PID";
1355 default: return "invalid connection kind";
1356 }
1357}
1358
1359static char *shared_mem;
1360
sewardj992d3cc2011-10-22 20:38:08 +00001361static int from_gdb = 0; /* stdin by default, changed if --port is given. */
sewardj3b290482011-05-06 21:02:55 +00001362static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
1363/* Returns True in case read/write operations were done properly.
1364 Returns False in case of error.
1365 to_pid is the file descriptor to write to the process pid. */
1366static
1367Bool read_from_gdb_write_to_pid(int to_pid)
1368{
philippe1d76a802011-12-26 21:21:37 +00001369 char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +00001370 int nrread;
1371
1372 nrread = read_buf(from_gdb, buf, "from gdb on stdin");
1373 if (nrread <= 0) {
1374 if (nrread == 0)
1375 DEBUG(1, "read 0 bytes from gdb => assume exit\n");
1376 else
1377 DEBUG(1, "error reading bytes from gdb\n");
1378 close (from_gdb);
1379 shutting_down = True;
1380 return False;
1381 }
1382 return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
1383}
1384
sewardj992d3cc2011-10-22 20:38:08 +00001385static int to_gdb = 1; /* stdout by default, changed if --port is given. */
sewardj3b290482011-05-06 21:02:55 +00001386static char *to_gdb_from_pid; /* fifo name to read pid replies */
1387/* Returns True in case read/write operations were done properly.
1388 Returns False in case of error.
1389 from_pid is the file descriptor to read data from the process pid. */
1390static
1391Bool read_from_pid_write_to_gdb(int from_pid)
1392{
philippe1d76a802011-12-26 21:21:37 +00001393 char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +00001394 int nrread;
1395
1396 nrread = read_buf(from_pid, buf, "from pid");
1397 if (nrread <= 0) {
1398 if (nrread == 0)
1399 DEBUG(1, "read 0 bytes from pid => assume exit\n");
1400 else
1401 DEBUG(1, "error reading bytes from pid\n");
1402 close (from_pid);
1403 shutting_down = True;
1404 return False;
1405 }
1406 return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
1407}
1408
sewardj992d3cc2011-10-22 20:38:08 +00001409static
1410void wait_for_gdb_connect (int in_port)
1411{
1412 struct sockaddr_in addr;
1413
1414 int listen_gdb = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
1415 int gdb_connect;
1416
1417 if (-1 == listen_gdb) {
1418 XERROR(errno, "cannot create socket");
1419 }
1420
1421 memset(&addr, 0, sizeof(addr));
1422
1423 addr.sin_family = AF_INET;
1424 addr.sin_port = htons((unsigned short int)in_port);
1425 addr.sin_addr.s_addr = INADDR_ANY;
1426
1427 if (-1 == bind(listen_gdb,(struct sockaddr *)&addr, sizeof(addr))) {
1428 XERROR(errno, "bind failed");
1429 }
1430 fprintf(stderr, "listening on port %d ...", in_port);
1431 fflush(stderr);
1432 if (-1 == listen(listen_gdb, 1)) {
1433 XERROR(errno, "error listen failed");
1434 }
1435
1436 gdb_connect = accept(listen_gdb, NULL, NULL);
1437 if (gdb_connect < 0) {
1438 XERROR(errno, "accept failed");
1439 }
1440 fprintf(stderr, "connected.\n");
1441 fflush(stderr);
1442 close(listen_gdb);
1443 from_gdb = gdb_connect;
1444 to_gdb = gdb_connect;
1445}
1446
sewardj3b290482011-05-06 21:02:55 +00001447/* prepares the FIFOs filenames, map the shared memory. */
1448static
1449void prepare_fifos_and_shared_mem(int pid)
1450{
florianab8630f2011-09-29 21:20:49 +00001451 const HChar *user, *host;
1452 unsigned len;
1453
1454 user = getenv("LOGNAME");
1455 if (user == NULL) user = getenv("USER");
1456 if (user == NULL) user = "???";
1457
1458 host = getenv("HOST");
1459 if (host == NULL) host = getenv("HOSTNAME");
1460 if (host == NULL) host = "???";
1461
1462 len = strlen(vgdb_prefix) + strlen(user) + strlen(host) + 40;
1463 from_gdb_to_pid = vmalloc (len);
1464 to_gdb_from_pid = vmalloc (len);
1465 shared_mem = vmalloc (len);
sewardj3b290482011-05-06 21:02:55 +00001466 /* below 3 lines must match the equivalent in remote-utils.c */
florianab8630f2011-09-29 21:20:49 +00001467 sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d-by-%s-on-%s", vgdb_prefix,
1468 pid, user, host);
1469 sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d-by-%s-on-%s", vgdb_prefix,
1470 pid, user, host);
1471 sprintf(shared_mem, "%s-shared-mem-vgdb-%d-by-%s-on-%s", vgdb_prefix,
1472 pid, user, host);
sewardj3b290482011-05-06 21:02:55 +00001473 DEBUG (1, "vgdb: using %s %s %s\n",
1474 from_gdb_to_pid, to_gdb_from_pid, shared_mem);
1475
1476 map_vgdbshared(shared_mem);
1477}
1478
1479/* Convert hex digit A to a number. */
1480
1481static int
1482fromhex (int a)
1483{
1484 if (a >= '0' && a <= '9')
1485 return a - '0';
1486 else if (a >= 'a' && a <= 'f')
1487 return a - 'a' + 10;
1488 else
1489 XERROR(0, "Reply contains invalid hex digit %c\n", a);
1490 return 0;
1491}
1492
1493/* Returns next char from fd. -1 if error, -2 if EOF.
1494 NB: must always call it with the same fd */
1495static int
1496readchar (int fd)
1497{
philippe1d76a802011-12-26 21:21:37 +00001498 static unsigned char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +00001499 static int bufcnt = 0;
1500 static unsigned char *bufp;
1501
1502 if (bufcnt-- > 0)
1503 return *bufp++;
1504
philippe1d76a802011-12-26 21:21:37 +00001505 bufcnt = read_buf (fd, buf, "static buf readchar");
sewardj3b290482011-05-06 21:02:55 +00001506
1507 if (bufcnt <= 0) {
1508 if (bufcnt == 0) {
1509 fprintf (stderr, "readchar: Got EOF\n");
1510 return -2;
1511 } else {
1512 ERROR (errno, "readchar\n");
1513 return -1;
1514 }
1515 }
1516
1517 bufp = buf;
1518 bufcnt--;
1519 return *bufp++;
1520}
1521
1522/* Read a packet from fromfd, with error checking,
1523 and store it in BUF.
1524 Returns length of packet, or -1 if error or -2 if EOF.
1525 Writes ack on ackfd */
1526
1527static int
1528getpkt (char *buf, int fromfd, int ackfd)
1529{
1530 char *bp;
1531 unsigned char csum, c1, c2;
1532 int c;
1533
1534 while (1) {
1535 csum = 0;
1536
1537 while (1) {
1538 c = readchar (fromfd);
1539 if (c == '$')
1540 break;
1541 DEBUG(2, "[getpkt: discarding char '%c']\n", c);
1542 if (c < 0)
1543 return c;
1544 }
1545
1546 bp = buf;
1547 while (1) {
1548 c = readchar (fromfd);
1549 if (c < 0)
1550 return c;
1551 if (c == '#')
1552 break;
1553 if (c == '*') {
1554 int repeat;
1555 int r;
1556 int prev;
1557 prev = *(bp-1);
1558 csum += c;
1559 repeat = readchar (fromfd);
1560 csum += repeat;
1561 for (r = 0; r < repeat - 29; r ++)
1562 *bp++ = prev;
1563 } else {
1564 *bp++ = c;
1565 csum += c;
1566 }
1567 }
1568 *bp = 0;
1569
1570 c1 = fromhex (readchar (fromfd));
1571 c2 = fromhex (readchar (fromfd));
1572
1573 if (csum == (c1 << 4) + c2)
1574 break;
1575
1576 fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1577 (c1 << 4) + c2, csum, buf);
1578 if (write (ackfd, "-", 1) != 1)
1579 ERROR(0, "error when writing - (nack)\n");
1580 else
1581 add_written(1);
1582 }
1583
1584 DEBUG(2, "getpkt (\"%s\"); [sending ack] \n", buf);
1585 if (write (ackfd, "+", 1) != 1)
1586 ERROR(0, "error when writing + (ack)\n");
1587 else
1588 add_written(1);
1589 return bp - buf;
1590}
1591
1592static int sigint = 0;
1593static int sigterm = 0;
1594static int sigpipe = 0;
1595static int sighup = 0;
1596static int sigusr1 = 0;
1597static int sigalrm = 0;
1598static int sigusr1_fd = -1;
1599static pthread_t invoke_gdbserver_in_valgrind_thread;
1600
1601static
1602void received_signal (int signum)
1603{
1604 if (signum == SIGINT)
1605 sigint++;
1606 else if (signum == SIGUSR1) {
1607 sigusr1++;
1608 if (sigusr1_fd >= 0) {
1609 char control_c = '\003';
1610 write_buf(sigusr1_fd, &control_c, 1,
1611 "write \\003 on SIGUSR1", /* notify */ True);
1612 }
1613 }
1614 else if (signum == SIGTERM) {
1615 shutting_down = True;
1616 sigterm++;
1617 } else if (signum == SIGHUP) {
1618 shutting_down = True;
1619 sighup++;
1620 } else if (signum == SIGPIPE) {
1621 sigpipe++;
1622 } else if (signum == SIGALRM) {
1623 sigalrm++;
sewardj992d3cc2011-10-22 20:38:08 +00001624#if defined(VGPV_arm_linux_android)
1625 /* Android has no pthread_cancel. As it also does not have
1626 PTRACE_INVOKER, there is no need for cleanup action.
1627 So, we just do nothing. */
1628 DEBUG(1, "sigalrm received, no action on android\n");
1629#else
sewardj3b290482011-05-06 21:02:55 +00001630 /* Note: we cannot directly invoke restore_and_detach : this must
1631 be done by the thread that has attached.
1632 We have in this thread pushed a cleanup handler that will
1633 cleanup what is needed. */
sewardj992d3cc2011-10-22 20:38:08 +00001634 DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
sewardj3b290482011-05-06 21:02:55 +00001635 pthread_cancel(invoke_gdbserver_in_valgrind_thread);
sewardj992d3cc2011-10-22 20:38:08 +00001636#endif
sewardj3b290482011-05-06 21:02:55 +00001637 } else {
1638 ERROR(0, "unexpected signal %d\n", signum);
1639 }
1640}
1641
1642/* install the signal handlers allowing e.g. vgdb to cleanup in
1643 case of termination. */
1644static
1645void install_handlers(void)
1646{
1647 struct sigaction action, oldaction;
1648
1649 action.sa_handler = received_signal;
1650 sigemptyset (&action.sa_mask);
1651 action.sa_flags = 0;
1652
1653 /* SIGINT: when user types C-c in gdb, this sends
1654 a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
1655 The later is enough to wakeup the valgrind process. */
1656 if (sigaction (SIGINT, &action, &oldaction) != 0)
1657 XERROR (errno, "vgdb error sigaction SIGINT\n");
1658 /* We might do something more intelligent than just
1659 reporting this SIGINT E.g. behave similarly to the gdb: two
1660 control-C without feedback from the debugged process would
1661 mean to stop debugging it. */
1662
1663 /* SIGUSR1: this is used to facilitate automatic testing. When
1664 vgdb receives this signal, it will simulate the user typing C-c. */
1665 if (sigaction (SIGUSR1, &action, &oldaction) != 0)
1666 XERROR (errno, "vgdb error sigaction SIGUSR1\n");
1667
1668
1669 /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
1670 when detaching or similar. A clean shutdown will be done as both
1671 the read and write side will detect an end of file. */
1672 if (sigaction (SIGTERM, &action, &oldaction) != 0)
1673 XERROR (errno, "vgdb error sigaction SIGTERM\n");
1674
1675 /* SIGPIPE: can receive this signal when gdb detaches or kill the
1676 process debugged: gdb will close its pipes to vgdb. vgdb
1677 must resist to this signal to allow a clean shutdown. */
1678 if (sigaction (SIGPIPE, &action, &oldaction) != 0)
1679 XERROR (errno, "vgdb error sigaction SIGPIPE\n");
1680
1681 /* SIGALRM: in case invoke thread is blocked, alarm is used
1682 to cleanup. */
1683 if (sigaction (SIGALRM, &action, &oldaction) != 0)
1684 XERROR (errno, "vgdb error sigaction SIGALRM\n");
1685}
1686
1687/* close the FIFOs provided connections, terminate the invoker thread. */
1688static
1689void close_connection(int to_pid, int from_pid)
1690{
1691 DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
1692 sigint, sigterm, sighup, sigpipe);
1693 /* Note that we do not forward sigterm to the valgrind process:
1694 a sigterm signal is (probably) received from gdb if the user wants to
1695 kill the debugged process. The kill instruction has been given to
1696 the valgrind process, which should execute a clean exit. */
1697
1698 /* We first close the connection to pid. The pid will then
1699 terminates its gdbserver work. We keep the from pid
1700 fifo opened till the invoker thread is finished.
1701 This allows the gdbserver to finish sending its last reply. */
1702 if (close(to_pid) != 0)
1703 ERROR(errno, "close to_pid\n");
1704
1705 /* if there is a task that was busy trying to wake up valgrind
1706 process, we wait for it to be terminated otherwise threads
1707 in the valgrind process can stay stopped if vgdb main
1708 exits before the invoke thread had time to detach from
1709 all valgrind threads. */
sewardj30b3eca2011-06-28 08:20:39 +00001710 if (max_invoke_ms > 0 || cmd_time_out != NEVER) {
sewardj3b290482011-05-06 21:02:55 +00001711 int join;
1712
1713 /* It is surprisingly complex to properly shutdown or exit the
1714 valgrind process in which gdbserver has been invoked through
1715 ptrace. In the normal case (gdb detaches from the process,
1716 or process is continued), the valgrind process will reach the
1717 breakpoint place. Using ptrace, vgdb will ensure the
1718 previous activity of the process is resumed (e.g. restart a
1719 blocking system call). The special case is when gdb asks the
1720 valgrind process to exit (using either the "kill" command or
1721 "monitor exit"). In such a case, the valgrind process will
1722 call exit. But a ptraced process will be blocked in exit,
1723 waiting for the ptracing process to detach or die. vgdb
1724 cannot detach unconditionally as otherwise, in the normal
sewardjb2572b52011-06-26 09:36:38 +00001725 case, the valgrind process would stop abnormally with SIGSTOP
sewardj3b290482011-05-06 21:02:55 +00001726 (as vgdb would not be there to catch it). vgdb can also not
1727 die unconditionally otherwise again, similar problem. So, we
1728 assume that most of the time, we arrive here in the normal
1729 case, and so, the breakpoint has been encountered by the
1730 valgrind process, so the invoker thread will exit and the
1731 join will succeed. For the "kill" case, we cause an alarm
1732 signal to be sent after a few seconds. This means that in the
1733 normal case, the gdbserver code in valgrind process must have
1734 returned the control in less than the alarm nr of seconds,
sewardjb2572b52011-06-26 09:36:38 +00001735 otherwise, valgrind will stop abnormally with SIGSTOP. */
sewardj3b290482011-05-06 21:02:55 +00001736 (void) alarm (3);
1737
1738 DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
1739 join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
1740 if (join != 0)
1741 XERROR
1742 (join,
1743 "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
1744 }
1745 if (close(from_pid) != 0)
1746 ERROR(errno, "close from_pid\n");
1747}
1748
1749/* Relay data between gdb and Valgrind gdbserver, till EOF or an
1750 error is encountered. */
1751static
1752void gdb_relay (int pid)
1753{
1754 int from_pid = -1; /* fd to read from pid */
1755 int to_pid = -1; /* fd to write to pid */
1756
1757 int shutdown_loop = 0;
1758 fprintf (stderr, "relaying data between gdb and process %d\n", pid);
1759 fflush (stderr);
1760
1761 if (max_invoke_ms > 0)
1762 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1763 invoke_gdbserver_in_valgrind, (void *) &pid);
1764 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1765 acquire_lock (shared_mem_fd, pid);
1766
1767 from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK,
1768 "read mode from pid");
1769
1770 sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1771
1772 while (1) {
1773 ConnectionKind ck;
1774 int ret;
1775 struct pollfd pollfds[NumConnectionKind];
1776
1777 /* watch data written by gdb, watch POLLERR on both gdb fd */
1778 pollfds[FROM_GDB].fd = from_gdb;
1779 pollfds[FROM_GDB].events = POLLIN;
1780 pollfds[FROM_GDB].revents = 0;
1781 pollfds[TO_GDB].fd = to_gdb;
1782 pollfds[TO_GDB].events = 0;
1783 pollfds[TO_GDB].revents = 0;
1784
1785 /* watch data written by pid, watch POLLERR on both pid fd */
1786 pollfds[FROM_PID].fd = from_pid;
1787 pollfds[FROM_PID].events = POLLIN;
1788 pollfds[FROM_PID].revents = 0;
1789 pollfds[TO_PID].fd = to_pid;
1790 pollfds[TO_PID].events = 0;
1791 pollfds[TO_PID].revents = 0;
1792
1793 ret = poll(pollfds,
1794 NumConnectionKind,
1795 (shutting_down ?
1796 1 /* one second */
1797 : -1 /* infinite */));
1798 DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1799
1800 /* check for unexpected error */
1801 if (ret <= 0 && errno != EINTR) {
1802 ERROR (errno, "unexpected poll ret %d\n", ret);
1803 shutting_down = True;
1804 break;
1805 }
1806
1807 /* check for data to read */
1808 for (ck = 0; ck < NumConnectionKind; ck ++) {
1809 if (pollfds[ck].revents & POLLIN) {
1810 switch (ck) {
1811 case FROM_GDB:
1812 if (!read_from_gdb_write_to_pid(to_pid))
1813 shutting_down = True;
1814 break;
philippe1d76a802011-12-26 21:21:37 +00001815 case FROM_PID:
1816 if (!read_from_pid_write_to_gdb(from_pid))
1817 shutting_down = True;
1818 break;
sewardj3b290482011-05-06 21:02:55 +00001819 default: XERROR(0, "unexpected POLLIN on %s\n",
1820 ppConnectionKind(ck));
1821 }
1822 }
1823 }
1824
1825 /* check for an fd being in error condition */
1826 for (ck = 0; ck < NumConnectionKind; ck ++) {
1827 if (pollfds[ck].revents & POLLERR) {
1828 DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1829 ppConnectionKind(ck), pollfds[ck].fd);
1830 valgrind_dying();
1831 shutting_down = True;
1832 }
1833 if (pollfds[ck].revents & POLLHUP) {
1834 DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1835 ppConnectionKind(ck), pollfds[ck].fd);
1836 valgrind_dying();
1837 shutting_down = True;
1838 }
1839 if (pollfds[ck].revents & POLLNVAL) {
1840 DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1841 ppConnectionKind(ck), pollfds[ck].fd);
1842 valgrind_dying();
1843 shutting_down = True;
1844 }
1845 }
1846
1847 if (shutting_down) {
1848 /* we let some time to the final packets to be transferred */
1849 shutdown_loop++;
1850 if (shutdown_loop > 3)
1851 break;
1852 }
1853 }
1854 close_connection(to_pid, from_pid);
1855}
1856
1857static int packet_len_for_command(char *cmd)
1858{
1859 /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc */
1860 return 7+ 2*strlen(cmd) +3 + 1;
1861}
1862
1863/* hyper-minimal protocol implementation that
1864 sends the provided commands (using qRcmd packets)
1865 and read and display their replies. */
1866static
1867void standalone_send_commands(int pid,
1868 int last_command,
1869 char *commands[] )
1870{
1871 int from_pid = -1; /* fd to read from pid */
1872 int to_pid = -1; /* fd to write to pid */
1873
1874 int i;
1875 int hi;
1876 unsigned char hex[3];
1877 unsigned char cksum;
1878 unsigned char *hexcommand;
philippe1d76a802011-12-26 21:21:37 +00001879 unsigned char buf[PBUFSIZ+1]; // +1 for trailing \0
sewardj3b290482011-05-06 21:02:55 +00001880 int buflen;
1881 int nc;
1882
1883
sewardj30b3eca2011-06-28 08:20:39 +00001884 if (max_invoke_ms > 0 || cmd_time_out != NEVER)
sewardj3b290482011-05-06 21:02:55 +00001885 pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL,
1886 invoke_gdbserver_in_valgrind, (void *) &pid);
1887
1888 to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1889 acquire_lock (shared_mem_fd, pid);
1890
1891 /* first send a C-c \003 to pid, so that it wakes up the process
1892 After that, we can open the fifo from the pid in read mode
1893 We then start to wait for packets (normally first a resume reply)
1894 At that point, we send our command and expect replies */
1895 buf[0] = '\003';
1896 write_buf(to_pid, buf, 1, "write \\003 to wake up", /* notify */ True);
1897 from_pid = open_fifo(to_gdb_from_pid, O_RDONLY,
1898 "read cmd result from pid");
1899
1900 for (nc = 0; nc <= last_command; nc++) {
1901 fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
1902 fflush (stderr);
1903
1904 /* prepare hexcommand $qRcmd,xxxx....................xx#cc */
1905 hexcommand = vmalloc (packet_len_for_command(commands[nc]));
1906 hexcommand[0] = 0;
1907 strcat (hexcommand, "$qRcmd,");
1908 for (i = 0; i < strlen(commands[nc]); i++) {
1909 sprintf(hex, "%02x", commands[nc][i]);
1910 strcat (hexcommand, hex);
1911 }
1912 /* checksum (but without the $) */
1913 cksum = 0;
1914 for (hi = 1; hi < strlen(hexcommand); hi++)
1915 cksum+=hexcommand[hi];
1916 strcat(hexcommand, "#");
1917 sprintf(hex, "%02x", cksum);
1918 strcat(hexcommand, hex);
1919 write_buf(to_pid, hexcommand, strlen(hexcommand),
1920 "writing hex command to pid", /* notify */ True);
1921
1922 /* we exit of the below loop explicitely when the command has
1923 been handled or because a signal handler will set
1924 shutting_down. */
1925 while (!shutting_down) {
1926 buflen = getpkt(buf, from_pid, to_pid);
1927 if (buflen < 0) {
1928 ERROR (0, "error reading packet\n");
1929 if (buflen == -2)
1930 valgrind_dying();
1931 break;
1932 }
1933 if (strlen(buf) == 0) {
1934 DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1935 break;
1936 }
1937 if (strcmp(buf, "OK") == 0) {
1938 DEBUG(1, "OK packet rcvd\n");
1939 break;
1940 }
1941 if (buf[0] == 'E') {
1942 DEBUG(0,
1943 "E NN error packet rcvd: %s (unknown monitor command?)\n",
1944 buf);
1945 break;
1946 }
1947 if (buf[0] == 'W') {
1948 DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1949 break;
1950 }
1951 if (buf[0] == 'T') {
1952 DEBUG(1, "T resume reply packet received: %s\n", buf);
1953 continue;
1954 }
1955
1956 /* must be here an O packet with hex encoded string reply
1957 => decode and print it */
1958 if (buf[0] != 'O') {
1959 DEBUG(0, "expecting O packet, received: %s\n", buf);
1960 continue;
1961 }
1962 {
1963 char buf_print[buflen/2 + 1];
1964 for (i = 1; i < buflen; i = i + 2)
1965 buf_print[i/2] = (fromhex(*(buf+i)) << 4)
1966 + fromhex(*(buf+i+1));
1967 buf_print[buflen/2] = 0;
1968 printf("%s", buf_print);
1969 fflush(stdout);
1970 }
1971 }
1972 free (hexcommand);
1973 }
1974 shutting_down = True;
1975
1976 close_connection(to_pid, from_pid);
1977}
1978
1979/* report to user the existence of a vgdb-able valgrind process
1980 with given pid */
1981static
sewardj30b3eca2011-06-28 08:20:39 +00001982void report_pid (int pid, Bool on_stdout)
sewardj3b290482011-05-06 21:02:55 +00001983{
1984 char cmdline_file[100];
1985 char cmdline[1000];
1986 int fd;
1987 int i, sz;
1988
1989 sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1990 fd = open (cmdline_file, O_RDONLY);
1991 if (fd == -1) {
1992 DEBUG(1, "error opening cmdline file %s %s\n",
1993 cmdline_file, strerror(errno));
1994 sprintf(cmdline, "(could not obtain process command line)");
1995 } else {
1996 sz = read(fd, cmdline, 1000);
1997 for (i = 0; i < sz; i++)
1998 if (cmdline[i] == 0)
1999 cmdline[i] = ' ';
2000 cmdline[sz] = 0;
sewardjd8c12f12011-05-11 22:54:57 +00002001 close (fd);
sewardj3b290482011-05-06 21:02:55 +00002002 }
sewardj30b3eca2011-06-28 08:20:39 +00002003 fprintf((on_stdout ? stdout : stderr), "use --pid=%d for %s\n", pid, cmdline);
2004 fflush((on_stdout ? stdout : stderr));
sewardj3b290482011-05-06 21:02:55 +00002005}
2006
sewardj30b3eca2011-06-28 08:20:39 +00002007/* Possibly produces additional usage information documenting the
sewardj3b290482011-05-06 21:02:55 +00002008 ptrace restrictions. */
2009static
sewardj30b3eca2011-06-28 08:20:39 +00002010void ptrace_restrictions_msg(void)
sewardj3b290482011-05-06 21:02:55 +00002011{
2012# ifdef PR_SET_PTRACER
2013 char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
2014 int fd = -1;
2015 char ptrace_scope = 'X';
2016 fd = open (ptrace_scope_setting_file, O_RDONLY, 0);
2017 if (fd >= 0 && (read (fd, &ptrace_scope, 1) == 1) && (ptrace_scope != '0')) {
2018 fprintf (stderr,
2019 "Note: your kernel restricts ptrace invoker using %s\n"
2020 "vgdb will only be able to attach to a Valgrind process\n"
2021 "blocked in a system call *after* an initial successful attach\n",
2022 ptrace_scope_setting_file);
2023 } else if (ptrace_scope == 'X') {
sewardjd142f992011-05-17 17:15:07 +00002024 DEBUG (1,
2025 "PR_SET_PTRACER defined"
2026 " but could not determine ptrace scope from %s\n",
2027 ptrace_scope_setting_file);
sewardj3b290482011-05-06 21:02:55 +00002028 }
2029 if (fd >= 0)
2030 close (fd);
2031# endif
2032
2033# ifndef PTRACEINVOKER
2034 fprintf(stderr,
2035 "Note: ptrace invoker not implemented\n"
2036 "For more info: read user manual section"
2037 " 'Limitations of the Valgrind gdbserver'\n");
2038# endif
2039}
2040
2041static
2042void usage(void)
2043{
2044 fprintf(stderr,
2045"Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
2046"vgdb (valgrind gdb) has two usages\n"
2047" 1. standalone to send monitor commands to a Valgrind gdbserver.\n"
2048" The OPTION(s) must be followed by the command to send\n"
2049" To send more than one command, separate the commands with -c\n"
2050" 2. relay application between gdb and a Valgrind gdbserver.\n"
2051" Only OPTION(s) can be given.\n"
2052"\n"
2053" OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
sewardj30b3eca2011-06-28 08:20:39 +00002054" [--wait=<number>] [--max-invoke-ms=<number>]\n"
sewardj992d3cc2011-10-22 20:38:08 +00002055" [--port=<portnr>\n"
sewardj30b3eca2011-06-28 08:20:39 +00002056" [--cmd-time-out=<number>] [-l] [-D] [-d]\n"
2057" \n"
sewardj3b290482011-05-06 21:02:55 +00002058" --pid arg must be given if multiple Valgrind gdbservers are found.\n"
2059" --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
2060" if you want to change the default prefix for the FIFOs communication\n"
2061" between the Valgrind gdbserver and vgdb.\n"
sewardj30b3eca2011-06-28 08:20:39 +00002062" --wait (default 0) tells vgdb to check during the specified number\n"
sewardj3b290482011-05-06 21:02:55 +00002063" of seconds if a Valgrind gdbserver can be found.\n"
sewardj30b3eca2011-06-28 08:20:39 +00002064" --max-invoke-ms (default 100) gives the nr of milli-seconds after which vgdb\n"
2065" will force the invocation of the Valgrind gdbserver (if the Valgrind\n"
2066" process is blocked in a system call).\n"
sewardj992d3cc2011-10-22 20:38:08 +00002067" --port instructs vgdb to listen for gdb on the specified port nr.\n"
sewardj30b3eca2011-06-28 08:20:39 +00002068" --cmd-time-out (default 99999999) tells vgdb to exit if the found Valgrind\n"
2069" gdbserver has not processed a command after number seconds\n"
sewardjd142f992011-05-17 17:15:07 +00002070" -l arg tells to show the list of running Valgrind gdbserver and then exit.\n"
sewardj30b3eca2011-06-28 08:20:39 +00002071" -D arg tells to show shared mem status and then exit.\n"
2072" -d arg tells to show debug info. Multiple -d args for more debug info\n"
sewardjd142f992011-05-17 17:15:07 +00002073"\n"
2074" -h --help shows this message\n"
2075" To get help from the Valgrind gdbserver, use vgdb help\n"
sewardj3b290482011-05-06 21:02:55 +00002076"\n"
2077 );
sewardj30b3eca2011-06-28 08:20:39 +00002078 ptrace_restrictions_msg();
sewardj3b290482011-05-06 21:02:55 +00002079}
2080
sewardj30b3eca2011-06-28 08:20:39 +00002081/* If show_list, outputs on stdout the list of Valgrind processes with gdbserver activated.
sewardjd142f992011-05-17 17:15:07 +00002082 and then exits.
2083
2084 else if arg_pid == -1, waits maximum check_trials seconds to discover
sewardj3b290482011-05-06 21:02:55 +00002085 a valgrind pid appearing.
sewardjd142f992011-05-17 17:15:07 +00002086
sewardj3b290482011-05-06 21:02:55 +00002087 Otherwise verify arg_pid is valid and corresponds to a Valgrind process
2088 with gdbserver activated.
2089
2090 Returns the pid to work with
2091 or exits in case of error (e.g. no pid found corresponding to arg_pid */
2092
2093static
sewardjd142f992011-05-17 17:15:07 +00002094int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
sewardj3b290482011-05-06 21:02:55 +00002095{
2096 int i;
2097 int pid = -1;
2098
2099 if (arg_pid == 0 || arg_pid < -1) {
2100 fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
2101 exit (1);
2102 } else {
2103 /* search for a matching named fifo.
2104 If we have been given a pid, we will check that the matching FIFO is
2105 there (or wait the nr of check_trials for this to appear).
2106 If no pid has been given, then if we find only one FIFO,
2107 we will use this to build the pid to use.
2108 If we find multiple processes with valid FIFO, we report them and will
2109 exit with an error. */
2110 DIR *vgdb_dir;
2111 char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
2112 struct dirent *f;
2113 int is;
2114 int nr_valid_pid = 0;
2115 const char *suffix = "-from-vgdb-to-"; /* followed by pid */
2116 char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
2117
2118 strcpy (vgdb_format, vgdb_prefix);
2119 strcat (vgdb_format, suffix);
2120
2121 strcpy (vgdb_dir_name, vgdb_prefix);
2122
2123 for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
2124 if (vgdb_dir_name[is] == '/') {
2125 vgdb_dir_name[is+1] = '\0';
2126 break;
2127 }
2128 if (strlen(vgdb_dir_name) == 0)
2129 strcpy (vgdb_dir_name, "./");
2130
2131 DEBUG(1, "searching pid in directory %s format %s\n",
2132 vgdb_dir_name, vgdb_format);
2133
2134 /* try to find FIFOs with valid pid.
2135 On exit of the loop, pid is set to:
sewardjd142f992011-05-17 17:15:07 +00002136 the last pid found if show_list (or -1 if no process was listed)
sewardj3b290482011-05-06 21:02:55 +00002137 -1 if no FIFOs matching a running process is found
2138 -2 if multiple FIFOs of running processes are found
2139 otherwise it is set to the (only) pid found that can be debugged
2140 */
2141 for (i = 0; i < check_trials; i++) {
2142 DEBUG(1, "check_trial %d \n", i);
2143 if (i > 0)
2144 /* wait one second before checking again */
2145 sleep(1);
2146
2147 vgdb_dir = opendir (vgdb_dir_name);
2148 if (vgdb_dir == NULL)
2149 XERROR (errno,
2150 "vgdb error: opening directory %s searching vgdb fifo\n",
2151 vgdb_dir_name);
2152
2153 errno = 0; /* avoid complain if vgdb_dir is empty */
2154 while ((f = readdir (vgdb_dir))) {
2155 struct stat st;
philippebb4827b2012-04-06 11:51:04 +00002156 char pathname[strlen(vgdb_dir_name) + strlen(f->d_name) + 1];
sewardj3b290482011-05-06 21:02:55 +00002157 char *wrongpid;
2158 int newpid;
2159
2160 strcpy (pathname, vgdb_dir_name);
2161 strcat (pathname, f->d_name);
philippebb4827b2012-04-06 11:51:04 +00002162 DEBUG(3, "checking pathname is FIFO %s\n", pathname);
sewardj3b290482011-05-06 21:02:55 +00002163 if (stat (pathname, &st) != 0) {
2164 if (debuglevel >= 3)
2165 ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n",
2166 pathname);
2167 } else if (S_ISFIFO (st.st_mode)) {
philippebb4827b2012-04-06 11:51:04 +00002168 DEBUG(3, "trying FIFO %s\n", pathname);
sewardj3b290482011-05-06 21:02:55 +00002169 if (strncmp (pathname, vgdb_format,
2170 strlen (vgdb_format)) == 0) {
2171 newpid = strtol(pathname + strlen (vgdb_format),
2172 &wrongpid, 10);
florianab8630f2011-09-29 21:20:49 +00002173 if (*wrongpid == '-' && newpid > 0
sewardj3b290482011-05-06 21:02:55 +00002174 && kill (newpid, 0) == 0) {
2175 nr_valid_pid++;
sewardjd142f992011-05-17 17:15:07 +00002176 if (show_list) {
sewardj30b3eca2011-06-28 08:20:39 +00002177 report_pid (newpid, /*on_stdout*/ True);
sewardjd142f992011-05-17 17:15:07 +00002178 pid = newpid;
2179 } else if (arg_pid != -1) {
sewardj3b290482011-05-06 21:02:55 +00002180 if (arg_pid == newpid) {
2181 pid = newpid;
2182 }
2183 } else if (nr_valid_pid > 1) {
2184 if (nr_valid_pid == 2) {
2185 fprintf
2186 (stderr,
2187 "no --pid= arg given"
2188 " and multiple valgrind pids found:\n");
sewardj30b3eca2011-06-28 08:20:39 +00002189 report_pid (pid, /*on_stdout*/ False);
sewardj3b290482011-05-06 21:02:55 +00002190 }
2191 pid = -2;
sewardj30b3eca2011-06-28 08:20:39 +00002192 report_pid (newpid, /*on_stdout*/ False);
sewardj3b290482011-05-06 21:02:55 +00002193 } else {
2194 pid = newpid;
2195 }
2196 }
2197 }
2198 }
2199 errno = 0; /* avoid complain if at the end of vgdb_dir */
2200 }
2201 if (f == NULL && errno != 0)
2202 XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n",
2203 vgdb_dir_name);
2204
2205 closedir (vgdb_dir);
2206 if (pid != -1)
2207 break;
2208 }
2209
2210 free (vgdb_dir_name);
2211 free (vgdb_format);
2212 }
sewardjd142f992011-05-17 17:15:07 +00002213
2214 if (show_list) {
2215 exit (1);
2216 } else if (pid == -1) {
sewardj3b290482011-05-06 21:02:55 +00002217 if (arg_pid == -1)
2218 fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
2219 else
2220 fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n",
2221 arg_pid);
2222 exit (1);
2223 }
2224 else if (pid == -2) {
2225 /* no arg_pid given, multiple FIFOs found */
2226 exit (1);
2227 }
2228 else {
2229 return pid;
2230 }
2231}
2232
2233/* return true if the numeric value of an option of the
2234 form --xxxxxxxxx=<number> could properly be extracted
2235 from arg. If True is returned, *value contains the
2236 extracted value.*/
2237static
2238Bool numeric_val(char* arg, int *value)
2239{
2240 const char *eq_pos = strchr(arg, '=');
2241 char *wrong;
sewardj30b3eca2011-06-28 08:20:39 +00002242 long long int long_value;
sewardj3b290482011-05-06 21:02:55 +00002243
2244 if (eq_pos == NULL)
2245 return False;
2246
sewardj30b3eca2011-06-28 08:20:39 +00002247 long_value = strtoll(eq_pos+1, &wrong, 10);
2248 if (long_value < 0 || long_value > INT_MAX)
2249 return False;
sewardj3b290482011-05-06 21:02:55 +00002250 if (*wrong)
2251 return False;
2252
sewardj30b3eca2011-06-28 08:20:39 +00002253 *value = (int) long_value;
sewardj3b290482011-05-06 21:02:55 +00002254 return True;
2255}
2256
2257/* true if arg matches the provided option */
2258static
2259Bool is_opt(char* arg, char *option)
2260{
2261 int option_len = strlen(option);
2262 if (option[option_len-1] == '=')
2263 return (0 == strncmp(option, arg, option_len));
2264 else
2265 return (0 == strcmp(option, arg));
2266}
2267
2268/* Parse command lines options. If error(s), exits.
2269 Otherwise returns the options in *p_... args.
2270 commands must be big enough for the commands extracted from argv.
2271 On return, *p_last_command gives the position in commands where
2272 the last command has been allocated (using vmalloc). */
2273static
2274void parse_options(int argc, char** argv,
2275 Bool *p_show_shared_mem,
sewardjd142f992011-05-17 17:15:07 +00002276 Bool *p_show_list,
sewardj3b290482011-05-06 21:02:55 +00002277 int *p_arg_pid,
2278 int *p_check_trials,
sewardj992d3cc2011-10-22 20:38:08 +00002279 int *p_port,
sewardj3b290482011-05-06 21:02:55 +00002280 int *p_last_command,
2281 char *commands[])
2282{
2283 Bool show_shared_mem = False;
sewardjd142f992011-05-17 17:15:07 +00002284 Bool show_list = False;
sewardj3b290482011-05-06 21:02:55 +00002285 int arg_pid = -1;
2286 int check_trials = 1;
2287 int last_command = -1;
sewardj992d3cc2011-10-22 20:38:08 +00002288 int int_port = 0;
sewardj3b290482011-05-06 21:02:55 +00002289
2290 int i;
2291 int arg_errors = 0;
2292
2293 for (i = 1; i < argc; i++) {
2294 if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2295 usage();
2296 exit(0);
2297 } else if (is_opt(argv[i], "-d")) {
2298 debuglevel++;
2299 } else if (is_opt(argv[i], "-D")) {
2300 show_shared_mem = True;
sewardjd142f992011-05-17 17:15:07 +00002301 } else if (is_opt(argv[i], "-l")) {
2302 show_list = True;
sewardj3b290482011-05-06 21:02:55 +00002303 } else if (is_opt(argv[i], "--pid=")) {
2304 int newpid;
2305 if (!numeric_val(argv[i], &newpid)) {
sewardj30b3eca2011-06-28 08:20:39 +00002306 fprintf (stderr, "invalid --pid argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00002307 arg_errors++;
2308 } else if (arg_pid != -1) {
sewardj30b3eca2011-06-28 08:20:39 +00002309 fprintf (stderr, "multiple --pid arguments given\n");
sewardj3b290482011-05-06 21:02:55 +00002310 arg_errors++;
2311 } else {
2312 arg_pid = newpid;
2313 }
2314 } else if (is_opt(argv[i], "--wait=")) {
2315 if (!numeric_val(argv[i], &check_trials)) {
sewardj30b3eca2011-06-28 08:20:39 +00002316 fprintf (stderr, "invalid --wait argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00002317 arg_errors++;
2318 }
2319 } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2320 if (!numeric_val(argv[i], &max_invoke_ms)) {
sewardj30b3eca2011-06-28 08:20:39 +00002321 fprintf (stderr, "invalid --max-invoke-ms argument %s\n", argv[i]);
2322 arg_errors++;
2323 }
2324 } else if (is_opt(argv[i], "--cmd-time-out=")) {
2325 if (!numeric_val(argv[i], &cmd_time_out)) {
2326 fprintf (stderr, "invalid --cmd-time-out argument %s\n", argv[i]);
sewardj3b290482011-05-06 21:02:55 +00002327 arg_errors++;
2328 }
sewardj992d3cc2011-10-22 20:38:08 +00002329 } else if (is_opt(argv[i], "--port=")) {
2330 if (!numeric_val(argv[i], &int_port)) {
2331 fprintf (stderr, "invalid --port argument %s\n", argv[i]);
2332 arg_errors++;
2333 }
sewardj3b290482011-05-06 21:02:55 +00002334 } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2335 vgdb_prefix = argv[i] + 14;
2336 } else if (is_opt(argv[i], "-c")) {
2337 last_command++;
2338 commands[last_command] = vmalloc (1);
2339 commands[last_command][0] = '\0';
2340 } else if (0 == strncmp(argv[i], "-", 1)) {
2341 fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
2342 arg_errors++;
2343 } else {
2344 int len;
2345 if (last_command == -1) {
2346 /* only one command, no -c command indicator */
2347 last_command++;
2348 commands[last_command] = vmalloc (1);
2349 commands[last_command][0] = '\0';
2350 }
2351 len = strlen(commands[last_command]);
2352 commands[last_command] = vrealloc (commands[last_command],
2353 len + 1 + strlen(argv[i]) + 1);
2354 if (len > 0)
2355 strcat (commands[last_command], " ");
2356 strcat (commands[last_command], argv[i]);
2357 if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2358 fprintf (stderr, "command %s too long\n", commands[last_command]);
2359 arg_errors++;
2360 }
2361
2362 }
2363 }
sewardjd142f992011-05-17 17:15:07 +00002364
florianb985e2d2011-09-29 03:03:45 +00002365 if (vgdb_prefix == NULL)
2366 vgdb_prefix = vgdb_prefix_default();
2367
sewardjd142f992011-05-17 17:15:07 +00002368 if (isatty(0)
2369 && !show_shared_mem
2370 && !show_list
sewardj992d3cc2011-10-22 20:38:08 +00002371 && int_port == 0
sewardjd142f992011-05-17 17:15:07 +00002372 && last_command == -1) {
2373 arg_errors++;
2374 fprintf (stderr,
2375 "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2376 }
2377
2378 if (show_shared_mem && show_list) {
2379 arg_errors++;
2380 fprintf (stderr,
2381 "Can't use both -D and -l options\n");
2382 }
2383
sewardj30b3eca2011-06-28 08:20:39 +00002384 if (max_invoke_ms > 0
2385 && cmd_time_out != NEVER
2386 && (cmd_time_out * 1000) <= max_invoke_ms) {
2387 arg_errors++;
2388 fprintf (stderr,
2389 "--max-invoke-ms must be < --cmd-time-out * 1000\n");
2390 }
2391
sewardjd142f992011-05-17 17:15:07 +00002392 if (show_list && arg_pid != -1) {
2393 arg_errors++;
2394 fprintf (stderr,
2395 "Can't use both --pid and -l options\n");
2396 }
2397
sewardj992d3cc2011-10-22 20:38:08 +00002398 if (int_port > 0 && last_command != -1) {
2399 arg_errors++;
2400 fprintf (stderr,
2401 "Can't use --port to send commands\n");
2402 }
2403
sewardj3b290482011-05-06 21:02:55 +00002404 if (arg_errors > 0) {
2405 fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
2406 exit(1);
2407 }
2408
2409 *p_show_shared_mem = show_shared_mem;
sewardjd142f992011-05-17 17:15:07 +00002410 *p_show_list = show_list;
sewardj3b290482011-05-06 21:02:55 +00002411 *p_arg_pid = arg_pid;
2412 *p_check_trials = check_trials;
sewardj992d3cc2011-10-22 20:38:08 +00002413 *p_port = int_port;
sewardj3b290482011-05-06 21:02:55 +00002414 *p_last_command = last_command;
2415}
2416
2417int main(int argc, char** argv)
2418{
2419 int i;
2420 int pid;
2421
2422 Bool show_shared_mem;
sewardjd142f992011-05-17 17:15:07 +00002423 Bool show_list;
sewardj3b290482011-05-06 21:02:55 +00002424 int arg_pid;
2425 int check_trials;
sewardj992d3cc2011-10-22 20:38:08 +00002426 int in_port;
sewardj3b290482011-05-06 21:02:55 +00002427 int last_command;
2428 char *commands[argc]; // we will never have more commands than args.
2429
2430 parse_options(argc, argv,
2431 &show_shared_mem,
sewardjd142f992011-05-17 17:15:07 +00002432 &show_list,
sewardj3b290482011-05-06 21:02:55 +00002433 &arg_pid,
2434 &check_trials,
sewardj992d3cc2011-10-22 20:38:08 +00002435 &in_port,
sewardj3b290482011-05-06 21:02:55 +00002436 &last_command,
2437 commands);
2438
2439 /* when we are working as a relay for gdb, handle some signals by
2440 only reporting them (according to debug level). Also handle these
2441 when ptrace will be used: vgdb must clean up the ptrace effect before
2442 dying. */
2443 if (max_invoke_ms > 0 || last_command == -1)
2444 install_handlers();
2445
sewardjd142f992011-05-17 17:15:07 +00002446 pid = search_arg_pid (arg_pid, check_trials, show_list);
sewardj3b290482011-05-06 21:02:55 +00002447
2448 prepare_fifos_and_shared_mem(pid);
2449
sewardj992d3cc2011-10-22 20:38:08 +00002450 if (in_port > 0)
2451 wait_for_gdb_connect(in_port);
2452
sewardj3b290482011-05-06 21:02:55 +00002453 if (show_shared_mem) {
2454 fprintf(stderr,
2455 "vgdb %d "
2456 "written_by_vgdb %d "
2457 "seen_by_valgrind %d\n"
2458 "vgdb pid %d\n",
2459 VS_vgdb_pid,
2460 VS_written_by_vgdb,
2461 VS_seen_by_valgrind,
2462 VS_vgdb_pid);
2463 exit (0);
2464 }
2465
2466 if (last_command >= 0) {
2467 standalone_send_commands(pid, last_command, commands);
2468 } else {
2469 gdb_relay(pid);
2470 }
2471
2472
2473 free (from_gdb_to_pid);
2474 free (to_gdb_from_pid);
2475 free (shared_mem);
2476
2477 for (i = 0; i <= last_command; i++)
2478 free (commands[i]);
2479 return 0;
2480}