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