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