]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/valgrind/src/valgrind-3.6.0-svn/coregrind/vgdb.c
update
[l4.git] / l4 / pkg / valgrind / src / valgrind-3.6.0-svn / coregrind / vgdb.c
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 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 #include "pub_core_basics.h"
29 #include "pub_core_vki.h"
30 #include "pub_core_libcsetjmp.h"
31 #include "pub_core_threadstate.h"
32 #include "pub_core_gdbserver.h"
33
34 #include <unistd.h>
35 #include <string.h>
36 #include <poll.h>
37 #include <pthread.h>
38 #include <stdlib.h>
39 #include <stdio.h>
40 #include <fcntl.h>
41 #include <dirent.h>
42 #include <sys/stat.h>
43 #include <sys/time.h>
44 #include <errno.h>
45 #include <signal.h>
46 #include <sys/mman.h>
47 #include <sys/ptrace.h>
48 #include <sys/wait.h>
49 #include "assert.h"
50 #include <sys/user.h>
51
52 #  if defined(VGO_linux)
53 #include <sys/prctl.h>
54 #include <linux/ptrace.h>
55 #  endif
56
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
86 I_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 static int debuglevel;
97 static struct timeval dbgtv;
98 /* if level <= debuglevel, print timestamp, then print provided by debug info */
99 #define DEBUG(level, ...) (level <= debuglevel ?                        \
100                            gettimeofday(&dbgtv, NULL),                  \
101                            fprintf(stderr, "%ld.%6.6ld ",               \
102                                    (long int)dbgtv.tv_sec,              \
103                                    (long int)dbgtv.tv_usec),            \
104                            fprintf(stderr, __VA_ARGS__),fflush(stderr)  \
105                            : 0)
106
107 /* same as DEBUG but does not print time stamp info */
108 #define PDEBUG(level, ...) (level <= debuglevel ?                       \
109                             fprintf(stderr, __VA_ARGS__),fflush(stderr) \
110                             : 0)
111
112 /* if errno != 0, 
113    report the errno and fprintf the ... varargs on stderr. */
114 #define ERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
115                            fprintf(stderr, __VA_ARGS__),                \
116                            fflush(stderr))
117 /* same as ERROR, but also exits with status 1 */
118 #define XERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
119                             fprintf(stderr, __VA_ARGS__),                \
120                             fflush(stderr),                              \
121                             exit(1))
122
123 static char *vgdb_prefix = "/tmp/vgdb-pipe";
124
125 /* Will be set to True when any condition indicating we have to shutdown
126    is encountered. */
127 static Bool shutting_down = False;
128
129 static VgdbShared32 *shared32;
130 static VgdbShared64 *shared64;
131 #define VS_written_by_vgdb (shared32 != NULL ?        \
132                             shared32->written_by_vgdb \
133                             : shared64->written_by_vgdb)
134 #define VS_seen_by_valgrind (shared32 != NULL ?         \
135                              shared32->seen_by_valgrind \
136                              : shared64->seen_by_valgrind)
137
138 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
139
140 /* Calls malloc (size). Exits if memory can't be allocated. */
141 static
142 void *vmalloc(size_t size)
143 {
144    void * mem = malloc(size);
145    if (mem == NULL)
146       XERROR (errno, "can't allocate memory\n");
147    return mem;
148 }
149
150 /* Calls realloc (size). Exits if memory can't be allocated. */
151 static
152 void *vrealloc(void *ptr,size_t size)
153 {
154    void * mem = realloc(ptr, size);
155    if (mem == NULL)
156       XERROR (errno, "can't reallocate memory\n");
157    return mem;
158 }
159
160 /* add nrw to the written_by_vgdb field of shared32 or shared64 */ 
161 static
162 void add_written(int nrw)
163 {
164    if (shared32 != NULL) 
165       shared32->written_by_vgdb += nrw;
166    else if (shared64 != NULL) 
167       shared64->written_by_vgdb += nrw;
168    else
169       assert(0);
170 }
171
172 static int shared_mem_fd = -1;
173 static
174 void map_vgdbshared (char* shared_mem)
175 {
176    struct stat fdstat;
177    void **s;
178    shared_mem_fd = open(shared_mem, O_RDWR);
179    /* shared_mem_fd will not be closed till vgdb exits. */
180
181    if (shared_mem_fd == -1)
182       XERROR (errno, "error opening %s shared memory file\n", shared_mem);
183
184    if (fstat(shared_mem_fd, &fdstat) != 0)
185       XERROR (errno, "fstat");
186
187    if (fdstat.st_size == sizeof(VgdbShared64))
188       s = (void*) &shared64;
189    else if (fdstat.st_size == sizeof(VgdbShared32))
190       s = (void*) &shared32;
191    else
192 #if VEX_HOST_WORDSIZE == 8
193       XERROR (0,
194               "error size shared memory file %s.\n"
195               "expecting size %d (64bits) or %d (32bits) got %ld.\n",
196               shared_mem,
197               (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32), 
198               (long int)fdstat.st_size);
199 #elif VEX_HOST_WORDSIZE == 4
200       XERROR (0,
201               "error size shared memory file %s.\n"
202               "expecting size %d (32bits) got %ld.\n",
203               shared_mem,
204               (int) sizeof(VgdbShared32), 
205               fdstat.st_size);
206 #else
207 # error "unexpected wordsize"
208 #endif
209
210 #if VEX_HOST_WORDSIZE == 4
211    if (shared64 != NULL)
212       XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
213    /* But we can use a 64 bits vgdb with a 32 bits valgrind */
214 #endif
215
216    *s = (void*) mmap (NULL, fdstat.st_size, 
217                       PROT_READ|PROT_WRITE, MAP_SHARED, 
218                       shared_mem_fd, 0);
219
220    if (*s == (void *) -1)
221       XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
222
223 }
224
225 #if VEX_HOST_WORDSIZE == 8
226 typedef Addr64 CORE_ADDR;
227 typedef Addr64 PTRACE_XFER_TYPE;
228 typedef void* PTRACE_ARG3_TYPE;
229 #elif VEX_HOST_WORDSIZE == 4
230 typedef Addr32 CORE_ADDR;
231 typedef Addr32 PTRACE_XFER_TYPE;
232 typedef void* PTRACE_ARG3_TYPE;
233 #else
234 # error "unexpected wordsize"
235 #endif
236
237 static Bool pid_of_save_regs_continued = False;
238 // True if we have continued pid_of_save_regs after PTRACE_ATTACH
239
240 static Bool dying = False;
241 // Set to True when loss of connection indicating that the Valgrind
242 // process is dying.
243
244 /* To be called when connection with valgrind is lost.  In case we
245 have lost the connection, it means that Valgrind has closed the
246 connection and is busy exiting. We can't and don't have to stop it in
247 this case. */
248 static
249 void valgrind_dying(void)
250 {
251    pid_of_save_regs_continued = False;
252    dying = True;
253 }
254
255
256 #ifdef PTRACEINVOKER
257 /* ptrace_(read|write)_memory are modified extracts of linux-low.c
258    from gdb 6.6. Copyrighted FSF */
259 /* Copy LEN bytes from inferior's memory starting at MEMADDR
260    to debugger memory starting at MYADDR.  */
261
262 static
263 int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
264                         unsigned char *myaddr, int len)
265 {
266    register int i;
267    /* Round starting address down to longword boundary.  */
268    register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
269    /* Round ending address up; get number of longwords that makes.  */
270    register int count
271       = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
272       / sizeof (PTRACE_XFER_TYPE);
273    /* Allocate buffer of that many longwords.  */
274    register PTRACE_XFER_TYPE *buffer
275       = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
276    
277    /* Read all the longwords */
278    for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
279       errno = 0;
280       buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid, 
281                           (PTRACE_ARG3_TYPE) addr, 0);
282       if (errno)
283          return errno;
284    }
285    
286    /* Copy appropriate bytes out of the buffer.  */
287    memcpy (myaddr, 
288            (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
289    
290    return 0;
291 }
292
293 /* Copy LEN bytes of data from debugger memory at MYADDR
294    to inferior's memory at MEMADDR.
295    On failure (cannot write the inferior)
296    returns the value of errno.  */
297
298 static
299 int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr, 
300                          const unsigned char *myaddr, int len)
301 {
302    register int i;
303    /* Round starting address down to longword boundary.  */
304    register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
305    /* Round ending address up; get number of longwords that makes.  */
306    register int count
307       = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1) 
308       / sizeof (PTRACE_XFER_TYPE);
309    /* Allocate buffer of that many longwords.  */
310    register PTRACE_XFER_TYPE *buffer 
311       = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
312    
313    if (debuglevel >= 1) {
314       DEBUG (1, "Writing ");
315       for (i = 0; i < len; i++)
316          PDEBUG (1, "%02x", (unsigned)myaddr[i]);
317       PDEBUG(1, " to %p\n", (void *) memaddr);
318    }
319    
320    /* Fill start and end extra bytes of buffer with existing memory data.  */
321    
322    buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
323                        (PTRACE_ARG3_TYPE) addr, 0);
324    
325    if (count > 1) {
326       buffer[count - 1]
327          = ptrace (PTRACE_PEEKTEXT, inferior_pid,
328                    (PTRACE_ARG3_TYPE) (addr + (count - 1)
329                                        * sizeof (PTRACE_XFER_TYPE)),
330                    0);
331    }
332    
333    /* Copy data to be written over corresponding part of buffer */
334    
335    memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), 
336            myaddr, len);
337    
338    /* Write the entire buffer.  */
339    
340    for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
341       errno = 0;
342       ptrace (PTRACE_POKETEXT, inferior_pid, 
343               (PTRACE_ARG3_TYPE) addr, buffer[i]);
344       if (errno)
345          return errno;
346    }
347    
348    return 0;
349 }
350
351 /* subset of VG_(threads) needed for vgdb ptrace.
352    This is initialized when process is attached. */
353 typedef struct {
354    ThreadStatus status;
355    Int lwpid;
356 }
357 VgdbThreadState;
358 static VgdbThreadState vgdb_threads[VG_N_THREADS];
359
360 static const
361 HChar* name_of_ThreadStatus ( ThreadStatus status )
362 {
363    switch (status) {
364    case VgTs_Empty:     return "VgTs_Empty";
365    case VgTs_Init:      return "VgTs_Init";
366    case VgTs_Runnable:  return "VgTs_Runnable";
367    case VgTs_WaitSys:   return "VgTs_WaitSys";
368    case VgTs_Yielding:  return "VgTs_Yielding";
369    case VgTs_Zombie:    return "VgTs_Zombie";
370    default:             return "VgTs_???";
371   }
372 }
373
374 static 
375 char *status_image (int status)
376 {
377    static char result[256];
378    int sz = 0;
379 #define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
380   
381    result[0] = 0;
382
383    if (WIFEXITED(status))
384       APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
385    
386    if (WIFSIGNALED(status)) {
387       APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
388       if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
389    }
390
391    if (WIFSTOPPED(status))
392       APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
393
394    if (WIFCONTINUED(status))
395       APPEND ("WIFCONTINUED ");
396
397    return result;
398 #undef APPEND
399 }
400
401 /* Wait till the process pid is reported as stopped with signal_expected.
402    If other signal(s) than signal_expected are received, waitstopped
403    will pass them to pid, waiting for signal_expected to stop pid.
404    Returns True when process is in stopped state with signal_expected.
405    Returns False if a problem was encountered while waiting for pid
406    to be stopped.
407
408    If pid is reported as being dead/exited, waitstopped will return False.
409 */
410 static
411 Bool waitstopped (int pid, int signal_expected, char *msg)
412 {
413    pid_t p;
414    int status = 0;
415    int signal_received;
416    int res;
417
418    while (1) {
419       DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
420             msg, signal_expected);
421       p = waitpid(pid, &status, __WALL);
422       DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p, 
423             status, status_image (status));
424       if (p != pid) {
425          ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n", 
426                msg, pid, p, status, status_image (status));
427          return False;
428       }
429
430       if (WIFEXITED(status)) {
431          shutting_down = True;
432          return False;
433       }
434
435       assert (WIFSTOPPED(status));
436       signal_received = WSTOPSIG(status);
437       if (signal_received == signal_expected)
438          break;
439
440       /* pid received a signal which is not the signal we are waiting for.
441          We continue pid, transmitting this signal. */
442       DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
443       res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
444       if (res != 0) {
445          ERROR(errno, "waitstopped PTRACE_CONT\n");
446          return False;
447       }
448    }
449
450    return True;
451 }
452
453 /* Stops the given pid, wait for the process to be stopped.
454    Returns True if succesful, False otherwise.
455    msg is used in tracing and error reporting. */
456 static
457 Bool stop (int pid, char *msg)
458 {
459    long res;
460
461    DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
462    res = kill (pid, SIGSTOP);
463    if (res != 0) {
464       ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
465       return False;
466    }
467          
468    return waitstopped (pid, SIGSTOP, msg);
469
470 }
471
472 /* Attaches to given pid, wait for the process to be stopped.
473    Returns True if succesful, False otherwise.
474    msg is used in tracing and error reporting. */
475 static
476 Bool attach (int pid, char *msg)
477 {
478    long res;
479
480    DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
481    res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
482    if (res != 0) {
483       ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
484       return False;
485    }
486
487    return waitstopped(pid, SIGSTOP, msg);
488 }
489
490 /* once we are attached to the pid, get the list of threads and stop 
491    them all.
492    Returns True if all threads properly suspended, False otherwise. */
493 static
494 Bool acquire_and_suspend_threads(int pid)
495 {
496    int i;
497    int rw;
498    Bool pid_found = False;
499    Addr vgt;
500    int sz_tst;
501    int off_status;
502    int off_lwpid;
503    int nr_live_threads = 0;
504
505    if (shared32 != NULL) {
506       vgt = shared32->threads;
507       sz_tst = shared32->sizeof_ThreadState;
508       off_status = shared32->offset_status;
509       off_lwpid = shared32->offset_lwpid;
510    }
511    else if (shared64 != NULL) {
512       vgt = shared64->threads;
513       sz_tst = shared64->sizeof_ThreadState;
514       off_status = shared64->offset_status;
515       off_lwpid = shared64->offset_lwpid;
516    } else {
517       assert (0);
518    }
519
520    /* note: the entry 0 is unused */
521    for (i = 1; i < VG_N_THREADS; i++) {
522       vgt += sz_tst;
523       rw = ptrace_read_memory(pid, vgt+off_status,
524                               (unsigned char *)&(vgdb_threads[i].status),
525                               sizeof(ThreadStatus));
526       if (rw != 0) {
527          ERROR(rw, "status ptrace_read_memory\n");
528          return False;
529       }
530       
531       rw = ptrace_read_memory(pid, vgt+off_lwpid,
532                               (unsigned char *)&(vgdb_threads[i].lwpid),
533                               sizeof(Int));
534       if (rw != 0) {
535          ERROR(rw, "lwpid ptrace_read_memory\n");
536          return False;
537       }
538       
539       if (vgdb_threads[i].status != VgTs_Empty) {
540          DEBUG(1, "found tid %d status %s lwpid %d\n",
541                i, name_of_ThreadStatus(vgdb_threads[i].status),
542                vgdb_threads[i].lwpid);
543          nr_live_threads++;
544          if (vgdb_threads[i].lwpid <= 1) {
545             if (vgdb_threads[i].lwpid == 0 
546                 && vgdb_threads[i].status == VgTs_Init) {
547                DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
548                      i, name_of_ThreadStatus(vgdb_threads[i].status),
549                      vgdb_threads[i].lwpid);
550             } else {
551                ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
552                      i, name_of_ThreadStatus(vgdb_threads[i].status),
553                      vgdb_threads[i].lwpid);
554             }
555             /* in case we have a VtTs_Init thread with lwpid not yet set,
556                we try again later. */
557             return False;
558          }
559          if (vgdb_threads[i].lwpid == pid) {
560             assert (!pid_found);
561             assert (i == 1);
562             pid_found = True;
563          } else {
564             if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
565                  ERROR(0, "ERROR attach pid %d tid %d\n", 
566                        vgdb_threads[i].lwpid, i);
567                return False;
568             }
569          }
570       }
571    }
572    /* If we found no thread, it means the process is stopping, and
573       we better do not force anything to happen during that. */
574    if (nr_live_threads > 0)
575       return True;
576    else
577       return False;
578 }
579
580 static
581 void detach_from_all_threads(int pid)
582 {
583    int i;
584    long res;
585    Bool pid_found = False;
586
587    /* detach from all the threads  */
588    for (i = 1; i < VG_N_THREADS; i++) {
589       if (vgdb_threads[i].status != VgTs_Empty) {
590          if (vgdb_threads[i].status == VgTs_Init
591              && vgdb_threads[i].lwpid == 0) {
592             DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
593                   vgdb_threads[i].lwpid, i, 
594                   name_of_ThreadStatus (vgdb_threads[i].status));
595          } else {
596             if (vgdb_threads[i].lwpid == pid) {
597                assert (!pid_found);
598                pid_found = True;
599             }
600             DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
601                   vgdb_threads[i].lwpid, i, 
602                   name_of_ThreadStatus (vgdb_threads[i].status));
603             res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
604             if (res != 0) {
605                ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n", 
606                      vgdb_threads[i].lwpid, i,
607                      name_of_ThreadStatus (vgdb_threads[i].status),
608                      res);
609             }
610          }
611       }
612    }
613
614    if (!pid_found && pid) {
615       /* No threads are live. Process is busy stopping.
616          We need to detach from pid explicitely. */
617       DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
618       res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
619       if (res != 0)
620          ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
621    }
622 }
623
624 // if > 0, pid for which registers have to be restored.
625 static int pid_of_save_regs = 0;
626 static struct user user_save;
627
628 // The below indicates if ptrace_getregs (and ptrace_setregs) can be used.
629 // Note that some linux versions are defining PTRACE_GETREGS but using
630 // it gives back EIO.
631 // has_working_ptrace_getregs can take the following values:
632 //  -1 : PTRACE_GETREGS is defined
633 //       runtime check not yet done.
634 //   0 : PTRACE_GETREGS runtime check has failed.
635 //   1 : PTRACE_GETREGS defined and runtime check ok.
636 #ifdef PTRACE_GETREGS
637 static int has_working_ptrace_getregs = -1;
638 #endif
639
640 /* Get the registers from pid into regs.
641    regs_bsz value gives the length of *regs. 
642    Returns True if all ok, otherwise False. */
643 static
644 Bool getregs (int pid, void *regs, long regs_bsz)
645 {
646    DEBUG(1, "getregs regs_bsz %ld\n", regs_bsz);
647 #  ifdef PTRACE_GETREGS
648    if (has_working_ptrace_getregs) {
649       // Platforms having GETREGS
650       long res;
651       DEBUG(1, "getregs PTRACE_GETREGS\n");
652       res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
653       if (res == 0) {
654          if (has_working_ptrace_getregs == -1) {
655             // First call to PTRACE_GETREGS succesful =>
656             has_working_ptrace_getregs = 1;
657             DEBUG(1, "detected a working PTRACE_GETREGS\n");
658          }
659          assert (has_working_ptrace_getregs == 1);
660          return True;
661       }
662       else if (has_working_ptrace_getregs == 1) {
663          // We had a working call, but now it fails.
664          // This is unexpected.
665          ERROR(errno, "PTRACE_GETREGS %ld\n", res);
666          return False;
667       } else {
668          // Check this is the first call:
669          assert (has_working_ptrace_getregs == -1);
670          if (errno == EIO) {
671             DEBUG(1, "detected a broken PTRACE_GETREGS with EIO\n");
672             has_working_ptrace_getregs = 0;
673             // Fall over to the PTRACE_PEEKUSER case.
674          } else {
675             ERROR(errno, "broken PTRACE_GETREGS unexpected errno %ld\n", res);
676             return False;
677          }
678       }
679    }
680 #  endif
681
682    // We assume  PTRACE_PEEKUSER is defined everywhere.
683    {
684 #     ifdef PT_ENDREGS
685       long peek_bsz = PT_ENDREGS;
686       assert (peek_bsz <= regs_bsz);
687 #     else
688       long peek_bsz = regs_bsz-1;
689 #     endif
690       char *pregs = (char *) regs;
691       long offset;
692       errno = 0;
693       DEBUG(1, "getregs PTRACE_PEEKUSER(s) peek_bsz %ld\n", peek_bsz);
694       for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
695          *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
696          if (errno != 0) {
697             ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
698             return False;
699          }
700       }
701       return True;
702    }
703
704    // If neither PTRACE_GETREGS not PTRACE_PEEKUSER have returned,
705    // then we are in serious trouble.
706    assert (0);
707 }
708
709 /* Set the registers of pid to regs.
710    regs_bsz value gives the length of *regs. 
711    Returns True if all ok, otherwise False. */
712 static
713 Bool setregs (int pid, void *regs, long regs_bsz)
714 {
715    DEBUG(1, "setregs regs_bsz %ld\n", regs_bsz);
716 // Note : the below is checking for GETREGS, not SETREGS
717 // as if one is defined and working, the other one should also work.
718 #  ifdef PTRACE_GETREGS
719    if (has_working_ptrace_getregs) {
720       // Platforms having SETREGS
721       long res;
722       // setregs can never be called before getregs has done a runtime check.
723       assert (has_working_ptrace_getregs == 1);
724       DEBUG(1, "setregs PTRACE_SETREGS\n");
725       res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
726       if (res != 0) {
727          ERROR(errno, "PTRACE_SETREGS %ld\n", res);
728          return False;
729       }
730       return True;
731    }
732 #  endif
733
734    {
735       char *pregs = (char *) regs;
736       long offset;
737       long res;
738 #     ifdef PT_ENDREGS
739       long peek_bsz = PT_ENDREGS;
740       assert (peek_bsz <= regs_bsz);
741 #     else
742       long peek_bsz = regs_bsz-1;
743 #     endif
744       errno = 0;
745       DEBUG(1, "setregs PTRACE_POKEUSER(s) %ld\n", peek_bsz);
746       for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
747          res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
748          if (errno != 0) {
749             ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
750             return False;
751          }
752       }
753       return True;
754    }
755
756    // If neither PTRACE_SETREGS not PTRACE_POKEUSER have returned,
757    // then we are in serious trouble.
758    assert (0);
759 }
760
761 /* Restore the registers to the saved value, then detaches from all threads */
762 static
763 void restore_and_detach(int pid)
764 {
765    if (pid_of_save_regs) {
766       /* In case the 'main pid' has been continued, we need to stop it
767          before resetting the registers. */
768       if (pid_of_save_regs_continued) {
769          pid_of_save_regs_continued = False;
770          if (!stop(pid_of_save_regs, "sigstop before reset regs"))
771             DEBUG(0, "Could not sigstop before reset");
772       }
773
774       DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
775       if (!setregs(pid_of_save_regs, &user_save.regs, sizeof(user_save.regs))) {
776          ERROR(errno, "setregs restore registers pid %d after cont\n",
777                pid_of_save_regs);
778       }
779       pid_of_save_regs = 0;
780    } else {
781       DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
782    }
783    detach_from_all_threads(pid);
784 }
785
786 /* Ensures that the gdbserver code is invoked by pid.
787    If an error occurs, resets to the valgrind process
788    to the state it has before being ptrace-d.
789    Returns True if invoke successful, False otherwise.
790 */
791 static
792 Bool invoke_gdbserver (int pid)
793 {
794    long res;
795    Bool stopped;
796    struct user user_mod;
797    Addr sp;
798    /* A specific int value is passed to invoke_gdbserver, to check
799       everything goes according to the plan. */
800    const int check = 0x8BADF00D; // ate bad food.
801
802    const Addr bad_return = 0;
803    // A bad return address will be pushed on the stack.
804    // The function invoke_gdbserver cannot return. If ever it returns, a NULL
805    // address pushed on the stack should ensure this is detected.
806
807    /* Not yet attached. If problem, vgdb can abort,
808       no cleanup needed.
809
810       On Ubuntu>= 10.10, a /proc setting can disable ptrace.
811       So, Valgrind has to SET_PTRACER this vgdb. Once this
812       is done, this vgdb can ptrace the valgrind process. */
813
814    DEBUG(1, "attach to 'main' pid %d\n", pid);
815    if (!attach(pid, "attach main pid")) {
816       ERROR(0, "error attach main pid %d\n", pid);
817       return False;
818    }
819
820    /* Now, we are attached. If problem, detach and return. */
821
822    if (!acquire_and_suspend_threads(pid)) {
823       detach_from_all_threads(pid);
824       /* if the pid does not exist anymore, we better stop */
825       if (kill(pid, 0) != 0)
826         XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
827                 pid);
828       return False;
829    }
830
831    if (!getregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
832       detach_from_all_threads(pid);
833       return False;
834    }
835    user_save = user_mod;
836
837 #if defined(VGA_x86)
838    sp = user_mod.regs.esp;
839 #elif defined(VGA_amd64)
840    sp = user_mod.regs.rsp;
841    if (shared32 != NULL) {
842      /* 64bit vgdb speaking with a 32bit executable.
843         To have system call restart properly, we need to sign extend rax.
844         For more info:
845         web search '[patch] Fix syscall restarts for amd64->i386 biarch'
846         e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
847      *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
848      DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
849            user_mod.regs.rax, user_save.regs.rax);
850    }
851 #elif defined(VGA_arm)
852    sp = user_mod.regs.uregs[13];
853 #elif defined(VGA_ppc32)
854    sp = user_mod.regs.gpr[1];
855 #elif defined(VGA_ppc64)
856    sp = user_mod.regs.gpr[1];
857 #elif defined(VGA_s390x)
858    sp = user_mod.regs.gprs[15];
859 #else
860    I_die_here : (sp) architecture missing in vgdb.c
861 #endif
862
863
864    // the magic below is derived from spying what gdb sends to
865    // the (classical) gdbserver when invoking a C function.
866    if (shared32 != NULL) {
867       // vgdb speaking with a 32bit executable.
868 #if   defined(VGA_x86) || defined(VGA_amd64)
869       const int regsize = 4;
870       int rw;
871       /* push check arg on the stack */
872       sp = sp - regsize;
873       DEBUG(1, "push check arg ptrace_write_memory\n");
874       assert(regsize == sizeof(check));
875       rw = ptrace_write_memory(pid, sp, 
876                                (unsigned char *) &check, 
877                                regsize);
878       if (rw != 0) {
879          ERROR(rw, "push check arg ptrace_write_memory");
880          detach_from_all_threads(pid);
881          return False;
882       }
883
884       sp = sp - regsize;
885       DEBUG(1, "push bad_return return address ptrace_write_memory\n");
886       // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
887       // are written.
888       rw = ptrace_write_memory(pid, sp, 
889                                (unsigned char *) &bad_return,
890                                regsize);
891       if (rw != 0) {
892          ERROR(rw, "push bad_return return address ptrace_write_memory");
893          detach_from_all_threads(pid);
894          return False;
895       }
896 #if   defined(VGA_x86)
897       /* set ebp, esp, eip and orig_eax to invoke gdbserver */
898       // compiled in 32bits, speaking with a 32bits exe
899       user_mod.regs.ebp = sp; // bp set to sp
900       user_mod.regs.esp = sp;
901       user_mod.regs.eip = shared32->invoke_gdbserver;
902       user_mod.regs.orig_eax = -1L;
903 #elif defined(VGA_amd64)
904       /* set ebp, esp, eip and orig_eax to invoke gdbserver */
905       // compiled in 64bits, speaking with a 32bits exe
906       user_mod.regs.rbp = sp; // bp set to sp
907       user_mod.regs.rsp = sp;
908       user_mod.regs.rip = shared32->invoke_gdbserver;
909       user_mod.regs.orig_rax = -1L;
910 #else
911       I_die_here : not x86 or amd64 in x86/amd64 section/
912 #endif
913
914 #elif defined(VGA_ppc32) || defined(VGA_ppc64)
915       user_mod.regs.nip = shared32->invoke_gdbserver;
916       user_mod.regs.trap = -1L;
917       /* put check arg in register 3 */
918       user_mod.regs.gpr[3] = check;
919       /* put NULL return address in Link Register */
920       user_mod.regs.link = bad_return;
921
922 #elif defined(VGA_arm)
923       /* put check arg in register 0 */
924       user_mod.regs.uregs[0] = check;
925       /* put NULL return address in Link Register */
926       user_mod.regs.uregs[14] = bad_return;
927       user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
928
929 #elif defined(VGA_s390x)
930       XERROR(0, "(fn32) s390x has no 32bits implementation");
931 #else
932       I_die_here : architecture missing in vgdb.c
933 #endif
934       }
935
936    else if (shared64 != NULL) {
937 #if defined(VGA_x86)
938       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
939 #elif defined(VGA_amd64)
940       // vgdb speaking with a 64 bit executable.
941       const int regsize = 8;
942       int rw;
943       
944       /* give check arg in rdi */
945       user_mod.regs.rdi = check;
946
947       /* push return address on stack : return to breakaddr */
948       sp = sp - regsize;
949       DEBUG(1, "push bad_return return address ptrace_write_memory\n");
950       rw = ptrace_write_memory(pid, sp, 
951                                (unsigned char *) &bad_return,
952                                sizeof(bad_return));
953       if (rw != 0) {
954          ERROR(rw, "push bad_return return address ptrace_write_memory");
955          detach_from_all_threads(pid);
956          return False;
957       }
958
959       /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
960       user_mod.regs.rbp = sp; // bp set to sp
961       user_mod.regs.rsp = sp;
962       user_mod.regs.rip = shared64->invoke_gdbserver;
963       user_mod.regs.orig_rax = -1L;
964
965 #elif defined(VGA_arm)
966       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
967 #elif defined(VGA_ppc32)
968       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
969 #elif defined(VGA_ppc64)
970       Addr64 func_addr;
971       Addr64 toc_addr;
972       int rw;
973       rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
974                               (unsigned char *)&func_addr,
975                               sizeof(Addr64));
976       if (rw != 0) {
977          ERROR(rw, "ppc64 read func_addr\n");
978          detach_from_all_threads(pid);
979          return False;
980       }
981       rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
982                               (unsigned char *)&toc_addr,
983                               sizeof(Addr64));
984       if (rw != 0) {
985          ERROR(rw, "ppc64 read toc_addr\n");
986          detach_from_all_threads(pid);
987          return False;
988       }
989       // We are not pushing anything on the stack, so it is not
990       // very clear why the sp has to be decreased, but it seems
991       // needed. The ppc64 ABI might give some lights on this ?
992       user_mod.regs.gpr[1] = sp - 220;
993       user_mod.regs.gpr[2] = toc_addr;
994       user_mod.regs.nip = func_addr;
995       user_mod.regs.trap = -1L;
996       /* put check arg in register 3 */
997       user_mod.regs.gpr[3] = check;
998       /* put bad_return return address in Link Register */
999       user_mod.regs.link = bad_return;
1000 #elif defined(VGA_s390x)
1001       /* put check arg in register r2 */
1002       user_mod.regs.gprs[2] = check;
1003       /* bad_return Return address is in r14 */
1004       user_mod.regs.gprs[14] = bad_return;
1005       /* minimum stack frame */
1006       sp = sp - 160;
1007       user_mod.regs.gprs[15] = sp;
1008       /* set program counter */
1009       user_mod.regs.psw.addr = shared64->invoke_gdbserver;
1010 #else
1011       I_die_here: architecture missing in vgdb.c
1012 #endif
1013    }
1014    else {
1015       assert(0);
1016    }
1017    
1018    if (!setregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
1019       detach_from_all_threads(pid);
1020       return False;
1021    }
1022    /* Now that we have modified the registers, we set
1023       pid_of_save_regs to indicate that restore_and_detach
1024       must restore the registers in case of cleanup. */
1025    pid_of_save_regs = pid;
1026    pid_of_save_regs_continued = False;
1027       
1028
1029    /* We PTRACE_CONT-inue pid. 
1030       Either gdbserver will be invoked directly (if all
1031       threads are interruptible) or gdbserver will be
1032       called soon by the scheduler. In the first case,
1033       pid will stop on the break inserted above when
1034       gdbserver returns. In the 2nd case, the break will
1035       be encountered directly. */
1036    DEBUG(1, "PTRACE_CONT to invoke\n");
1037    res = ptrace (PTRACE_CONT, pid, NULL, NULL);
1038    if (res != 0) {
1039       ERROR(errno, "PTRACE_CONT\n");
1040       restore_and_detach(pid);
1041       return False;
1042    }
1043    pid_of_save_regs_continued = True;
1044    
1045    stopped = waitstopped (pid, SIGTRAP,
1046                           "waitpid status after PTRACE_CONT to invoke");
1047    if (stopped) {
1048       /* Here pid has properly stopped on the break. */
1049       pid_of_save_regs_continued = False;
1050       restore_and_detach(pid);
1051       return True;
1052    } else {
1053       /* Whatever kind of problem happened. We shutdown */
1054       shutting_down = True;
1055       return False;
1056    }
1057 }
1058 #endif
1059
1060 static 
1061 void cleanup_restore_and_detach(void *v_pid)
1062 {
1063    DEBUG(1, "cleanup_restore_and_detach dying: %d\n", dying);
1064 #ifdef PTRACEINVOKER
1065    if (!dying)
1066       restore_and_detach(*(int*)v_pid);
1067 #endif
1068 }
1069
1070 /* This function loops till shutting_down becomes true.  In this loop,
1071    it verifies if valgrind process is reading the characters written
1072    by vgdb.  The verification is done every max_invoke_ms ms.  If
1073    valgrind is not reading characters, it will use invoke_gdbserver
1074    (if PTRACE_INVOKER is defined) to ensure that the gdbserver code is
1075    called soon by valgrind. */
1076 static int max_invoke_ms = 100;
1077 static
1078 void *invoke_gdbserver_in_valgrind(void *v_pid)
1079 {
1080    int pid = *(int *)v_pid;
1081    int written_by_vgdb_before_sleep;
1082    int seen_by_valgrind_before_sleep;
1083    
1084    int invoked_written = -1;
1085
1086    pthread_cleanup_push(cleanup_restore_and_detach, v_pid);
1087
1088    while (!shutting_down) {
1089       written_by_vgdb_before_sleep = VS_written_by_vgdb;
1090       seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
1091       DEBUG(3, 
1092             "written_by_vgdb_before_sleep %d "
1093             "seen_by_valgrind_before_sleep %d\n",
1094             written_by_vgdb_before_sleep,
1095             seen_by_valgrind_before_sleep);
1096       if (usleep(1000 * max_invoke_ms) != 0) {
1097          if (errno == EINTR)
1098             continue;
1099          XERROR (errno, "error usleep\n");
1100       }
1101       /* if nothing happened during our sleep, let's try to wake up valgrind */
1102       if (written_by_vgdb_before_sleep == VS_written_by_vgdb
1103           && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
1104           && VS_written_by_vgdb > VS_seen_by_valgrind) {
1105          DEBUG(2,
1106                "after sleep "
1107                "written_by_vgdb %d "
1108                "seen_by_valgrind %d "
1109                "invoked_written %d\n",
1110                VS_written_by_vgdb,
1111                VS_seen_by_valgrind,
1112                invoked_written);
1113          /* if the pid does not exist anymore, we better stop */
1114          if (kill(pid, 0) != 0)
1115            XERROR (errno, 
1116                    "invoke_gdbserver_in_valgrind: "
1117                    "check for pid %d existence failed\n", pid);
1118
1119          #if defined(PTRACEINVOKER)
1120          /* only need to wake up if the nr written has changed since
1121             last invoke. */
1122          if (invoked_written != written_by_vgdb_before_sleep) {
1123             if (invoke_gdbserver(pid)) {
1124                /* If invoke succesful, no need to invoke again
1125                   for the same value of written_by_vgdb_before_sleep. */
1126                invoked_written = written_by_vgdb_before_sleep;
1127             }
1128          }
1129          #else
1130          DEBUG(2, "invoke_gdbserver via ptrace not (yet) implemented\n");
1131          #endif
1132       }
1133    }
1134    pthread_cleanup_pop(0);
1135    return NULL;
1136 }
1137
1138 static
1139 int open_fifo (char* name, int flags, char* desc)
1140 {
1141    int fd;
1142    DEBUG(1, "opening %s %s\n", name, desc);
1143    fd = open(name, flags);
1144    if (fd == -1)
1145       XERROR (errno, "error opening %s %s\n", name, desc);
1146
1147    DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
1148    return fd;
1149 }
1150
1151 /* acquire a lock on the first byte of the given fd. If not successful,
1152    exits with error.
1153    This allows to avoid having two vgdb speaking with the same Valgrind
1154    gdbserver as this causes serious headaches to the protocol. */
1155 static
1156 void acquire_lock (int fd, int valgrind_pid)
1157 {
1158    if (lockf(fd, F_TLOCK, 1) < 0) {
1159       if (errno == EAGAIN || errno == EACCES) {
1160          XERROR(errno, 
1161                 "Cannot acquire lock.\n"
1162                 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
1163                 VS_vgdb_pid,
1164                 valgrind_pid);
1165       } else {
1166          XERROR(errno, "cannot acquire lock.\n");
1167       }
1168    }
1169
1170    /* Here, we have the lock. It will be released when fd will be closed. */
1171    /* We indicate our pid to Valgrind gdbserver */
1172    if (shared32 != NULL)
1173       shared32->vgdb_pid = getpid();
1174    else if (shared64 != NULL)
1175       shared64->vgdb_pid = getpid();
1176    else
1177       assert(0);
1178 }
1179
1180 #define PBUFSIZ 16384 /* keep in sync with server.h */
1181
1182 /* read some characters from fd.
1183    Returns the nr of characters read, -1 if error.
1184    desc is a string used in tracing */
1185 static
1186 int read_buf (int fd, char* buf, char* desc)
1187 {
1188    int nrread;
1189    DEBUG(2, "reading %s\n", desc);
1190    nrread = read(fd, buf, PBUFSIZ);
1191    if (nrread == -1) {
1192       ERROR (errno, "error reading %s\n", desc);
1193       return -1;
1194    }
1195    buf[nrread] = '\0';
1196    DEBUG(2, "read %s %s\n", desc, buf);
1197    return nrread;
1198 }
1199
1200 /* write size bytes from buf to fd.
1201    desc is a description of the action for which the write is done.
1202    If notify, then add size to the shared cntr indicating to the 
1203    valgrind process that there is new data.
1204    Returns True if write is ok, False if there was a problem. */
1205 static
1206 Bool write_buf(int fd, char* buf, int size, char* desc, Bool notify)
1207 {
1208    int nrwritten;
1209    int nrw;
1210    DEBUG(2, "writing %s len %d %s notify: %d\n", desc, size, buf, notify);
1211    nrwritten = 0;
1212    while (nrwritten < size) {
1213       nrw = write (fd, buf+nrwritten, size - nrwritten);
1214       if (nrw == -1) {
1215          ERROR(errno, "error write %s\n", desc);
1216          return False;
1217       }
1218       nrwritten = nrwritten + nrw;
1219       if (notify)
1220          add_written(nrw);
1221    }
1222    return True;
1223
1224
1225 typedef enum {
1226    FROM_GDB,
1227    TO_GDB,
1228    FROM_PID,
1229    TO_PID } ConnectionKind;
1230 static const int NumConnectionKind = TO_PID+1;
1231 static 
1232 char *ppConnectionKind (ConnectionKind con)
1233 {
1234    switch (con) {
1235    case FROM_GDB: return "FROM_GDB";
1236    case TO_GDB:   return "TO_GDB";
1237    case FROM_PID: return "FROM_PID";
1238    case TO_PID:   return "TO_PID";
1239    default:       return "invalid connection kind";
1240    }
1241 }
1242
1243 static char *shared_mem;
1244
1245 static const int from_gdb = 0;
1246 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
1247 /* Returns True in case read/write operations were done properly.
1248    Returns False in case of error.
1249    to_pid is the file descriptor to write to the process pid. */
1250 static
1251 Bool read_from_gdb_write_to_pid(int to_pid)
1252 {
1253    char buf[PBUFSIZ];
1254    int nrread;
1255
1256    nrread = read_buf(from_gdb, buf, "from gdb on stdin");
1257    if (nrread <= 0) {
1258       if (nrread == 0) 
1259          DEBUG(1, "read 0 bytes from gdb => assume exit\n");
1260       else
1261          DEBUG(1, "error reading bytes from gdb\n");
1262       close (from_gdb);
1263       shutting_down = True;
1264       return False;
1265    }
1266    return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
1267 }
1268
1269 static const int to_gdb = 1;
1270 static char *to_gdb_from_pid; /* fifo name to read pid replies */
1271 /* Returns True in case read/write operations were done properly.
1272    Returns False in case of error.
1273    from_pid is the file descriptor to read data from the process pid. */
1274 static
1275 Bool read_from_pid_write_to_gdb(int from_pid)
1276 {
1277    char buf[PBUFSIZ];
1278    int nrread;
1279
1280    nrread = read_buf(from_pid, buf, "from pid");
1281    if (nrread <= 0) {
1282       if (nrread == 0) 
1283          DEBUG(1, "read 0 bytes from pid => assume exit\n");
1284       else
1285          DEBUG(1, "error reading bytes from pid\n");
1286       close (from_pid);
1287       shutting_down = True;
1288       return False;
1289    }
1290    return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
1291 }
1292
1293 /* prepares the FIFOs filenames, map the shared memory. */
1294 static
1295 void prepare_fifos_and_shared_mem(int pid)
1296 {
1297    from_gdb_to_pid = vmalloc (strlen(vgdb_prefix) + 30);
1298    to_gdb_from_pid = vmalloc (strlen(vgdb_prefix) + 30);
1299    shared_mem      = vmalloc (strlen(vgdb_prefix) + 30);
1300    /* below 3 lines must match the equivalent in remote-utils.c */
1301    sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d",    vgdb_prefix, pid);
1302    sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d",    vgdb_prefix, pid);
1303    sprintf(shared_mem,      "%s-shared-mem-vgdb-%d", vgdb_prefix, pid);
1304    DEBUG (1, "vgdb: using %s %s %s\n", 
1305           from_gdb_to_pid, to_gdb_from_pid, shared_mem);
1306
1307    map_vgdbshared(shared_mem);
1308 }
1309
1310 /* Convert hex digit A to a number.  */
1311
1312 static int
1313 fromhex (int a)
1314 {
1315    if (a >= '0' && a <= '9')
1316       return a - '0';
1317    else if (a >= 'a' && a <= 'f')
1318       return a - 'a' + 10;
1319    else
1320       XERROR(0, "Reply contains invalid hex digit %c\n", a);
1321   return 0;
1322 }
1323
1324 /* Returns next char from fd.  -1 if error, -2 if EOF.
1325    NB: must always call it with the same fd */
1326 static int
1327 readchar (int fd)
1328 {
1329   static unsigned char buf[PBUFSIZ];
1330   static int bufcnt = 0;
1331   static unsigned char *bufp;
1332
1333   if (bufcnt-- > 0)
1334      return *bufp++;
1335
1336   bufcnt = read (fd, buf, sizeof (buf));
1337
1338   if (bufcnt <= 0) {
1339      if (bufcnt == 0) {
1340         fprintf (stderr, "readchar: Got EOF\n");
1341         return -2;
1342      } else {
1343         ERROR (errno, "readchar\n");
1344         return -1;
1345      }
1346   }
1347
1348   bufp = buf;
1349   bufcnt--;
1350   return *bufp++;
1351 }
1352
1353 /* Read a packet from fromfd, with error checking,
1354    and store it in BUF.  
1355    Returns length of packet, or -1 if error or -2 if EOF.
1356    Writes ack on ackfd */
1357
1358 static int
1359 getpkt (char *buf, int fromfd, int ackfd)
1360 {
1361   char *bp;
1362   unsigned char csum, c1, c2;
1363   int c;
1364   
1365   while (1) {
1366      csum = 0;
1367
1368      while (1) {
1369         c = readchar (fromfd);
1370         if (c == '$')
1371            break;
1372         DEBUG(2, "[getpkt: discarding char '%c']\n", c);
1373         if (c < 0)
1374            return c;
1375      }
1376
1377      bp = buf;
1378      while (1) {
1379         c = readchar (fromfd);
1380         if (c < 0)
1381            return c;
1382         if (c == '#')
1383            break;
1384         if (c == '*') {
1385            int repeat;
1386            int r;
1387            int prev;
1388            prev = *(bp-1);
1389            csum += c;
1390            repeat = readchar (fromfd);
1391            csum += repeat;
1392            for (r = 0; r < repeat - 29; r ++)
1393               *bp++ = prev;
1394         } else {
1395            *bp++ = c;
1396            csum += c;
1397         }
1398      }
1399      *bp = 0;
1400
1401      c1 = fromhex (readchar (fromfd));
1402      c2 = fromhex (readchar (fromfd));
1403
1404      if (csum == (c1 << 4) + c2)
1405         break;
1406
1407      fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
1408               (c1 << 4) + c2, csum, buf);
1409      if (write (ackfd, "-", 1) != 1)
1410         ERROR(0, "error when writing - (nack)\n");
1411      else
1412         add_written(1);
1413   }
1414
1415   DEBUG(2, "getpkt (\"%s\");  [sending ack] \n", buf);
1416   if (write (ackfd, "+", 1) != 1)
1417      ERROR(0, "error when writing + (ack)\n");
1418   else
1419      add_written(1);
1420   return bp - buf;
1421 }
1422
1423 static int sigint = 0;
1424 static int sigterm = 0;
1425 static int sigpipe = 0;
1426 static int sighup = 0;
1427 static int sigusr1 = 0;
1428 static int sigalrm = 0;
1429 static int sigusr1_fd = -1;
1430 static pthread_t invoke_gdbserver_in_valgrind_thread;
1431
1432 static
1433 void received_signal (int signum)
1434 {
1435    if (signum == SIGINT)
1436       sigint++;
1437    else if (signum == SIGUSR1) {
1438       sigusr1++;
1439       if (sigusr1_fd >= 0) {
1440          char control_c = '\003';
1441          write_buf(sigusr1_fd, &control_c, 1,
1442                    "write \\003 on SIGUSR1", /* notify */ True);
1443       }
1444    }
1445    else if (signum == SIGTERM) {
1446       shutting_down = True;
1447       sigterm++;
1448    } else if (signum == SIGHUP) {
1449       shutting_down = True;
1450       sighup++;
1451    } else if (signum == SIGPIPE) {
1452       sigpipe++;
1453    } else if (signum == SIGALRM) {
1454       sigalrm++;
1455       DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
1456       /* Note: we cannot directly invoke restore_and_detach : this must
1457          be done by the thread that has attached. 
1458          We have in this thread pushed a cleanup handler that will
1459          cleanup what is needed. */
1460       pthread_cancel(invoke_gdbserver_in_valgrind_thread);
1461    } else {
1462       ERROR(0, "unexpected signal %d\n", signum);
1463    }
1464 }
1465
1466 /* install the signal handlers allowing e.g. vgdb to cleanup in
1467    case of termination. */
1468 static
1469 void install_handlers(void)
1470 {
1471    struct sigaction action, oldaction;
1472
1473    action.sa_handler = received_signal;
1474    sigemptyset (&action.sa_mask);
1475    action.sa_flags = 0;
1476    
1477    /* SIGINT: when user types C-c in gdb, this sends
1478       a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
1479       The later is enough to wakeup the valgrind process. */
1480    if (sigaction (SIGINT, &action, &oldaction) != 0)
1481       XERROR (errno, "vgdb error sigaction SIGINT\n");
1482    /* We might do something more intelligent than just
1483       reporting this SIGINT E.g. behave similarly to the gdb: two
1484       control-C without feedback from the debugged process would
1485       mean to stop debugging it. */
1486
1487    /* SIGUSR1: this is used to facilitate automatic testing.  When
1488       vgdb receives this signal, it will simulate the user typing C-c. */
1489    if (sigaction (SIGUSR1, &action, &oldaction) != 0)
1490       XERROR (errno, "vgdb error sigaction SIGUSR1\n");
1491    
1492
1493    /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
1494       when detaching or similar. A clean shutdown will be done as both
1495       the read and write side will detect an end of file. */
1496    if (sigaction (SIGTERM, &action, &oldaction) != 0)
1497       XERROR (errno, "vgdb error sigaction SIGTERM\n");
1498    
1499    /* SIGPIPE: can receive this signal when gdb detaches or kill the
1500       process debugged: gdb will close its pipes to vgdb. vgdb
1501       must resist to this signal to allow a clean shutdown. */
1502    if (sigaction (SIGPIPE, &action, &oldaction) != 0)
1503       XERROR (errno, "vgdb error sigaction SIGPIPE\n");
1504    
1505    /* SIGALRM: in case invoke thread is blocked, alarm is used
1506       to cleanup.  */
1507    if (sigaction (SIGALRM, &action, &oldaction) != 0)
1508       XERROR (errno, "vgdb error sigaction SIGALRM\n");
1509 }
1510
1511 /* close the FIFOs provided connections, terminate the invoker thread.  */
1512 static
1513 void close_connection(int to_pid, int from_pid)
1514 {
1515    DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
1516          sigint, sigterm, sighup, sigpipe);
1517    /* Note that we do not forward sigterm to the valgrind process:
1518       a sigterm signal is (probably) received from gdb if the user wants to
1519       kill the debugged process. The kill instruction has been given to
1520       the valgrind process, which should execute a clean exit. */
1521
1522    /* We first close the connection to pid. The pid will then
1523       terminates its gdbserver work. We keep the from pid
1524       fifo opened till the invoker thread is finished.
1525       This allows the gdbserver to finish sending its last reply. */
1526    if (close(to_pid) != 0)
1527       ERROR(errno, "close to_pid\n");
1528
1529    /* if there is a task that was busy trying to wake up valgrind
1530       process, we wait for it to be terminated otherwise threads
1531       in the valgrind process can stay stopped if vgdb main
1532       exits before the invoke thread had time to detach from
1533       all valgrind threads. */
1534    if (max_invoke_ms > 0) {
1535       int join;
1536
1537       /* It is surprisingly complex to properly shutdown or exit the
1538          valgrind process in which gdbserver has been invoked through
1539          ptrace.  In the normal case (gdb detaches from the process,
1540          or process is continued), the valgrind process will reach the
1541          breakpoint place.  Using ptrace, vgdb will ensure the
1542          previous activity of the process is resumed (e.g. restart a
1543          blocking system call).  The special case is when gdb asks the
1544          valgrind process to exit (using either the "kill" command or
1545          "monitor exit").  In such a case, the valgrind process will
1546          call exit.  But a ptraced process will be blocked in exit,
1547          waiting for the ptracing process to detach or die. vgdb
1548          cannot detach unconditionally as otherwise, in the normal
1549          case, the valgrind process would die abnormally with SIGTRAP
1550          (as vgdb would not be there to catch it). vgdb can also not
1551          die unconditionally otherwise again, similar problem.  So, we
1552          assume that most of the time, we arrive here in the normal
1553          case, and so, the breakpoint has been encountered by the
1554          valgrind process, so the invoker thread will exit and the
1555          join will succeed.  For the "kill" case, we cause an alarm
1556          signal to be sent after a few seconds. This means that in the
1557          normal case, the gdbserver code in valgrind process must have
1558          returned the control in less than the alarm nr of seconds,
1559          otherwise, valgrind will die abnormally with SIGTRAP. */
1560       (void) alarm (3);
1561
1562       DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
1563       join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
1564       if (join != 0)
1565          XERROR 
1566             (join, 
1567              "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
1568    }
1569    if (close(from_pid) != 0)
1570       ERROR(errno, "close from_pid\n");
1571 }
1572
1573 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
1574    error is encountered. */
1575 static
1576 void gdb_relay (int pid)
1577 {
1578    int from_pid = -1; /* fd to read from pid */
1579    int to_pid = -1; /* fd to write to pid */
1580
1581    int shutdown_loop = 0;
1582    fprintf (stderr, "relaying data between gdb and process %d\n", pid);
1583    fflush (stderr);
1584
1585    if (max_invoke_ms > 0)
1586       pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL, 
1587                      invoke_gdbserver_in_valgrind, (void *) &pid);
1588    to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1589    acquire_lock (shared_mem_fd, pid);
1590    
1591    from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK, 
1592                          "read mode from pid");
1593
1594    sigusr1_fd = to_pid; /* allow simulating user typing control-c */
1595
1596    while (1) {
1597       ConnectionKind ck;
1598       int ret;
1599       struct pollfd pollfds[NumConnectionKind];
1600       
1601       /* watch data written by gdb, watch POLLERR on both gdb fd */
1602       pollfds[FROM_GDB].fd = from_gdb;
1603       pollfds[FROM_GDB].events = POLLIN;
1604       pollfds[FROM_GDB].revents = 0;
1605       pollfds[TO_GDB].fd = to_gdb;
1606       pollfds[TO_GDB].events = 0;
1607       pollfds[TO_GDB].revents = 0;
1608       
1609       /* watch data written by pid, watch POLLERR on both pid fd */
1610       pollfds[FROM_PID].fd = from_pid;
1611       pollfds[FROM_PID].events = POLLIN;
1612       pollfds[FROM_PID].revents = 0;
1613       pollfds[TO_PID].fd = to_pid;
1614       pollfds[TO_PID].events = 0;
1615       pollfds[TO_PID].revents = 0;
1616       
1617       ret = poll(pollfds, 
1618                  NumConnectionKind, 
1619                  (shutting_down ? 
1620                   1 /* one second */ 
1621                   : -1 /* infinite */));
1622       DEBUG(2, "poll ret %d errno %d\n", ret, errno);
1623
1624       /* check for unexpected error */
1625       if (ret <= 0 && errno != EINTR) {
1626          ERROR (errno, "unexpected poll ret %d\n", ret);
1627          shutting_down = True;
1628          break;
1629       }
1630       
1631       /* check for data to read */
1632       for (ck = 0; ck < NumConnectionKind; ck ++) {
1633          if (pollfds[ck].revents & POLLIN) {
1634             switch (ck) {
1635             case FROM_GDB: 
1636                if (!read_from_gdb_write_to_pid(to_pid))
1637                   shutting_down = True;
1638                break;
1639                case FROM_PID:
1640                   if (!read_from_pid_write_to_gdb(from_pid))
1641                      shutting_down = True;
1642                   break;
1643             default: XERROR(0, "unexpected POLLIN on %s\n",
1644                                ppConnectionKind(ck));
1645             }
1646          }
1647       }
1648
1649       /* check for an fd being in error condition */
1650       for (ck = 0; ck < NumConnectionKind; ck ++) {
1651          if (pollfds[ck].revents & POLLERR) {
1652             DEBUG(1, "connection %s fd %d POLLERR error condition\n",
1653                      ppConnectionKind(ck), pollfds[ck].fd);
1654             valgrind_dying();
1655             shutting_down = True;
1656          }
1657          if (pollfds[ck].revents & POLLHUP) {
1658             DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
1659                   ppConnectionKind(ck), pollfds[ck].fd);
1660             valgrind_dying();
1661             shutting_down = True;
1662          }
1663          if (pollfds[ck].revents & POLLNVAL) {
1664             DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
1665                   ppConnectionKind(ck), pollfds[ck].fd);
1666             valgrind_dying();
1667             shutting_down = True;
1668          }
1669       }
1670       
1671       if (shutting_down) {
1672          /* we let some time to the final packets to be transferred */
1673          shutdown_loop++;
1674          if (shutdown_loop > 3)
1675             break;
1676       }
1677    }
1678    close_connection(to_pid, from_pid);
1679 }
1680
1681 static int packet_len_for_command(char *cmd)
1682 {
1683    /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc      */
1684    return                          7+     2*strlen(cmd)             +3  + 1;
1685 }
1686
1687 /* hyper-minimal protocol implementation that
1688    sends the provided commands (using qRcmd packets)
1689    and read and display their replies. */
1690 static
1691 void standalone_send_commands(int pid, 
1692                               int last_command,
1693                               char *commands[] )
1694 {
1695    int from_pid = -1; /* fd to read from pid */
1696    int to_pid = -1; /* fd to write to pid */
1697
1698    int i;
1699    int hi;
1700    unsigned char hex[3];
1701    unsigned char cksum;
1702    unsigned char *hexcommand;
1703    unsigned char buf[PBUFSIZ];
1704    int buflen;
1705    int nc;
1706
1707
1708    if (max_invoke_ms > 0)
1709       pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL, 
1710                      invoke_gdbserver_in_valgrind, (void *) &pid);
1711
1712    to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
1713    acquire_lock (shared_mem_fd, pid);
1714
1715    /* first send a C-c \003 to pid, so that it wakes up the process
1716       After that, we can open the fifo from the pid in read mode
1717       We then start to wait for packets (normally first a resume reply)
1718       At that point, we send our command and expect replies */
1719    buf[0] = '\003';
1720    write_buf(to_pid, buf, 1, "write \\003 to wake up", /* notify */ True);
1721    from_pid = open_fifo(to_gdb_from_pid, O_RDONLY, 
1722                         "read cmd result from pid");
1723    
1724    for (nc = 0; nc <= last_command; nc++) {
1725       fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
1726       fflush (stderr);
1727       
1728       /* prepare hexcommand $qRcmd,xxxx....................xx#cc      */
1729       hexcommand = vmalloc (packet_len_for_command(commands[nc]));
1730       hexcommand[0] = 0;
1731       strcat (hexcommand, "$qRcmd,");
1732       for (i = 0; i < strlen(commands[nc]); i++) {
1733          sprintf(hex, "%02x", commands[nc][i]);
1734          strcat (hexcommand, hex);
1735       }
1736       /* checksum (but without the $) */
1737       cksum = 0;
1738       for (hi = 1; hi < strlen(hexcommand); hi++)
1739          cksum+=hexcommand[hi];
1740       strcat(hexcommand, "#");
1741       sprintf(hex, "%02x", cksum);
1742       strcat(hexcommand, hex);
1743       write_buf(to_pid, hexcommand, strlen(hexcommand), 
1744                 "writing hex command to pid", /* notify */ True);
1745
1746       /* we exit of the below loop explicitely when the command has
1747          been handled or because a signal handler will set
1748          shutting_down. */
1749       while (!shutting_down) {
1750          buflen = getpkt(buf, from_pid, to_pid);
1751          if (buflen < 0) {
1752             ERROR (0, "error reading packet\n");
1753             if (buflen == -2)
1754                valgrind_dying();
1755             break;
1756          }
1757          if (strlen(buf) == 0) {
1758             DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
1759             break;
1760          }
1761          if (strcmp(buf, "OK") == 0) {
1762             DEBUG(1, "OK packet rcvd\n");
1763             break;
1764          }
1765          if (buf[0] == 'E') {
1766             DEBUG(0, 
1767                   "E NN error packet rcvd: %s (unknown monitor command?)\n",
1768                   buf);
1769             break;
1770          }
1771          if (buf[0] == 'W') {
1772             DEBUG(0, "W stopped packet rcvd: %s\n", buf);
1773             break;
1774          }
1775          if (buf[0] == 'T') {
1776             DEBUG(1, "T resume reply packet received: %s\n", buf);
1777             continue;
1778          }
1779          
1780          /* must be here an O packet with hex encoded string reply 
1781             => decode and print it */
1782          if (buf[0] != 'O') {
1783             DEBUG(0, "expecting O packet, received: %s\n", buf);
1784             continue;
1785          }
1786          {
1787             char buf_print[buflen/2 + 1];
1788             for (i = 1; i < buflen; i = i + 2)
1789                buf_print[i/2] = (fromhex(*(buf+i)) << 4) 
1790                      + fromhex(*(buf+i+1));
1791             buf_print[buflen/2] = 0;
1792             printf("%s", buf_print);
1793             fflush(stdout);
1794          }
1795       }
1796       free (hexcommand);
1797    }
1798    shutting_down = True;
1799
1800    close_connection(to_pid, from_pid);
1801 }
1802
1803 /* report to user the existence of a vgdb-able valgrind process 
1804    with given pid */
1805 static
1806 void report_pid (int pid)
1807 {
1808    char cmdline_file[100];
1809    char cmdline[1000];
1810    int fd;
1811    int i, sz;
1812
1813    sprintf(cmdline_file, "/proc/%d/cmdline", pid);
1814    fd = open (cmdline_file, O_RDONLY);
1815    if (fd == -1) {
1816       DEBUG(1, "error opening cmdline file %s %s\n", 
1817             cmdline_file, strerror(errno));
1818       sprintf(cmdline, "(could not obtain process command line)");
1819    } else {
1820       sz = read(fd, cmdline, 1000);
1821       for (i = 0; i < sz; i++)
1822          if (cmdline[i] == 0)
1823             cmdline[i] = ' ';
1824       cmdline[sz] = 0;
1825       close (fd);
1826    }  
1827    fprintf(stderr, "use --pid=%d for %s\n", pid, cmdline);
1828    fflush(stderr);
1829 }
1830
1831 /* Eventually produces additional usage information documenting the
1832    ptrace restrictions. */
1833 static
1834 void ptrace_restrictions(void)
1835 {
1836 #  ifdef PR_SET_PTRACER
1837    char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
1838    int fd = -1;
1839    char ptrace_scope = 'X';
1840    fd = open (ptrace_scope_setting_file, O_RDONLY, 0);
1841    if (fd >= 0 && (read (fd, &ptrace_scope, 1) == 1) && (ptrace_scope != '0')) {
1842       fprintf (stderr,
1843                "Note: your kernel restricts ptrace invoker using %s\n"
1844                "vgdb will only be able to attach to a Valgrind process\n"
1845                "blocked in a system call *after* an initial successful attach\n",
1846                ptrace_scope_setting_file);
1847    } else if (ptrace_scope == 'X') {
1848       DEBUG (1, 
1849              "PR_SET_PTRACER defined"
1850              " but could not determine ptrace scope from %s\n",
1851              ptrace_scope_setting_file);
1852    }
1853    if (fd >= 0)
1854       close (fd);
1855 #  endif
1856
1857 #  ifndef PTRACEINVOKER
1858    fprintf(stderr, 
1859            "Note: ptrace invoker not implemented\n"
1860            "For more info: read user manual section"
1861            " 'Limitations of the Valgrind gdbserver'\n");
1862 #  endif
1863 }
1864
1865 static
1866 void usage(void)
1867 {
1868    fprintf(stderr,
1869 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
1870 "vgdb (valgrind gdb) has two usages\n"
1871 "  1. standalone to send monitor commands to a Valgrind gdbserver.\n"
1872 "     The OPTION(s) must be followed by the command to send\n"
1873 "     To send more than one command, separate the commands with -c\n"
1874 "  2. relay application between gdb and a Valgrind gdbserver.\n"
1875 "     Only OPTION(s) can be given.\n"
1876 "\n"
1877 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
1878 "             [--max-invoke-ms=<number>] [--wait=<number>] [-d] [-D] [-l]\n"
1879 "  --pid arg must be given if multiple Valgrind gdbservers are found.\n"
1880 "  --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
1881 "      if you want to change the default prefix for the FIFOs communication\n"
1882 "      between the Valgrind gdbserver and vgdb.\n"
1883 "  --wait arg tells vgdb to check during the specified number\n"
1884 "      of seconds if a Valgrind gdbserver can be found.\n"
1885 "  --max-invoke-ms gives the nr of milli-seconds after which vgdb will force\n"
1886 "      the invocation of the Valgrind gdbserver (if the Valgrind process\n"
1887 "           is blocked in a system call).\n"
1888 "  -d  arg tells to show debug info. Multiple -d args for more debug info\n"
1889 "  -D  arg tells to show shared mem status and then exit.\n"
1890 "  -l  arg tells to show the list of running Valgrind gdbserver and then exit.\n"
1891 "\n"
1892 "  -h --help shows this message\n"
1893 "  To get help from the Valgrind gdbserver, use vgdb help\n"
1894 "\n"
1895            );
1896    ptrace_restrictions();  
1897 }
1898
1899 /* If show_list, shows the list of Valgrind processes with gdbserver activated.
1900                  and then exits.
1901
1902    else if arg_pid == -1, waits maximum check_trials seconds to discover
1903    a valgrind pid appearing.
1904
1905    Otherwise verify arg_pid is valid and corresponds to a Valgrind process
1906    with gdbserver activated.
1907
1908    Returns the pid to work with
1909    or exits in case of error (e.g. no pid found corresponding to arg_pid */
1910
1911 static
1912 int search_arg_pid(int arg_pid, int check_trials, Bool show_list)
1913 {
1914    int i;
1915    int pid = -1;
1916
1917    if (arg_pid == 0 || arg_pid < -1) {
1918       fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
1919       exit (1);
1920    } else {
1921       /* search for a matching named fifo. 
1922          If we have been given a pid, we will check that the matching FIFO is
1923          there (or wait the nr of check_trials for this to appear).
1924          If no pid has been given, then if we find only one FIFO,
1925          we will use this to build the pid to use.
1926          If we find multiple processes with valid FIFO, we report them and will
1927          exit with an error. */
1928       DIR *vgdb_dir;
1929       char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
1930       struct dirent *f;
1931       int is;
1932       int nr_valid_pid = 0;
1933       const char *suffix = "-from-vgdb-to-"; /* followed by pid */
1934       char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
1935       
1936       strcpy (vgdb_format, vgdb_prefix);
1937       strcat (vgdb_format, suffix);
1938       
1939       strcpy (vgdb_dir_name, vgdb_prefix);
1940       
1941       for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
1942          if (vgdb_dir_name[is] == '/') {
1943             vgdb_dir_name[is+1] = '\0';
1944             break;
1945          }
1946       if (strlen(vgdb_dir_name) == 0)
1947          strcpy (vgdb_dir_name, "./");
1948
1949       DEBUG(1, "searching pid in directory %s format %s\n", 
1950             vgdb_dir_name, vgdb_format);
1951
1952       /* try to find FIFOs with valid pid.
1953          On exit of the loop, pid is set to:
1954          the last pid found if show_list (or -1 if no process was listed)
1955          -1 if no FIFOs matching a running process is found
1956          -2 if multiple FIFOs of running processes are found
1957          otherwise it is set to the (only) pid found that can be debugged
1958       */
1959       for (i = 0; i < check_trials; i++) {
1960          DEBUG(1, "check_trial %d \n", i);
1961          if (i > 0)
1962            /* wait one second before checking again */
1963            sleep(1);
1964
1965          vgdb_dir = opendir (vgdb_dir_name);
1966          if (vgdb_dir == NULL)
1967             XERROR (errno, 
1968                     "vgdb error: opening directory %s searching vgdb fifo\n", 
1969                     vgdb_dir_name);
1970       
1971          errno = 0; /* avoid complain if vgdb_dir is empty */
1972          while ((f = readdir (vgdb_dir))) {
1973             struct stat st;
1974             char pathname[strlen(vgdb_dir_name) + strlen(f->d_name)];
1975             char *wrongpid;
1976             int newpid;
1977
1978             strcpy (pathname, vgdb_dir_name);
1979             strcat (pathname, f->d_name);
1980             DEBUG(3, "trying %s\n", pathname);
1981             if (stat (pathname, &st) != 0) {
1982                if (debuglevel >= 3)
1983                   ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n", 
1984                          pathname);
1985             } else if (S_ISFIFO (st.st_mode)) {
1986                DEBUG(3, "trying %s\n", pathname);
1987                if (strncmp (pathname, vgdb_format, 
1988                             strlen (vgdb_format)) == 0) {
1989                   newpid = strtol(pathname + strlen (vgdb_format), 
1990                                   &wrongpid, 10);
1991                   if (*wrongpid == '\0' && newpid > 0 
1992                       && kill (newpid, 0) == 0) {
1993                      nr_valid_pid++;
1994                      if (show_list) {
1995                         report_pid (newpid);
1996                         pid = newpid;
1997                      } else if (arg_pid != -1) {
1998                         if (arg_pid == newpid) {
1999                            pid = newpid;
2000                         }
2001                      } else if (nr_valid_pid > 1) {
2002                         if (nr_valid_pid == 2) {
2003                            fprintf 
2004                               (stderr, 
2005                                "no --pid= arg given"
2006                                " and multiple valgrind pids found:\n");
2007                            report_pid (pid);
2008                         }
2009                         pid = -2;
2010                         report_pid (newpid);
2011                      } else {
2012                         pid = newpid;
2013                      }
2014                   }
2015                }
2016             }
2017             errno = 0; /* avoid complain if at the end of vgdb_dir */
2018          }
2019          if (f == NULL && errno != 0)
2020             XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n", 
2021                     vgdb_dir_name);
2022
2023          closedir (vgdb_dir);
2024          if (pid != -1)
2025             break;
2026       }
2027
2028       free (vgdb_dir_name);
2029       free (vgdb_format);
2030    }
2031    
2032    if (show_list) {
2033       exit (1);
2034    } else if (pid == -1) {
2035       if (arg_pid == -1)
2036          fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
2037       else
2038          fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n", 
2039                   arg_pid);
2040       exit (1);
2041    }
2042    else if (pid == -2) {
2043       /* no arg_pid given, multiple FIFOs found */
2044       exit (1);
2045    }
2046    else {
2047       return pid;
2048    }
2049 }
2050
2051 /* return true if the numeric value of an option of the 
2052    form --xxxxxxxxx=<number> could properly be extracted
2053    from arg. If True is returned, *value contains the
2054    extracted value.*/
2055 static
2056 Bool numeric_val(char* arg, int *value)
2057 {
2058    const char *eq_pos = strchr(arg, '=');
2059    char *wrong;
2060
2061    if (eq_pos == NULL)
2062       return False;
2063
2064    *value = strtol(eq_pos+1, &wrong, 10);
2065    if (*wrong)
2066       return False;
2067
2068    return True;
2069 }
2070
2071 /* true if arg matches the provided option */
2072 static
2073 Bool is_opt(char* arg, char *option)
2074 {
2075    int option_len = strlen(option);
2076    if (option[option_len-1] == '=')
2077       return (0 == strncmp(option, arg, option_len));
2078    else
2079       return (0 == strcmp(option, arg));
2080 }
2081
2082 /* Parse command lines options. If error(s), exits.
2083    Otherwise returns the options in *p_... args.
2084    commands must be big enough for the commands extracted from argv.
2085    On return, *p_last_command gives the position in commands where
2086    the last command has been allocated (using vmalloc). */
2087 static
2088 void parse_options(int argc, char** argv,
2089                    Bool *p_show_shared_mem,
2090                    Bool *p_show_list,
2091                    int *p_arg_pid,
2092                    int *p_check_trials,
2093                    int *p_last_command,
2094                    char *commands[])
2095 {
2096    Bool show_shared_mem = False;
2097    Bool show_list = False;
2098    int arg_pid = -1;
2099    int check_trials = 1;
2100    int last_command = -1;
2101
2102    int i;
2103    int arg_errors = 0;
2104
2105    for (i = 1; i < argc; i++) {
2106       if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
2107          usage();
2108          exit(0);
2109       } else if (is_opt(argv[i], "-d")) {
2110          debuglevel++;
2111       } else if (is_opt(argv[i], "-D")) {
2112          show_shared_mem = True;
2113       } else if (is_opt(argv[i], "-l")) {
2114          show_list = True;
2115       } else if (is_opt(argv[i], "--pid=")) {
2116          int newpid;
2117          if (!numeric_val(argv[i], &newpid)) {
2118             fprintf (stderr, "invalid pid argument %s\n", argv[i]);
2119             arg_errors++;
2120          } else if (arg_pid != -1) {
2121             fprintf (stderr, "multiple pid arguments given\n");
2122             arg_errors++;
2123          } else {
2124             arg_pid = newpid;
2125          }
2126       } else if (is_opt(argv[i], "--wait=")) {
2127          if (!numeric_val(argv[i], &check_trials)) {
2128             fprintf (stderr, "invalid wait argument %s\n", argv[i]);
2129             arg_errors++;
2130          }
2131       } else if (is_opt(argv[i], "--max-invoke-ms=")) {
2132          if (!numeric_val(argv[i], &max_invoke_ms)) {
2133             fprintf (stderr, "invalid max-invoke-ms argument %s\n", argv[i]);
2134             arg_errors++;
2135          }
2136       } else if (is_opt(argv[i], "--vgdb-prefix=")) {
2137          vgdb_prefix = argv[i] + 14;
2138       } else if (is_opt(argv[i], "-c")) {
2139          last_command++;
2140          commands[last_command] = vmalloc (1);
2141          commands[last_command][0] = '\0';
2142       } else if (0 == strncmp(argv[i], "-", 1)) {
2143          fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
2144          arg_errors++;
2145       } else {
2146          int len;
2147          if (last_command == -1) {
2148             /* only one command, no -c command indicator */
2149             last_command++;
2150             commands[last_command] = vmalloc (1);
2151             commands[last_command][0] = '\0';
2152          }
2153          len = strlen(commands[last_command]);
2154          commands[last_command] = vrealloc (commands[last_command], 
2155                                             len + 1 + strlen(argv[i]) + 1);
2156          if (len > 0)
2157             strcat (commands[last_command], " ");
2158          strcat (commands[last_command], argv[i]);
2159          if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
2160             fprintf (stderr, "command %s too long\n", commands[last_command]);
2161             arg_errors++;
2162          }
2163             
2164       }
2165    }
2166
2167    if (isatty(0) 
2168        && !show_shared_mem 
2169        && !show_list
2170        && last_command == -1) {
2171       arg_errors++;
2172       fprintf (stderr, 
2173                "Using vgdb standalone implies to give -D or -l or a COMMAND\n");
2174    }
2175
2176    if (show_shared_mem && show_list) {
2177       arg_errors++;
2178       fprintf (stderr,
2179                "Can't use both -D and -l options\n");
2180    }
2181
2182    if (show_list && arg_pid != -1) {
2183       arg_errors++;
2184       fprintf (stderr,
2185                "Can't use both --pid and -l options\n");
2186    }
2187
2188    if (arg_errors > 0) {
2189       fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
2190       exit(1);
2191    }
2192
2193    *p_show_shared_mem = show_shared_mem;
2194    *p_show_list = show_list;
2195    *p_arg_pid = arg_pid;
2196    *p_check_trials = check_trials;
2197    *p_last_command = last_command;
2198 }
2199
2200 int main(int argc, char** argv)
2201 {
2202    int i;
2203    int pid;
2204
2205    Bool show_shared_mem;
2206    Bool show_list;
2207    int arg_pid;
2208    int check_trials;
2209    int last_command;
2210    char *commands[argc]; // we will never have more commands than args.
2211
2212    parse_options(argc, argv,
2213                  &show_shared_mem,
2214                  &show_list,
2215                  &arg_pid,
2216                  &check_trials,
2217                  &last_command,
2218                  commands);
2219   
2220    /* when we are working as a relay for gdb, handle some signals by
2221       only reporting them (according to debug level). Also handle these
2222       when ptrace will be used: vgdb must clean up the ptrace effect before
2223       dying. */
2224    if (max_invoke_ms > 0 || last_command == -1)
2225       install_handlers();
2226
2227    pid = search_arg_pid (arg_pid, check_trials, show_list);
2228
2229    prepare_fifos_and_shared_mem(pid);
2230
2231    if (show_shared_mem) {
2232       fprintf(stderr, 
2233               "vgdb %d "
2234               "written_by_vgdb %d "
2235               "seen_by_valgrind %d\n"
2236               "vgdb pid %d\n",
2237               VS_vgdb_pid,
2238               VS_written_by_vgdb,
2239               VS_seen_by_valgrind,
2240               VS_vgdb_pid);
2241       exit (0);
2242    }
2243
2244    if (last_command >= 0) {
2245       standalone_send_commands(pid, last_command, commands);
2246    } else {
2247       gdb_relay(pid);
2248    }
2249       
2250
2251    free (from_gdb_to_pid);
2252    free (to_gdb_from_pid);
2253    free (shared_mem);
2254
2255    for (i = 0; i <= last_command; i++)
2256       free (commands[i]);
2257    return 0;
2258 }
2259 /*--------------------------------------------------------------------*/
2260 /*--- Relay between gdb and gdbserver embedded in valgrind  vgdb.c ---*/
2261 /*--------------------------------------------------------------------*/
2262
2263 /*
2264    This file is part of Valgrind, a dynamic binary instrumentation
2265    framework.
2266
2267    Copyright (C) 2011 Philippe Waroquiers
2268
2269    This program is free software; you can redistribute it and/or
2270    modify it under the terms of the GNU General Public License as
2271    published by the Free Software Foundation; either version 2 of the
2272    License, or (at your option) any later version.
2273
2274    This program is distributed in the hope that it will be useful, but
2275    WITHOUT ANY WARRANTY; without even the implied warranty of
2276    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
2277    General Public License for more details.
2278
2279    You should have received a copy of the GNU General Public License
2280    along with this program; if not, write to the Free Software
2281    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
2282    02111-1307, USA.
2283
2284    The GNU General Public License is contained in the file COPYING.
2285 */
2286 #include "pub_core_basics.h"
2287 #include "pub_core_vki.h"
2288 #include "pub_core_libcsetjmp.h"
2289 #include "pub_core_threadstate.h"
2290 #include "pub_core_gdbserver.h"
2291
2292 #include <unistd.h>
2293 #include <string.h>
2294 #include <poll.h>
2295 #include <pthread.h>
2296 #include <stdlib.h>
2297 #include <stdio.h>
2298 #include <fcntl.h>
2299 #include <dirent.h>
2300 #include <sys/stat.h>
2301 #include <sys/time.h>
2302 #include <errno.h>
2303 #include <signal.h>
2304 #include <sys/mman.h>
2305 #include <sys/ptrace.h>
2306 #include <sys/wait.h>
2307 #include "assert.h"
2308 #include <sys/user.h>
2309
2310 #  if defined(VGO_linux)
2311 #include <sys/prctl.h>
2312 #  endif
2313
2314 /* vgdb has two usages:
2315    1. relay application between gdb and the gdbserver embedded in valgrind.
2316    2. standalone to send monitor commands to a running valgrind-ified process
2317
2318    It is made of a main program which reads arguments.  If no
2319    arguments are given or only --pid and --vgdb-prefix, then usage 1 is
2320    assumed.
2321    
2322    As relay application, vgdb reads bytes from gdb on stdin and
2323    writes these bytes to valgrind.  Bytes read from valgrind are
2324    written to gdb on stdout.  Read/Write from/to valgrind is done
2325    using FIFOs.  There is one thread reading from stdin, writing to
2326    valgrind on a FIFO.  There is one thread reading from valgrind on a
2327    FIFO, writing to gdb on stdout
2328
2329    As a standalone utility, vgdb builds command packets to write to valgrind,
2330    sends it and reads the reply. The same two threads are used to write/read.
2331    Once all the commands are sent and their replies received, vgdb will exit.
2332    
2333 */
2334
2335 /* define PTRACEINVOKER to compile the ptrace related code
2336    which ensures a valgrind process blocked in a system call
2337    can be "waken up". PTRACEINVOKER implies some architecture
2338    specific code and/or some OS specific code. */
2339 #if defined(VGA_arm) || defined(VGA_x86) || defined(VGA_amd64) \
2340     || defined(VGA_ppc32) || defined(VGA_ppc64) || defined(VGA_s390x)
2341 #define PTRACEINVOKER
2342 #else
2343 I_die_here : (PTRACEINVOKER) architecture missing in vgdb.c
2344 #endif
2345
2346 /* Some darwin specific stuff is needed as ptrace is not
2347    fully supported on MacOS. Till we find someone courageous
2348    having access to Darwin, there is no PTRACEINVOKER. */
2349 #if defined(VGO_darwin)
2350 #undef PTRACEINVOKER
2351 #endif
2352
2353 static int debuglevel;
2354 static struct timeval dbgtv;
2355 /* if level <= debuglevel, print timestamp, then print provided by debug info */
2356 #define DEBUG(level, ...) (level <= debuglevel ?                        \
2357                            gettimeofday(&dbgtv, NULL),                  \
2358                            fprintf(stderr, "%ld.%6.6ld ",               \
2359                                    (long int)dbgtv.tv_sec,              \
2360                                    (long int)dbgtv.tv_usec),            \
2361                            fprintf(stderr, __VA_ARGS__),fflush(stderr)  \
2362                            : 0)
2363
2364 /* same as DEBUG but does not print time stamp info */
2365 #define PDEBUG(level, ...) (level <= debuglevel ?                       \
2366                             fprintf(stderr, __VA_ARGS__),fflush(stderr) \
2367                             : 0)
2368
2369 /* if errno != 0, 
2370    report the errno and fprintf the ... varargs on stderr. */
2371 #define ERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
2372                            fprintf(stderr, __VA_ARGS__),                \
2373                            fflush(stderr))
2374 /* same as ERROR, but also exits with status 1 */
2375 #define XERROR(errno, ...) ((errno == 0 ? 0 : perror("syscall failed")), \
2376                             fprintf(stderr, __VA_ARGS__),                \
2377                             fflush(stderr),                              \
2378                             exit(1))
2379
2380 static char *vgdb_prefix = "/tmp/vgdb-pipe";
2381
2382 /* Will be set to True when any condition indicating we have to shutdown
2383    is encountered. */
2384 static Bool shutting_down = False;
2385
2386 static VgdbShared32 *shared32;
2387 static VgdbShared64 *shared64;
2388 #define VS_written_by_vgdb (shared32 != NULL ?        \
2389                             shared32->written_by_vgdb \
2390                             : shared64->written_by_vgdb)
2391 #define VS_seen_by_valgrind (shared32 != NULL ?         \
2392                              shared32->seen_by_valgrind \
2393                              : shared64->seen_by_valgrind)
2394
2395 #define VS_vgdb_pid (shared32 != NULL ? shared32->vgdb_pid : shared64->vgdb_pid)
2396
2397 /* Calls malloc (size). Exits if memory can't be allocated. */
2398 static
2399 void *vmalloc(size_t size)
2400 {
2401    void * mem = malloc(size);
2402    if (mem == NULL)
2403       XERROR (errno, "can't allocate memory\n");
2404    return mem;
2405 }
2406
2407 /* Calls realloc (size). Exits if memory can't be allocated. */
2408 static
2409 void *vrealloc(void *ptr,size_t size)
2410 {
2411    void * mem = realloc(ptr, size);
2412    if (mem == NULL)
2413       XERROR (errno, "can't reallocate memory\n");
2414    return mem;
2415 }
2416
2417 /* add nrw to the written_by_vgdb field of shared32 or shared64 */ 
2418 static
2419 void add_written(int nrw)
2420 {
2421    if (shared32 != NULL) 
2422       shared32->written_by_vgdb += nrw;
2423    else if (shared64 != NULL) 
2424       shared64->written_by_vgdb += nrw;
2425    else
2426       assert(0);
2427 }
2428
2429 static int shared_mem_fd = -1;
2430 static
2431 void map_vgdbshared (char* shared_mem)
2432 {
2433    struct stat fdstat;
2434    void **s;
2435    shared_mem_fd = open(shared_mem, O_RDWR);
2436    /* shared_mem_fd will not be closed till vgdb exits. */
2437
2438    if (shared_mem_fd == -1)
2439       XERROR (errno, "error opening %s shared memory file\n", shared_mem);
2440
2441    if (fstat(shared_mem_fd, &fdstat) != 0)
2442       XERROR (errno, "fstat");
2443
2444    if (fdstat.st_size == sizeof(VgdbShared64))
2445       s = (void*) &shared64;
2446    else if (fdstat.st_size == sizeof(VgdbShared32))
2447       s = (void*) &shared32;
2448    else
2449 #if VEX_HOST_WORDSIZE == 8
2450       XERROR (0,
2451               "error size shared memory file %s.\n"
2452               "expecting size %d (64bits) or %d (32bits) got %ld.\n",
2453               shared_mem,
2454               (int) sizeof(VgdbShared64), (int) sizeof(VgdbShared32), 
2455               (long int)fdstat.st_size);
2456 #elif VEX_HOST_WORDSIZE == 4
2457       XERROR (0,
2458               "error size shared memory file %s.\n"
2459               "expecting size %d (32bits) got %ld.\n",
2460               shared_mem,
2461               (int) sizeof(VgdbShared32), 
2462               fdstat.st_size);
2463 #else
2464 # error "unexpected wordsize"
2465 #endif
2466
2467 #if VEX_HOST_WORDSIZE == 4
2468    if (shared64 != NULL)
2469       XERROR (0, "cannot use 32 bits vgdb with a 64bits valgrind process\n");
2470    /* But we can use a 64 bits vgdb with a 32 bits valgrind */
2471 #endif
2472
2473    *s = (void*) mmap (NULL, fdstat.st_size, 
2474                       PROT_READ|PROT_WRITE, MAP_SHARED, 
2475                       shared_mem_fd, 0);
2476
2477    if (*s == (void *) -1)
2478       XERROR (errno, "error mmap shared memory file %s\n", shared_mem);
2479
2480 }
2481
2482 #if VEX_HOST_WORDSIZE == 8
2483 typedef Addr64 CORE_ADDR;
2484 typedef Addr64 PTRACE_XFER_TYPE;
2485 typedef void* PTRACE_ARG3_TYPE;
2486 #elif VEX_HOST_WORDSIZE == 4
2487 typedef Addr32 CORE_ADDR;
2488 typedef Addr32 PTRACE_XFER_TYPE;
2489 typedef void* PTRACE_ARG3_TYPE;
2490 #else
2491 # error "unexpected wordsize"
2492 #endif
2493
2494 static Bool pid_of_save_regs_continued = False;
2495 // True if we have continued pid_of_save_regs after PTRACE_ATTACH
2496
2497 static Bool dying = False;
2498 // Set to True when loss of connection indicating that the Valgrind
2499 // process is dying.
2500
2501 /* To be called when connection with valgrind is lost.  In case we
2502 have lost the connection, it means that Valgrind has closed the
2503 connection and is busy exiting. We can't and don't have to stop it in
2504 this case. */
2505 static
2506 void valgrind_dying(void)
2507 {
2508    pid_of_save_regs_continued = False;
2509    dying = True;
2510 }
2511
2512
2513 #ifdef PTRACEINVOKER
2514 /* ptrace_(read|write)_memory are modified extracts of linux-low.c
2515    from gdb 6.6. Copyrighted FSF */
2516 /* Copy LEN bytes from inferior's memory starting at MEMADDR
2517    to debugger memory starting at MYADDR.  */
2518
2519 static
2520 int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
2521                         unsigned char *myaddr, int len)
2522 {
2523    register int i;
2524    /* Round starting address down to longword boundary.  */
2525    register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2526    /* Round ending address up; get number of longwords that makes.  */
2527    register int count
2528       = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
2529       / sizeof (PTRACE_XFER_TYPE);
2530    /* Allocate buffer of that many longwords.  */
2531    register PTRACE_XFER_TYPE *buffer
2532       = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2533    
2534    /* Read all the longwords */
2535    for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
2536       errno = 0;
2537       buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid, 
2538                           (PTRACE_ARG3_TYPE) addr, 0);
2539       if (errno)
2540          return errno;
2541    }
2542    
2543    /* Copy appropriate bytes out of the buffer.  */
2544    memcpy (myaddr, 
2545            (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
2546    
2547    return 0;
2548 }
2549
2550 /* Copy LEN bytes of data from debugger memory at MYADDR
2551    to inferior's memory at MEMADDR.
2552    On failure (cannot write the inferior)
2553    returns the value of errno.  */
2554
2555 static
2556 int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr, 
2557                          const unsigned char *myaddr, int len)
2558 {
2559    register int i;
2560    /* Round starting address down to longword boundary.  */
2561    register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
2562    /* Round ending address up; get number of longwords that makes.  */
2563    register int count
2564       = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1) 
2565       / sizeof (PTRACE_XFER_TYPE);
2566    /* Allocate buffer of that many longwords.  */
2567    register PTRACE_XFER_TYPE *buffer 
2568       = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
2569    
2570    if (debuglevel >= 1) {
2571       DEBUG (1, "Writing ");
2572       for (i = 0; i < len; i++)
2573          PDEBUG (1, "%02x", (unsigned)myaddr[i]);
2574       PDEBUG(1, " to %p\n", (void *) memaddr);
2575    }
2576    
2577    /* Fill start and end extra bytes of buffer with existing memory data.  */
2578    
2579    buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
2580                        (PTRACE_ARG3_TYPE) addr, 0);
2581    
2582    if (count > 1) {
2583       buffer[count - 1]
2584          = ptrace (PTRACE_PEEKTEXT, inferior_pid,
2585                    (PTRACE_ARG3_TYPE) (addr + (count - 1)
2586                                        * sizeof (PTRACE_XFER_TYPE)),
2587                    0);
2588    }
2589    
2590    /* Copy data to be written over corresponding part of buffer */
2591    
2592    memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), 
2593            myaddr, len);
2594    
2595    /* Write the entire buffer.  */
2596    
2597    for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
2598       errno = 0;
2599       ptrace (PTRACE_POKETEXT, inferior_pid, 
2600               (PTRACE_ARG3_TYPE) addr, buffer[i]);
2601       if (errno)
2602          return errno;
2603    }
2604    
2605    return 0;
2606 }
2607
2608 /* subset of VG_(threads) needed for vgdb ptrace.
2609    This is initialized when process is attached. */
2610 typedef struct {
2611    ThreadStatus status;
2612    Int lwpid;
2613 }
2614 VgdbThreadState;
2615 static VgdbThreadState vgdb_threads[VG_N_THREADS];
2616
2617 static const
2618 HChar* name_of_ThreadStatus ( ThreadStatus status )
2619 {
2620    switch (status) {
2621    case VgTs_Empty:     return "VgTs_Empty";
2622    case VgTs_Init:      return "VgTs_Init";
2623    case VgTs_Runnable:  return "VgTs_Runnable";
2624    case VgTs_WaitSys:   return "VgTs_WaitSys";
2625    case VgTs_Yielding:  return "VgTs_Yielding";
2626    case VgTs_Zombie:    return "VgTs_Zombie";
2627    default:             return "VgTs_???";
2628   }
2629 }
2630
2631 static 
2632 char *status_image (int status)
2633 {
2634    static char result[256];
2635    int sz = 0;
2636 #define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
2637   
2638    result[0] = 0;
2639
2640    if (WIFEXITED(status))
2641       APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
2642    
2643    if (WIFSIGNALED(status)) {
2644       APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
2645       if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
2646    }
2647
2648    if (WIFSTOPPED(status))
2649       APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
2650
2651    if (WIFCONTINUED(status))
2652       APPEND ("WIFCONTINUED ");
2653
2654    return result;
2655 #undef APPEND
2656 }
2657
2658 /* Wait till the process pid is reported as stopped with signal_expected.
2659    If other signal(s) than signal_expected are received, waitstopped
2660    will pass them to pid, waiting for signal_expected to stop pid.
2661    Returns True when process is in stopped state with signal_expected.
2662    Returns False if a problem was encountered while waiting for pid
2663    to be stopped.
2664
2665    If pid is reported as being dead/exited, waitstopped will return False.
2666 */
2667 static
2668 Bool waitstopped (int pid, int signal_expected, char *msg)
2669 {
2670    pid_t p;
2671    int status = 0;
2672    int signal_received;
2673    int res;
2674
2675    while (1) {
2676       DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
2677             msg, signal_expected);
2678       p = waitpid(pid, &status, __WALL);
2679       DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p, 
2680             status, status_image (status));
2681       if (p != pid) {
2682          ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n", 
2683                msg, pid, p, status, status_image (status));
2684          return False;
2685       }
2686
2687       if (WIFEXITED(status)) {
2688          shutting_down = True;
2689          return False;
2690       }
2691
2692       assert (WIFSTOPPED(status));
2693       signal_received = WSTOPSIG(status);
2694       if (signal_received == signal_expected)
2695          break;
2696
2697       /* pid received a signal which is not the signal we are waiting for.
2698          We continue pid, transmitting this signal. */
2699       DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
2700       res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
2701       if (res != 0) {
2702          ERROR(errno, "waitstopped PTRACE_CONT\n");
2703          return False;
2704       }
2705    }
2706
2707    return True;
2708 }
2709
2710 /* Stops the given pid, wait for the process to be stopped.
2711    Returns True if succesful, False otherwise.
2712    msg is used in tracing and error reporting. */
2713 static
2714 Bool stop (int pid, char *msg)
2715 {
2716    long res;
2717
2718    DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
2719    res = kill (pid, SIGSTOP);
2720    if (res != 0) {
2721       ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
2722       return False;
2723    }
2724          
2725    return waitstopped (pid, SIGSTOP, msg);
2726
2727 }
2728
2729 /* Attaches to given pid, wait for the process to be stopped.
2730    Returns True if succesful, False otherwise.
2731    msg is used in tracing and error reporting. */
2732 static
2733 Bool attach (int pid, char *msg)
2734 {
2735    long res;
2736
2737    DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
2738    res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
2739    if (res != 0) {
2740       ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
2741       return False;
2742    }
2743
2744    return waitstopped(pid, SIGSTOP, msg);
2745 }
2746
2747 /* once we are attached to the pid, get the list of threads and stop 
2748    them all.
2749    Returns True if all threads properly suspended, False otherwise. */
2750 static
2751 Bool acquire_and_suspend_threads(int pid)
2752 {
2753    int i;
2754    int rw;
2755    Bool pid_found = False;
2756    Addr vgt;
2757    int sz_tst;
2758    int off_status;
2759    int off_lwpid;
2760    int nr_live_threads = 0;
2761
2762    if (shared32 != NULL) {
2763       vgt = shared32->threads;
2764       sz_tst = shared32->sizeof_ThreadState;
2765       off_status = shared32->offset_status;
2766       off_lwpid = shared32->offset_lwpid;
2767    }
2768    else if (shared64 != NULL) {
2769       vgt = shared64->threads;
2770       sz_tst = shared64->sizeof_ThreadState;
2771       off_status = shared64->offset_status;
2772       off_lwpid = shared64->offset_lwpid;
2773    } else {
2774       assert (0);
2775    }
2776
2777    /* note: the entry 0 is unused */
2778    for (i = 1; i < VG_N_THREADS; i++) {
2779       vgt += sz_tst;
2780       rw = ptrace_read_memory(pid, vgt+off_status,
2781                               (unsigned char *)&(vgdb_threads[i].status),
2782                               sizeof(ThreadStatus));
2783       if (rw != 0) {
2784          ERROR(rw, "status ptrace_read_memory\n");
2785          return False;
2786       }
2787       
2788       rw = ptrace_read_memory(pid, vgt+off_lwpid,
2789                               (unsigned char *)&(vgdb_threads[i].lwpid),
2790                               sizeof(Int));
2791       if (rw != 0) {
2792          ERROR(rw, "lwpid ptrace_read_memory\n");
2793          return False;
2794       }
2795       
2796       if (vgdb_threads[i].status != VgTs_Empty) {
2797          DEBUG(1, "found tid %d status %s lwpid %d\n",
2798                i, name_of_ThreadStatus(vgdb_threads[i].status),
2799                vgdb_threads[i].lwpid);
2800          nr_live_threads++;
2801          if (vgdb_threads[i].lwpid <= 1) {
2802             if (vgdb_threads[i].lwpid == 0 
2803                 && vgdb_threads[i].status == VgTs_Init) {
2804                DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
2805                      i, name_of_ThreadStatus(vgdb_threads[i].status),
2806                      vgdb_threads[i].lwpid);
2807             } else {
2808                ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
2809                      i, name_of_ThreadStatus(vgdb_threads[i].status),
2810                      vgdb_threads[i].lwpid);
2811             }
2812             /* in case we have a VtTs_Init thread with lwpid not yet set,
2813                we try again later. */
2814             return False;
2815          }
2816          if (vgdb_threads[i].lwpid == pid) {
2817             assert (!pid_found);
2818             assert (i == 1);
2819             pid_found = True;
2820          } else {
2821             if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
2822                  ERROR(0, "ERROR attach pid %d tid %d\n", 
2823                        vgdb_threads[i].lwpid, i);
2824                return False;
2825             }
2826          }
2827       }
2828    }
2829    /* If we found no thread, it means the process is stopping, and
2830       we better do not force anything to happen during that. */
2831    if (nr_live_threads > 0)
2832       return True;
2833    else
2834       return False;
2835 }
2836
2837 static
2838 void detach_from_all_threads(int pid)
2839 {
2840    int i;
2841    long res;
2842    Bool pid_found = False;
2843
2844    /* detach from all the threads  */
2845    for (i = 1; i < VG_N_THREADS; i++) {
2846       if (vgdb_threads[i].status != VgTs_Empty) {
2847          if (vgdb_threads[i].status == VgTs_Init
2848              && vgdb_threads[i].lwpid == 0) {
2849             DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
2850                   vgdb_threads[i].lwpid, i, 
2851                   name_of_ThreadStatus (vgdb_threads[i].status));
2852          } else {
2853             if (vgdb_threads[i].lwpid == pid) {
2854                assert (!pid_found);
2855                pid_found = True;
2856             }
2857             DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
2858                   vgdb_threads[i].lwpid, i, 
2859                   name_of_ThreadStatus (vgdb_threads[i].status));
2860             res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
2861             if (res != 0) {
2862                ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n", 
2863                      vgdb_threads[i].lwpid, i,
2864                      name_of_ThreadStatus (vgdb_threads[i].status),
2865                      res);
2866             }
2867          }
2868       }
2869    }
2870
2871    if (!pid_found && pid) {
2872       /* No threads are live. Process is busy stopping.
2873          We need to detach from pid explicitely. */
2874       DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
2875       res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
2876       if (res != 0)
2877          ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
2878    }
2879 }
2880
2881 // if > 0, pid for which registers have to be restored.
2882 static int pid_of_save_regs = 0;
2883 static struct user user_save;
2884
2885 /* Get the registers from pid into regs.
2886    Returns True if all ok, otherwise False. */
2887 static
2888 Bool getregs (int pid, void *regs)
2889 {
2890 #  ifdef VGA_s390x
2891    char *pregs = (char *) regs;
2892    long offset;
2893    errno = 0;
2894    DEBUG(1, "getregs PTRACE_PEEKUSER(s)\n");
2895    for (offset = 0; offset < PT_ENDREGS; offset = offset + sizeof(long)) {
2896       *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
2897       if (errno != 0) {
2898          ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
2899          return False;
2900       }
2901    }
2902    return True;
2903 #  else
2904    // Platforms having GETREGS
2905    long res;
2906    DEBUG(1, "getregs PTRACE_GETREGS\n");
2907    res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
2908    if (res != 0) {
2909       ERROR(errno, "PTRACE_GETREGS %ld\n", res);
2910       return False;
2911    }
2912    return True;
2913 #  endif
2914 }
2915
2916 /* Set the registers of pid to regs.
2917    Returns True if all ok, otherwise False. */
2918 static
2919 Bool setregs (int pid, void *regs)
2920 {
2921 #  ifdef VGA_s390x
2922    char *pregs = (char *) regs;
2923    long offset;
2924    long res;
2925    errno = 0;
2926    DEBUG(1, "setregs PTRACE_POKEUSER(s)\n");
2927    for (offset = 0; offset < PT_ENDREGS; offset = offset + sizeof(long)) {
2928       res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
2929       if (errno != 0) {
2930          ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
2931          return False;
2932       }
2933    }
2934    return True;
2935 #  else
2936    // Platforms having SETREGS
2937    long res;
2938    DEBUG(1, "setregs PTRACE_SETREGS\n");
2939    res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
2940    if (res != 0) {
2941       ERROR(errno, "PTRACE_SETREGS %ld\n", res);
2942       return False;
2943    }
2944    return True;
2945 #  endif
2946 }
2947
2948 /* Restore the registers to the saved value, then detaches from all threads */
2949 static
2950 void restore_and_detach(int pid)
2951 {
2952    if (pid_of_save_regs) {
2953       /* In case the 'main pid' has been continued, we need to stop it
2954          before resetting the registers. */
2955       if (pid_of_save_regs_continued) {
2956          pid_of_save_regs_continued = False;
2957          if (!stop(pid_of_save_regs, "sigstop before reset regs"))
2958             DEBUG(0, "Could not sigstop before reset");
2959       }
2960
2961       DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
2962       if (!setregs(pid_of_save_regs, &user_save.regs)) {
2963          ERROR(errno, "setregs restore registers pid %d after cont\n",
2964                pid_of_save_regs);
2965       }
2966       pid_of_save_regs = 0;
2967    } else {
2968       DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
2969    }
2970    detach_from_all_threads(pid);
2971 }
2972
2973 /* Ensures that the gdbserver code is invoked by pid.
2974    If an error occurs, resets to the valgrind process
2975    to the state it has before being ptrace-d.
2976    Returns True if invoke successful, False otherwise.
2977 */
2978 static
2979 Bool invoke_gdbserver (int pid)
2980 {
2981    long res;
2982    Bool stopped;
2983    struct user user_mod;
2984    Addr sp;
2985    /* A specific int value is passed to invoke_gdbserver, to check
2986       everything goes according to the plan. */
2987    const int check = 0x8BADF00D; // ate bad food.
2988
2989    const Addr bad_return = 0;
2990    // A bad return address will be pushed on the stack.
2991    // The function invoke_gdbserver cannot return. If ever it returns, a NULL
2992    // address pushed on the stack should ensure this is detected.
2993
2994    /* Not yet attached. If problem, vgdb can abort,
2995       no cleanup needed.
2996
2997       On Ubuntu>= 10.10, a /proc setting can disable ptrace.
2998       So, Valgrind has to SET_PTRACER this vgdb. Once this
2999       is done, this vgdb can ptrace the valgrind process. */
3000
3001    DEBUG(1, "attach to 'main' pid %d\n", pid);
3002    if (!attach(pid, "attach main pid")) {
3003       ERROR(0, "error attach main pid %d\n", pid);
3004       return False;
3005    }
3006
3007    /* Now, we are attached. If problem, detach and return. */
3008
3009    if (!acquire_and_suspend_threads(pid)) {
3010       detach_from_all_threads(pid);
3011       /* if the pid does not exist anymore, we better stop */
3012       if (kill(pid, 0) != 0)
3013         XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
3014                 pid);
3015       return False;
3016    }
3017
3018    if (!getregs(pid, &user_mod.regs)) {
3019       detach_from_all_threads(pid);
3020       return False;
3021    }
3022    user_save = user_mod;
3023
3024 #if defined(VGA_x86)
3025    sp = user_mod.regs.esp;
3026 #elif defined(VGA_amd64)
3027    sp = user_mod.regs.rsp;
3028    if (shared32 != NULL) {
3029      /* 64bit vgdb speaking with a 32bit executable.
3030         To have system call restart properly, we need to sign extend rax.
3031         For more info:
3032         web search '[patch] Fix syscall restarts for amd64->i386 biarch'
3033         e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
3034      *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
3035      DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
3036            user_mod.regs.rax, user_save.regs.rax);
3037    }
3038 #elif defined(VGA_arm)
3039    sp = user_mod.regs.uregs[13];
3040 #elif defined(VGA_ppc32)
3041    sp = user_mod.regs.gpr[1];
3042 #elif defined(VGA_ppc64)
3043    sp = user_mod.regs.gpr[1];
3044 #elif defined(VGA_s390x)
3045    sp = user_mod.regs.gprs[15];
3046 #else
3047    I_die_here : (sp) architecture missing in vgdb.c
3048 #endif
3049
3050
3051    // the magic below is derived from spying what gdb sends to
3052    // the (classical) gdbserver when invoking a C function.
3053    if (shared32 != NULL) {
3054       // vgdb speaking with a 32bit executable.
3055 #if   defined(VGA_x86) || defined(VGA_amd64)
3056       const int regsize = 4;
3057       int rw;
3058       /* push check arg on the stack */
3059       sp = sp - regsize;
3060       DEBUG(1, "push check arg ptrace_write_memory\n");
3061       assert(regsize == sizeof(check));
3062       rw = ptrace_write_memory(pid, sp, 
3063                                (unsigned char *) &check, 
3064                                regsize);
3065       if (rw != 0) {
3066          ERROR(rw, "push check arg ptrace_write_memory");
3067          detach_from_all_threads(pid);
3068          return False;
3069       }
3070
3071       sp = sp - regsize;
3072       DEBUG(1, "push bad_return return address ptrace_write_memory\n");
3073       // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
3074       // are written.
3075       rw = ptrace_write_memory(pid, sp, 
3076                                (unsigned char *) &bad_return,
3077                                regsize);
3078       if (rw != 0) {
3079          ERROR(rw, "push bad_return return address ptrace_write_memory");
3080          detach_from_all_threads(pid);
3081          return False;
3082       }
3083 #if   defined(VGA_x86)
3084       /* set ebp, esp, eip and orig_eax to invoke gdbserver */
3085       // compiled in 32bits, speaking with a 32bits exe
3086       user_mod.regs.ebp = sp; // bp set to sp
3087       user_mod.regs.esp = sp;
3088       user_mod.regs.eip = shared32->invoke_gdbserver;
3089       user_mod.regs.orig_eax = -1L;
3090 #elif defined(VGA_amd64)
3091       /* set ebp, esp, eip and orig_eax to invoke gdbserver */
3092       // compiled in 64bits, speaking with a 32bits exe
3093       user_mod.regs.rbp = sp; // bp set to sp
3094       user_mod.regs.rsp = sp;
3095       user_mod.regs.rip = shared32->invoke_gdbserver;
3096       user_mod.regs.orig_rax = -1L;
3097 #else
3098       I_die_here : not x86 or amd64 in x86/amd64 section/
3099 #endif
3100
3101 #elif defined(VGA_ppc32) || defined(VGA_ppc64)
3102       user_mod.regs.nip = shared32->invoke_gdbserver;
3103       user_mod.regs.trap = -1L;
3104       /* put check arg in register 3 */
3105       user_mod.regs.gpr[3] = check;
3106       /* put NULL return address in Link Register */
3107       user_mod.regs.link = bad_return;
3108
3109 #elif defined(VGA_arm)
3110       /* put check arg in register 0 */
3111       user_mod.regs.uregs[0] = check;
3112       /* put NULL return address in Link Register */
3113       user_mod.regs.uregs[14] = bad_return;
3114       user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
3115
3116 #elif defined(VGA_s390x)
3117       XERROR(0, "(fn32) s390x has no 32bits implementation");
3118 #else
3119       I_die_here : architecture missing in vgdb.c
3120 #endif
3121       }
3122
3123    else if (shared64 != NULL) {
3124 #if defined(VGA_x86)
3125       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3126 #elif defined(VGA_amd64)
3127       // vgdb speaking with a 64 bit executable.
3128       const int regsize = 8;
3129       int rw;
3130       
3131       /* give check arg in rdi */
3132       user_mod.regs.rdi = check;
3133
3134       /* push return address on stack : return to breakaddr */
3135       sp = sp - regsize;
3136       DEBUG(1, "push bad_return return address ptrace_write_memory\n");
3137       rw = ptrace_write_memory(pid, sp, 
3138                                (unsigned char *) &bad_return,
3139                                sizeof(bad_return));
3140       if (rw != 0) {
3141          ERROR(rw, "push bad_return return address ptrace_write_memory");
3142          detach_from_all_threads(pid);
3143          return False;
3144       }
3145
3146       /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
3147       user_mod.regs.rbp = sp; // bp set to sp
3148       user_mod.regs.rsp = sp;
3149       user_mod.regs.rip = shared64->invoke_gdbserver;
3150       user_mod.regs.orig_rax = -1L;
3151
3152 #elif defined(VGA_arm)
3153       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3154 #elif defined(VGA_ppc32)
3155       assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
3156 #elif defined(VGA_ppc64)
3157       Addr64 func_addr;
3158       Addr64 toc_addr;
3159       int rw;
3160       rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
3161                               (unsigned char *)&func_addr,
3162                               sizeof(Addr64));
3163       if (rw != 0) {
3164          ERROR(rw, "ppc64 read func_addr\n");
3165          detach_from_all_threads(pid);
3166          return False;
3167       }
3168       rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
3169                               (unsigned char *)&toc_addr,
3170                               sizeof(Addr64));
3171       if (rw != 0) {
3172          ERROR(rw, "ppc64 read toc_addr\n");
3173          detach_from_all_threads(pid);
3174          return False;
3175       }
3176       // We are not pushing anything on the stack, so it is not
3177       // very clear why the sp has to be decreased, but it seems
3178       // needed. The ppc64 ABI might give some lights on this ?
3179       user_mod.regs.gpr[1] = sp - 220;
3180       user_mod.regs.gpr[2] = toc_addr;
3181       user_mod.regs.nip = func_addr;
3182       user_mod.regs.trap = -1L;
3183       /* put check arg in register 3 */
3184       user_mod.regs.gpr[3] = check;
3185       /* put bad_return return address in Link Register */
3186       user_mod.regs.link = bad_return;
3187 #elif defined(VGA_s390x)
3188       /* put check arg in register r2 */
3189       user_mod.regs.gprs[2] = check;
3190       /* bad_return Return address is in r14 */
3191       user_mod.regs.gprs[14] = bad_return;
3192       /* minimum stack frame */
3193       sp = sp - 160;
3194       user_mod.regs.gprs[15] = sp;
3195       /* set program counter */
3196       user_mod.regs.psw.addr = shared64->invoke_gdbserver;
3197 #else
3198       I_die_here: architecture missing in vgdb.c
3199 #endif
3200    }
3201    else {
3202       assert(0);
3203    }
3204    
3205    if (!setregs(pid, &user_mod.regs)) {
3206       detach_from_all_threads(pid);
3207       return False;
3208    }
3209    /* Now that we have modified the registers, we set
3210       pid_of_save_regs to indicate that restore_and_detach
3211       must restore the registers in case of cleanup. */
3212    pid_of_save_regs = pid;
3213    pid_of_save_regs_continued = False;
3214       
3215
3216    /* We PTRACE_CONT-inue pid. 
3217       Either gdbserver will be invoked directly (if all
3218       threads are interruptible) or gdbserver will be
3219       called soon by the scheduler. In the first case,
3220       pid will stop on the break inserted above when
3221       gdbserver returns. In the 2nd case, the break will
3222       be encountered directly. */
3223    DEBUG(1, "PTRACE_CONT to invoke\n");
3224    res = ptrace (PTRACE_CONT, pid, NULL, NULL);
3225    if (res != 0) {
3226       ERROR(errno, "PTRACE_CONT\n");
3227       restore_and_detach(pid);
3228       return False;
3229    }
3230    pid_of_save_regs_continued = True;
3231    
3232    stopped = waitstopped (pid, SIGTRAP,
3233                           "waitpid status after PTRACE_CONT to invoke");
3234    if (stopped) {
3235       /* Here pid has properly stopped on the break. */
3236       pid_of_save_regs_continued = False;
3237       restore_and_detach(pid);
3238       return True;
3239    } else {
3240       /* Whatever kind of problem happened. We shutdown */
3241       shutting_down = True;
3242       return False;
3243    }
3244 }
3245 #endif
3246
3247 static 
3248 void cleanup_restore_and_detach(void *v_pid)
3249 {
3250    DEBUG(1, "cleanup_restore_and_detach dying: %d\n", dying);
3251 #ifdef PTRACEINVOKER
3252    if (!dying)
3253       restore_and_detach(*(int*)v_pid);
3254 #endif
3255 }
3256
3257 /* This function loops till shutting_down becomes true.  In this loop,
3258    it verifies if valgrind process is reading the characters written
3259    by vgdb.  The verification is done every max_invoke_ms ms.  If
3260    valgrind is not reading characters, it will use invoke_gdbserver
3261    (if PTRACE_INVOKER is defined) to ensure that the gdbserver code is
3262    called soon by valgrind. */
3263 static int max_invoke_ms = 100;
3264 static
3265 void *invoke_gdbserver_in_valgrind(void *v_pid)
3266 {
3267    int pid = *(int *)v_pid;
3268    int written_by_vgdb_before_sleep;
3269    int seen_by_valgrind_before_sleep;
3270    
3271    int invoked_written = -1;
3272
3273    pthread_cleanup_push(cleanup_restore_and_detach, v_pid);
3274
3275    while (!shutting_down) {
3276       written_by_vgdb_before_sleep = VS_written_by_vgdb;
3277       seen_by_valgrind_before_sleep = VS_seen_by_valgrind;
3278       DEBUG(3, 
3279             "written_by_vgdb_before_sleep %d "
3280             "seen_by_valgrind_before_sleep %d\n",
3281             written_by_vgdb_before_sleep,
3282             seen_by_valgrind_before_sleep);
3283       if (usleep(1000 * max_invoke_ms) != 0) {
3284          if (errno == EINTR)
3285             continue;
3286          XERROR (errno, "error usleep\n");
3287       }
3288       /* if nothing happened during our sleep, let's try to wake up valgrind */
3289       if (written_by_vgdb_before_sleep == VS_written_by_vgdb
3290           && seen_by_valgrind_before_sleep == VS_seen_by_valgrind
3291           && VS_written_by_vgdb > VS_seen_by_valgrind) {
3292          DEBUG(2,
3293                "after sleep "
3294                "written_by_vgdb %d "
3295                "seen_by_valgrind %d "
3296                "invoked_written %d\n",
3297                VS_written_by_vgdb,
3298                VS_seen_by_valgrind,
3299                invoked_written);
3300          /* if the pid does not exist anymore, we better stop */
3301          if (kill(pid, 0) != 0)
3302            XERROR (errno, 
3303                    "invoke_gdbserver_in_valgrind: "
3304                    "check for pid %d existence failed\n", pid);
3305
3306          #if defined(PTRACEINVOKER)
3307          /* only need to wake up if the nr written has changed since
3308             last invoke. */
3309          if (invoked_written != written_by_vgdb_before_sleep) {
3310             if (invoke_gdbserver(pid)) {
3311                /* If invoke succesful, no need to invoke again
3312                   for the same value of written_by_vgdb_before_sleep. */
3313                invoked_written = written_by_vgdb_before_sleep;
3314             }
3315          }
3316          #else
3317          DEBUG(2, "invoke_gdbserver via ptrace not (yet) implemented\n");
3318          #endif
3319       }
3320    }
3321    pthread_cleanup_pop(0);
3322    return NULL;
3323 }
3324
3325 static
3326 int open_fifo (char* name, int flags, char* desc)
3327 {
3328    int fd;
3329    DEBUG(1, "opening %s %s\n", name, desc);
3330    fd = open(name, flags);
3331    if (fd == -1)
3332       XERROR (errno, "error opening %s %s\n", name, desc);
3333
3334    DEBUG(1, "opened %s %s fd %d\n", name, desc, fd);
3335    return fd;
3336 }
3337
3338 /* acquire a lock on the first byte of the given fd. If not successful,
3339    exits with error.
3340    This allows to avoid having two vgdb speaking with the same Valgrind
3341    gdbserver as this causes serious headaches to the protocol. */
3342 static
3343 void acquire_lock (int fd, int valgrind_pid)
3344 {
3345    if (lockf(fd, F_TLOCK, 1) < 0) {
3346       if (errno == EAGAIN || errno == EACCES) {
3347          XERROR(errno, 
3348                 "Cannot acquire lock.\n"
3349                 "Probably vgdb pid %d already speaks with Valgrind pid %d\n",
3350                 VS_vgdb_pid,
3351                 valgrind_pid);
3352       } else {
3353          XERROR(errno, "cannot acquire lock.\n");
3354       }
3355    }
3356
3357    /* Here, we have the lock. It will be released when fd will be closed. */
3358    /* We indicate our pid to Valgrind gdbserver */
3359    if (shared32 != NULL)
3360       shared32->vgdb_pid = getpid();
3361    else if (shared64 != NULL)
3362       shared64->vgdb_pid = getpid();
3363    else
3364       assert(0);
3365 }
3366
3367 #define PBUFSIZ 16384 /* keep in sync with server.h */
3368
3369 /* read some characters from fd.
3370    Returns the nr of characters read, -1 if error.
3371    desc is a string used in tracing */
3372 static
3373 int read_buf (int fd, char* buf, char* desc)
3374 {
3375    int nrread;
3376    DEBUG(2, "reading %s\n", desc);
3377    nrread = read(fd, buf, PBUFSIZ);
3378    if (nrread == -1) {
3379       ERROR (errno, "error reading %s\n", desc);
3380       return -1;
3381    }
3382    buf[nrread] = '\0';
3383    DEBUG(2, "read %s %s\n", desc, buf);
3384    return nrread;
3385 }
3386
3387 /* write size bytes from buf to fd.
3388    desc is a description of the action for which the write is done.
3389    If notify, then add size to the shared cntr indicating to the 
3390    valgrind process that there is new data.
3391    Returns True if write is ok, False if there was a problem. */
3392 static
3393 Bool write_buf(int fd, char* buf, int size, char* desc, Bool notify)
3394 {
3395    int nrwritten;
3396    int nrw;
3397    DEBUG(2, "writing %s len %d %s notify: %d\n", desc, size, buf, notify);
3398    nrwritten = 0;
3399    while (nrwritten < size) {
3400       nrw = write (fd, buf+nrwritten, size - nrwritten);
3401       if (nrw == -1) {
3402          ERROR(errno, "error write %s\n", desc);
3403          return False;
3404       }
3405       nrwritten = nrwritten + nrw;
3406       if (notify)
3407          add_written(nrw);
3408    }
3409    return True;
3410
3411
3412 typedef enum {
3413    FROM_GDB,
3414    TO_GDB,
3415    FROM_PID,
3416    TO_PID } ConnectionKind;
3417 static const int NumConnectionKind = TO_PID+1;
3418 static 
3419 char *ppConnectionKind (ConnectionKind con)
3420 {
3421    switch (con) {
3422    case FROM_GDB: return "FROM_GDB";
3423    case TO_GDB:   return "TO_GDB";
3424    case FROM_PID: return "FROM_PID";
3425    case TO_PID:   return "TO_PID";
3426    default:       return "invalid connection kind";
3427    }
3428 }
3429
3430 static char *shared_mem;
3431
3432 static const int from_gdb = 0;
3433 static char *from_gdb_to_pid; /* fifo name to write gdb command to pid */
3434 /* Returns True in case read/write operations were done properly.
3435    Returns False in case of error.
3436    to_pid is the file descriptor to write to the process pid. */
3437 static
3438 Bool read_from_gdb_write_to_pid(int to_pid)
3439 {
3440    char buf[PBUFSIZ];
3441    int nrread;
3442
3443    nrread = read_buf(from_gdb, buf, "from gdb on stdin");
3444    if (nrread <= 0) {
3445       if (nrread == 0) 
3446          DEBUG(1, "read 0 bytes from gdb => assume exit\n");
3447       else
3448          DEBUG(1, "error reading bytes from gdb\n");
3449       close (from_gdb);
3450       shutting_down = True;
3451       return False;
3452    }
3453    return write_buf(to_pid, buf, nrread, "to_pid", /* notify */ True);
3454 }
3455
3456 static const int to_gdb = 1;
3457 static char *to_gdb_from_pid; /* fifo name to read pid replies */
3458 /* Returns True in case read/write operations were done properly.
3459    Returns False in case of error.
3460    from_pid is the file descriptor to read data from the process pid. */
3461 static
3462 Bool read_from_pid_write_to_gdb(int from_pid)
3463 {
3464    char buf[PBUFSIZ];
3465    int nrread;
3466
3467    nrread = read_buf(from_pid, buf, "from pid");
3468    if (nrread <= 0) {
3469       if (nrread == 0) 
3470          DEBUG(1, "read 0 bytes from pid => assume exit\n");
3471       else
3472          DEBUG(1, "error reading bytes from pid\n");
3473       close (from_pid);
3474       shutting_down = True;
3475       return False;
3476    }
3477    return write_buf(to_gdb, buf, nrread, "to_gdb", /* notify */ False);
3478 }
3479
3480 /* prepares the FIFOs filenames, map the shared memory. */
3481 static
3482 void prepare_fifos_and_shared_mem(int pid)
3483 {
3484    from_gdb_to_pid = vmalloc (strlen(vgdb_prefix) + 30);
3485    to_gdb_from_pid = vmalloc (strlen(vgdb_prefix) + 30);
3486    shared_mem      = vmalloc (strlen(vgdb_prefix) + 30);
3487    /* below 3 lines must match the equivalent in remote-utils.c */
3488    sprintf(from_gdb_to_pid, "%s-from-vgdb-to-%d",    vgdb_prefix, pid);
3489    sprintf(to_gdb_from_pid, "%s-to-vgdb-from-%d",    vgdb_prefix, pid);
3490    sprintf(shared_mem,      "%s-shared-mem-vgdb-%d", vgdb_prefix, pid);
3491    DEBUG (1, "vgdb: using %s %s %s\n", 
3492           from_gdb_to_pid, to_gdb_from_pid, shared_mem);
3493
3494    map_vgdbshared(shared_mem);
3495 }
3496
3497 /* Convert hex digit A to a number.  */
3498
3499 static int
3500 fromhex (int a)
3501 {
3502    if (a >= '0' && a <= '9')
3503       return a - '0';
3504    else if (a >= 'a' && a <= 'f')
3505       return a - 'a' + 10;
3506    else
3507       XERROR(0, "Reply contains invalid hex digit %c\n", a);
3508   return 0;
3509 }
3510
3511 /* Returns next char from fd.  -1 if error, -2 if EOF.
3512    NB: must always call it with the same fd */
3513 static int
3514 readchar (int fd)
3515 {
3516   static unsigned char buf[PBUFSIZ];
3517   static int bufcnt = 0;
3518   static unsigned char *bufp;
3519
3520   if (bufcnt-- > 0)
3521      return *bufp++;
3522
3523   bufcnt = read (fd, buf, sizeof (buf));
3524
3525   if (bufcnt <= 0) {
3526      if (bufcnt == 0) {
3527         fprintf (stderr, "readchar: Got EOF\n");
3528         return -2;
3529      } else {
3530         ERROR (errno, "readchar\n");
3531         return -1;
3532      }
3533   }
3534
3535   bufp = buf;
3536   bufcnt--;
3537   return *bufp++;
3538 }
3539
3540 /* Read a packet from fromfd, with error checking,
3541    and store it in BUF.  
3542    Returns length of packet, or -1 if error or -2 if EOF.
3543    Writes ack on ackfd */
3544
3545 static int
3546 getpkt (char *buf, int fromfd, int ackfd)
3547 {
3548   char *bp;
3549   unsigned char csum, c1, c2;
3550   int c;
3551   
3552   while (1) {
3553      csum = 0;
3554
3555      while (1) {
3556         c = readchar (fromfd);
3557         if (c == '$')
3558            break;
3559         DEBUG(2, "[getpkt: discarding char '%c']\n", c);
3560         if (c < 0)
3561            return c;
3562      }
3563
3564      bp = buf;
3565      while (1) {
3566         c = readchar (fromfd);
3567         if (c < 0)
3568            return c;
3569         if (c == '#')
3570            break;
3571         if (c == '*') {
3572            int repeat;
3573            int r;
3574            int prev;
3575            prev = *(bp-1);
3576            csum += c;
3577            repeat = readchar (fromfd);
3578            csum += repeat;
3579            for (r = 0; r < repeat - 29; r ++)
3580               *bp++ = prev;
3581         } else {
3582            *bp++ = c;
3583            csum += c;
3584         }
3585      }
3586      *bp = 0;
3587
3588      c1 = fromhex (readchar (fromfd));
3589      c2 = fromhex (readchar (fromfd));
3590
3591      if (csum == (c1 << 4) + c2)
3592         break;
3593
3594      fprintf (stderr, "Bad checksum, sentsum=0x%x, csum=0x%x, buf=%s\n",
3595               (c1 << 4) + c2, csum, buf);
3596      if (write (ackfd, "-", 1) != 1)
3597         ERROR(0, "error when writing - (nack)\n");
3598      else
3599         add_written(1);
3600   }
3601
3602   DEBUG(2, "getpkt (\"%s\");  [sending ack] \n", buf);
3603   if (write (ackfd, "+", 1) != 1)
3604      ERROR(0, "error when writing + (ack)\n");
3605   else
3606      add_written(1);
3607   return bp - buf;
3608 }
3609
3610 static int sigint = 0;
3611 static int sigterm = 0;
3612 static int sigpipe = 0;
3613 static int sighup = 0;
3614 static int sigusr1 = 0;
3615 static int sigalrm = 0;
3616 static int sigusr1_fd = -1;
3617 static pthread_t invoke_gdbserver_in_valgrind_thread;
3618
3619 static
3620 void received_signal (int signum)
3621 {
3622    if (signum == SIGINT)
3623       sigint++;
3624    else if (signum == SIGUSR1) {
3625       sigusr1++;
3626       if (sigusr1_fd >= 0) {
3627          char control_c = '\003';
3628          write_buf(sigusr1_fd, &control_c, 1,
3629                    "write \\003 on SIGUSR1", /* notify */ True);
3630       }
3631    }
3632    else if (signum == SIGTERM) {
3633       shutting_down = True;
3634       sigterm++;
3635    } else if (signum == SIGHUP) {
3636       shutting_down = True;
3637       sighup++;
3638    } else if (signum == SIGPIPE) {
3639       sigpipe++;
3640    } else if (signum == SIGALRM) {
3641       sigalrm++;
3642       DEBUG(1, "pthread_cancel invoke_gdbserver_in_valgrind_thread\n");
3643       /* Note: we cannot directly invoke restore_and_detach : this must
3644          be done by the thread that has attached. 
3645          We have in this thread pushed a cleanup handler that will
3646          cleanup what is needed. */
3647       pthread_cancel(invoke_gdbserver_in_valgrind_thread);
3648    } else {
3649       ERROR(0, "unexpected signal %d\n", signum);
3650    }
3651 }
3652
3653 /* install the signal handlers allowing e.g. vgdb to cleanup in
3654    case of termination. */
3655 static
3656 void install_handlers(void)
3657 {
3658    struct sigaction action, oldaction;
3659
3660    action.sa_handler = received_signal;
3661    sigemptyset (&action.sa_mask);
3662    action.sa_flags = 0;
3663    
3664    /* SIGINT: when user types C-c in gdb, this sends
3665       a SIGINT to vgdb + causes a character to be sent to remote gdbserver.
3666       The later is enough to wakeup the valgrind process. */
3667    if (sigaction (SIGINT, &action, &oldaction) != 0)
3668       XERROR (errno, "vgdb error sigaction SIGINT\n");
3669    /* We might do something more intelligent than just
3670       reporting this SIGINT E.g. behave similarly to the gdb: two
3671       control-C without feedback from the debugged process would
3672       mean to stop debugging it. */
3673
3674    /* SIGUSR1: this is used to facilitate automatic testing.  When
3675       vgdb receives this signal, it will simulate the user typing C-c. */
3676    if (sigaction (SIGUSR1, &action, &oldaction) != 0)
3677       XERROR (errno, "vgdb error sigaction SIGUSR1\n");
3678    
3679
3680    /* SIGTERM: can receive this signal (e.g. from gdb) to terminate vgdb
3681       when detaching or similar. A clean shutdown will be done as both
3682       the read and write side will detect an end of file. */
3683    if (sigaction (SIGTERM, &action, &oldaction) != 0)
3684       XERROR (errno, "vgdb error sigaction SIGTERM\n");
3685    
3686    /* SIGPIPE: can receive this signal when gdb detaches or kill the
3687       process debugged: gdb will close its pipes to vgdb. vgdb
3688       must resist to this signal to allow a clean shutdown. */
3689    if (sigaction (SIGPIPE, &action, &oldaction) != 0)
3690       XERROR (errno, "vgdb error sigaction SIGPIPE\n");
3691    
3692    /* SIGALRM: in case invoke thread is blocked, alarm is used
3693       to cleanup.  */
3694    if (sigaction (SIGALRM, &action, &oldaction) != 0)
3695       XERROR (errno, "vgdb error sigaction SIGALRM\n");
3696 }
3697
3698 /* close the FIFOs provided connections, terminate the invoker thread.  */
3699 static
3700 void close_connection(int to_pid, int from_pid)
3701 {
3702    DEBUG(1, "nr received signals: sigint %d sigterm %d sighup %d sigpipe %d\n",
3703          sigint, sigterm, sighup, sigpipe);
3704    /* Note that we do not forward sigterm to the valgrind process:
3705       a sigterm signal is (probably) received from gdb if the user wants to
3706       kill the debugged process. The kill instruction has been given to
3707       the valgrind process, which should execute a clean exit. */
3708
3709    /* We first close the connection to pid. The pid will then
3710       terminates its gdbserver work. We keep the from pid
3711       fifo opened till the invoker thread is finished.
3712       This allows the gdbserver to finish sending its last reply. */
3713    if (close(to_pid) != 0)
3714       ERROR(errno, "close to_pid\n");
3715
3716    /* if there is a task that was busy trying to wake up valgrind
3717       process, we wait for it to be terminated otherwise threads
3718       in the valgrind process can stay stopped if vgdb main
3719       exits before the invoke thread had time to detach from
3720       all valgrind threads. */
3721    if (max_invoke_ms > 0) {
3722       int join;
3723
3724       /* It is surprisingly complex to properly shutdown or exit the
3725          valgrind process in which gdbserver has been invoked through
3726          ptrace.  In the normal case (gdb detaches from the process,
3727          or process is continued), the valgrind process will reach the
3728          breakpoint place.  Using ptrace, vgdb will ensure the
3729          previous activity of the process is resumed (e.g. restart a
3730          blocking system call).  The special case is when gdb asks the
3731          valgrind process to exit (using either the "kill" command or
3732          "monitor exit").  In such a case, the valgrind process will
3733          call exit.  But a ptraced process will be blocked in exit,
3734          waiting for the ptracing process to detach or die. vgdb
3735          cannot detach unconditionally as otherwise, in the normal
3736          case, the valgrind process would die abnormally with SIGTRAP
3737          (as vgdb would not be there to catch it). vgdb can also not
3738          die unconditionally otherwise again, similar problem.  So, we
3739          assume that most of the time, we arrive here in the normal
3740          case, and so, the breakpoint has been encountered by the
3741          valgrind process, so the invoker thread will exit and the
3742          join will succeed.  For the "kill" case, we cause an alarm
3743          signal to be sent after a few seconds. This means that in the
3744          normal case, the gdbserver code in valgrind process must have
3745          returned the control in less than the alarm nr of seconds,
3746          otherwise, valgrind will die abnormally with SIGTRAP. */
3747       (void) alarm (3);
3748
3749       DEBUG(1, "joining with invoke_gdbserver_in_valgrind_thread\n");
3750       join = pthread_join(invoke_gdbserver_in_valgrind_thread, NULL);
3751       if (join != 0)
3752          XERROR 
3753             (join, 
3754              "vgdb error pthread_join invoke_gdbserver_in_valgrind_thread\n");
3755    }
3756    if (close(from_pid) != 0)
3757       ERROR(errno, "close from_pid\n");
3758 }
3759
3760 /* Relay data between gdb and Valgrind gdbserver, till EOF or an
3761    error is encountered. */
3762 static
3763 void gdb_relay (int pid)
3764 {
3765    int from_pid = -1; /* fd to read from pid */
3766    int to_pid = -1; /* fd to write to pid */
3767
3768    int shutdown_loop = 0;
3769    fprintf (stderr, "relaying data between gdb and process %d\n", pid);
3770    fflush (stderr);
3771
3772    if (max_invoke_ms > 0)
3773       pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL, 
3774                      invoke_gdbserver_in_valgrind, (void *) &pid);
3775    to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
3776    acquire_lock (shared_mem_fd, pid);
3777    
3778    from_pid = open_fifo (to_gdb_from_pid, O_RDONLY|O_NONBLOCK, 
3779                          "read mode from pid");
3780
3781    sigusr1_fd = to_pid; /* allow simulating user typing control-c */
3782
3783    while (1) {
3784       ConnectionKind ck;
3785       int ret;
3786       struct pollfd pollfds[NumConnectionKind];
3787       
3788       /* watch data written by gdb, watch POLLERR on both gdb fd */
3789       pollfds[FROM_GDB].fd = from_gdb;
3790       pollfds[FROM_GDB].events = POLLIN;
3791       pollfds[FROM_GDB].revents = 0;
3792       pollfds[TO_GDB].fd = to_gdb;
3793       pollfds[TO_GDB].events = 0;
3794       pollfds[TO_GDB].revents = 0;
3795       
3796       /* watch data written by pid, watch POLLERR on both pid fd */
3797       pollfds[FROM_PID].fd = from_pid;
3798       pollfds[FROM_PID].events = POLLIN;
3799       pollfds[FROM_PID].revents = 0;
3800       pollfds[TO_PID].fd = to_pid;
3801       pollfds[TO_PID].events = 0;
3802       pollfds[TO_PID].revents = 0;
3803       
3804       ret = poll(pollfds, 
3805                  NumConnectionKind, 
3806                  (shutting_down ? 
3807                   1 /* one second */ 
3808                   : -1 /* infinite */));
3809       DEBUG(2, "poll ret %d errno %d\n", ret, errno);
3810
3811       /* check for unexpected error */
3812       if (ret <= 0 && errno != EINTR) {
3813          ERROR (errno, "unexpected poll ret %d\n", ret);
3814          shutting_down = True;
3815          break;
3816       }
3817       
3818       /* check for data to read */
3819       for (ck = 0; ck < NumConnectionKind; ck ++) {
3820          if (pollfds[ck].revents & POLLIN) {
3821             switch (ck) {
3822             case FROM_GDB: 
3823                if (!read_from_gdb_write_to_pid(to_pid))
3824                   shutting_down = True;
3825                break;
3826                case FROM_PID:
3827                   if (!read_from_pid_write_to_gdb(from_pid))
3828                      shutting_down = True;
3829                   break;
3830             default: XERROR(0, "unexpected POLLIN on %s\n",
3831                                ppConnectionKind(ck));
3832             }
3833          }
3834       }
3835
3836       /* check for an fd being in error condition */
3837       for (ck = 0; ck < NumConnectionKind; ck ++) {
3838          if (pollfds[ck].revents & POLLERR) {
3839             DEBUG(1, "connection %s fd %d POLLERR error condition\n",
3840                      ppConnectionKind(ck), pollfds[ck].fd);
3841             valgrind_dying();
3842             shutting_down = True;
3843          }
3844          if (pollfds[ck].revents & POLLHUP) {
3845             DEBUG(1, "connection %s fd %d POLLHUP error condition\n",
3846                   ppConnectionKind(ck), pollfds[ck].fd);
3847             valgrind_dying();
3848             shutting_down = True;
3849          }
3850          if (pollfds[ck].revents & POLLNVAL) {
3851             DEBUG(1, "connection %s fd %d POLLNVAL error condition\n",
3852                   ppConnectionKind(ck), pollfds[ck].fd);
3853             valgrind_dying();
3854             shutting_down = True;
3855          }
3856       }
3857       
3858       if (shutting_down) {
3859          /* we let some time to the final packets to be transferred */
3860          shutdown_loop++;
3861          if (shutdown_loop > 3)
3862             break;
3863       }
3864    }
3865    close_connection(to_pid, from_pid);
3866 }
3867
3868 static int packet_len_for_command(char *cmd)
3869 {
3870    /* cmd will be send as a packet $qRcmd,xxxx....................xx#cc      */
3871    return                          7+     2*strlen(cmd)             +3  + 1;
3872 }
3873
3874 /* hyper-minimal protocol implementation that
3875    sends the provided commands (using qRcmd packets)
3876    and read and display their replies. */
3877 static
3878 void standalone_send_commands(int pid, 
3879                               int last_command,
3880                               char *commands[] )
3881 {
3882    int from_pid = -1; /* fd to read from pid */
3883    int to_pid = -1; /* fd to write to pid */
3884
3885    int i;
3886    int hi;
3887    unsigned char hex[3];
3888    unsigned char cksum;
3889    unsigned char *hexcommand;
3890    unsigned char buf[PBUFSIZ];
3891    int buflen;
3892    int nc;
3893
3894
3895    if (max_invoke_ms > 0)
3896       pthread_create(&invoke_gdbserver_in_valgrind_thread, NULL, 
3897                      invoke_gdbserver_in_valgrind, (void *) &pid);
3898
3899    to_pid = open_fifo(from_gdb_to_pid, O_WRONLY, "write to pid");
3900    acquire_lock (shared_mem_fd, pid);
3901
3902    /* first send a C-c \003 to pid, so that it wakes up the process
3903       After that, we can open the fifo from the pid in read mode
3904       We then start to wait for packets (normally first a resume reply)
3905       At that point, we send our command and expect replies */
3906    buf[0] = '\003';
3907    write_buf(to_pid, buf, 1, "write \\003 to wake up", /* notify */ True);
3908    from_pid = open_fifo(to_gdb_from_pid, O_RDONLY, 
3909                         "read cmd result from pid");
3910    
3911    for (nc = 0; nc <= last_command; nc++) {
3912       fprintf (stderr, "sending command %s to pid %d\n", commands[nc], pid);
3913       fflush (stderr);
3914       
3915       /* prepare hexcommand $qRcmd,xxxx....................xx#cc      */
3916       hexcommand = vmalloc (packet_len_for_command(commands[nc]));
3917       hexcommand[0] = 0;
3918       strcat (hexcommand, "$qRcmd,");
3919       for (i = 0; i < strlen(commands[nc]); i++) {
3920          sprintf(hex, "%02x", commands[nc][i]);
3921          strcat (hexcommand, hex);
3922       }
3923       /* checksum (but without the $) */
3924       cksum = 0;
3925       for (hi = 1; hi < strlen(hexcommand); hi++)
3926          cksum+=hexcommand[hi];
3927       strcat(hexcommand, "#");
3928       sprintf(hex, "%02x", cksum);
3929       strcat(hexcommand, hex);
3930       write_buf(to_pid, hexcommand, strlen(hexcommand), 
3931                 "writing hex command to pid", /* notify */ True);
3932
3933       /* we exit of the below loop explicitely when the command has
3934          been handled or because a signal handler will set
3935          shutting_down. */
3936       while (!shutting_down) {
3937          buflen = getpkt(buf, from_pid, to_pid);
3938          if (buflen < 0) {
3939             ERROR (0, "error reading packet\n");
3940             if (buflen == -2)
3941                valgrind_dying();
3942             break;
3943          }
3944          if (strlen(buf) == 0) {
3945             DEBUG(0, "empty packet rcvd (packet qRcmd not recognised?)\n");
3946             break;
3947          }
3948          if (strcmp(buf, "OK") == 0) {
3949             DEBUG(1, "OK packet rcvd\n");
3950             break;
3951          }
3952          if (buf[0] == 'E') {
3953             DEBUG(0, 
3954                   "E NN error packet rcvd: %s (unknown monitor command?)\n",
3955                   buf);
3956             break;
3957          }
3958          if (buf[0] == 'W') {
3959             DEBUG(0, "W stopped packet rcvd: %s\n", buf);
3960             break;
3961          }
3962          if (buf[0] == 'T') {
3963             DEBUG(1, "T resume reply packet received: %s\n", buf);
3964             continue;
3965          }
3966          
3967          /* must be here an O packet with hex encoded string reply 
3968             => decode and print it */
3969          if (buf[0] != 'O') {
3970             DEBUG(0, "expecting O packet, received: %s\n", buf);
3971             continue;
3972          }
3973          {
3974             char buf_print[buflen/2 + 1];
3975             for (i = 1; i < buflen; i = i + 2)
3976                buf_print[i/2] = (fromhex(*(buf+i)) << 4) 
3977                      + fromhex(*(buf+i+1));
3978             buf_print[buflen/2] = 0;
3979             printf("%s", buf_print);
3980             fflush(stdout);
3981          }
3982       }
3983       free (hexcommand);
3984    }
3985    shutting_down = True;
3986
3987    close_connection(to_pid, from_pid);
3988 }
3989
3990 /* report to user the existence of a vgdb-able valgrind process 
3991    with given pid */
3992 static
3993 void report_pid (int pid)
3994 {
3995    char cmdline_file[100];
3996    char cmdline[1000];
3997    int fd;
3998    int i, sz;
3999
4000    sprintf(cmdline_file, "/proc/%d/cmdline", pid);
4001    fd = open (cmdline_file, O_RDONLY);
4002    if (fd == -1) {
4003       DEBUG(1, "error opening cmdline file %s %s\n", 
4004             cmdline_file, strerror(errno));
4005       sprintf(cmdline, "(could not obtain process command line)");
4006    } else {
4007       sz = read(fd, cmdline, 1000);
4008       for (i = 0; i < sz; i++)
4009          if (cmdline[i] == 0)
4010             cmdline[i] = ' ';
4011       cmdline[sz] = 0;
4012    }  
4013    fprintf(stderr, "use --pid=%d for %s\n", pid, cmdline);
4014    fflush(stderr);
4015 }
4016
4017 /* Eventually produces additional usage information documenting the
4018    ptrace restrictions. */
4019 static
4020 void ptrace_restrictions(void)
4021 {
4022 #  ifdef PR_SET_PTRACER
4023    char *ptrace_scope_setting_file = "/proc/sys/kernel/yama/ptrace_scope";
4024    int fd = -1;
4025    char ptrace_scope = 'X';
4026    fd = open (ptrace_scope_setting_file, O_RDONLY, 0);
4027    if (fd >= 0 && (read (fd, &ptrace_scope, 1) == 1) && (ptrace_scope != '0')) {
4028       fprintf (stderr,
4029                "Note: your kernel restricts ptrace invoker using %s\n"
4030                "vgdb will only be able to attach to a Valgrind process\n"
4031                "blocked in a system call *after* an initial successful attach\n",
4032                ptrace_scope_setting_file);
4033    } else if (ptrace_scope == 'X') {
4034       fprintf(stderr, "Could not determine ptrace scope from %s\n",
4035               ptrace_scope_setting_file);
4036    }
4037    if (fd >= 0)
4038       close (fd);
4039 #  endif
4040
4041 #  ifndef PTRACEINVOKER
4042    fprintf(stderr, 
4043            "Note: ptrace invoker not implemented\n"
4044            "For more info: read user manual section"
4045            " 'Limitations of the Valgrind gdbserver'\n");
4046 #  endif
4047 }
4048
4049 static
4050 void usage(void)
4051 {
4052    fprintf(stderr,
4053 "Usage: vgdb [OPTION]... [[-c] COMMAND]...\n"
4054 "vgdb (valgrind gdb) has two usages\n"
4055 "  1. standalone to send monitor commands to a Valgrind gdbserver.\n"
4056 "     The OPTION(s) must be followed by the command to send\n"
4057 "     To send more than one command, separate the commands with -c\n"
4058 "  2. relay application between gdb and a Valgrind gdbserver.\n"
4059 "     Only OPTION(s) can be given.\n"
4060 "\n"
4061 " OPTIONS are [--pid=<number>] [--vgdb-prefix=<prefix>]\n"
4062 "             [--max-invoke-ms=<number>] [--wait=<number>] [-d] -D]\n"
4063 "  --pid arg must be given if multiple Valgrind gdbservers are found.\n"
4064 "  --vgdb-prefix arg must be given to both Valgrind and vgdb utility\n"
4065 "      if you want to change the default prefix for the FIFOs communication\n"
4066 "      between the Valgrind gdbserver and vgdb.\n"
4067 "  --wait arg tells vgdb to check during the specified number\n"
4068 "      of seconds if a Valgrind gdbserver can be found.\n"
4069 "  --max-invoke-ms gives the nr of milli-seconds after which vgdb will force\n"
4070 "      the invocation of the Valgrind gdbserver (if the Valgrind process\n"
4071 "           is blocked in a system call).\n"
4072 "  -d  arg tells to show debug info. Multiple -d args for more debug info\n"
4073 "  -D  arg tells to show shared mem status and then exit.\n"
4074 "\n"
4075            );
4076    ptrace_restrictions();  
4077 }
4078
4079 /* If arg_pid == -1, waits maximum check_trials seconds to discover
4080    a valgrind pid appearing.
4081    Otherwise verify arg_pid is valid and corresponds to a Valgrind process
4082    with gdbserver activated.
4083
4084    Returns the pid to work with
4085    or exits in case of error (e.g. no pid found corresponding to arg_pid */
4086
4087 static
4088 int search_arg_pid(int arg_pid, int check_trials)
4089 {
4090    int i;
4091    int pid = -1;
4092
4093    if (arg_pid == 0 || arg_pid < -1) {
4094       fprintf (stderr, "vgdb error: invalid pid %d given\n", arg_pid);
4095       exit (1);
4096    } else {
4097       /* search for a matching named fifo. 
4098          If we have been given a pid, we will check that the matching FIFO is
4099          there (or wait the nr of check_trials for this to appear).
4100          If no pid has been given, then if we find only one FIFO,
4101          we will use this to build the pid to use.
4102          If we find multiple processes with valid FIFO, we report them and will
4103          exit with an error. */
4104       DIR *vgdb_dir;
4105       char *vgdb_dir_name = vmalloc (strlen (vgdb_prefix) + 3);
4106       struct dirent *f;
4107       int is;
4108       int nr_valid_pid = 0;
4109       const char *suffix = "-from-vgdb-to-"; /* followed by pid */
4110       char *vgdb_format = vmalloc (strlen(vgdb_prefix) + strlen(suffix) + 1);
4111       
4112       strcpy (vgdb_format, vgdb_prefix);
4113       strcat (vgdb_format, suffix);
4114       
4115       strcpy (vgdb_dir_name, vgdb_prefix);
4116       
4117       for (is = strlen(vgdb_prefix) - 1; is >= 0; is--)
4118          if (vgdb_dir_name[is] == '/') {
4119             vgdb_dir_name[is+1] = '\0';
4120             break;
4121          }
4122       if (strlen(vgdb_dir_name) == 0)
4123          strcpy (vgdb_dir_name, "./");
4124
4125       DEBUG(1, "searching pid in directory %s format %s\n", 
4126             vgdb_dir_name, vgdb_format);
4127
4128       /* try to find FIFOs with valid pid.
4129          On exit of the loop, pid is set to:
4130          -1 if no FIFOs matching a running process is found
4131          -2 if multiple FIFOs of running processes are found
4132          otherwise it is set to the (only) pid found that can be debugged
4133       */
4134       for (i = 0; i < check_trials; i++) {
4135          DEBUG(1, "check_trial %d \n", i);
4136          if (i > 0)
4137            /* wait one second before checking again */
4138            sleep(1);
4139
4140          vgdb_dir = opendir (vgdb_dir_name);
4141          if (vgdb_dir == NULL)
4142             XERROR (errno, 
4143                     "vgdb error: opening directory %s searching vgdb fifo\n", 
4144                     vgdb_dir_name);
4145       
4146          errno = 0; /* avoid complain if vgdb_dir is empty */
4147          while ((f = readdir (vgdb_dir))) {
4148             struct stat st;
4149             char pathname[strlen(vgdb_dir_name) + strlen(f->d_name)];
4150             char *wrongpid;
4151             int newpid;
4152
4153             strcpy (pathname, vgdb_dir_name);
4154             strcat (pathname, f->d_name);
4155             DEBUG(3, "trying %s\n", pathname);
4156             if (stat (pathname, &st) != 0) {
4157                if (debuglevel >= 3)
4158                   ERROR (errno, "vgdb error: stat %s searching vgdb fifo\n", 
4159                          pathname);
4160             } else if (S_ISFIFO (st.st_mode)) {
4161                DEBUG(3, "trying %s\n", pathname);
4162                if (strncmp (pathname, vgdb_format, 
4163                             strlen (vgdb_format)) == 0) {
4164                   newpid = strtol(pathname + strlen (vgdb_format), 
4165                                   &wrongpid, 10);
4166                   if (*wrongpid == '\0' && newpid > 0 
4167                       && kill (newpid, 0) == 0) {
4168                      nr_valid_pid++;
4169                      if (arg_pid != -1) {
4170                         if (arg_pid == newpid) {
4171                            pid = newpid;
4172                         }
4173                      } else if (nr_valid_pid > 1) {
4174                         if (nr_valid_pid == 2) {
4175                            fprintf 
4176                               (stderr, 
4177                                "no --pid= arg given"
4178                                " and multiple valgrind pids found:\n");
4179                            report_pid (pid);
4180                         }
4181                         pid = -2;
4182                         report_pid (newpid);
4183                      } else {
4184                         pid = newpid;
4185                      }
4186                   }
4187                }
4188             }
4189             errno = 0; /* avoid complain if at the end of vgdb_dir */
4190          }
4191          if (f == NULL && errno != 0)
4192             XERROR (errno, "vgdb error: reading directory %s for vgdb fifo\n", 
4193                     vgdb_dir_name);
4194
4195          closedir (vgdb_dir);
4196          if (pid != -1)
4197             break;
4198       }
4199
4200       free (vgdb_dir_name);
4201       free (vgdb_format);
4202    }
4203
4204    if (pid == -1) {
4205       if (arg_pid == -1)
4206          fprintf (stderr, "vgdb error: no FIFO found and no pid given\n");
4207       else
4208          fprintf (stderr, "vgdb error: no FIFO found matching pid %d\n", 
4209                   arg_pid);
4210       exit (1);
4211    }
4212    else if (pid == -2) {
4213       /* no arg_pid given, multiple FIFOs found */
4214       exit (1);
4215    }
4216    else {
4217       return pid;
4218    }
4219 }
4220
4221 /* return true if the numeric value of an option of the 
4222    form --xxxxxxxxx=<number> could properly be extracted
4223    from arg. If True is returned, *value contains the
4224    extracted value.*/
4225 static
4226 Bool numeric_val(char* arg, int *value)
4227 {
4228    const char *eq_pos = strchr(arg, '=');
4229    char *wrong;
4230
4231    if (eq_pos == NULL)
4232       return False;
4233
4234    *value = strtol(eq_pos+1, &wrong, 10);
4235    if (*wrong)
4236       return False;
4237
4238    return True;
4239 }
4240
4241 /* true if arg matches the provided option */
4242 static
4243 Bool is_opt(char* arg, char *option)
4244 {
4245    int option_len = strlen(option);
4246    if (option[option_len-1] == '=')
4247       return (0 == strncmp(option, arg, option_len));
4248    else
4249       return (0 == strcmp(option, arg));
4250 }
4251
4252 /* Parse command lines options. If error(s), exits.
4253    Otherwise returns the options in *p_... args.
4254    commands must be big enough for the commands extracted from argv.
4255    On return, *p_last_command gives the position in commands where
4256    the last command has been allocated (using vmalloc). */
4257 static
4258 void parse_options(int argc, char** argv,
4259                    Bool *p_show_shared_mem,
4260                    int *p_arg_pid,
4261                    int *p_check_trials,
4262                    int *p_last_command,
4263                    char *commands[])
4264 {
4265    Bool show_shared_mem = False;
4266    int arg_pid = -1;
4267    int check_trials = 1;
4268    int last_command = -1;
4269
4270    int i;
4271    int arg_errors = 0;
4272
4273    for (i = 1; i < argc; i++) {
4274       if (is_opt(argv[i], "--help") || is_opt(argv[i], "-h")) {
4275          usage();
4276          exit(0);
4277       } else if (is_opt(argv[i], "-d")) {
4278          debuglevel++;
4279       } else if (is_opt(argv[i], "-D")) {
4280          show_shared_mem = True;
4281       } else if (is_opt(argv[i], "--pid=")) {
4282          int newpid;
4283          if (!numeric_val(argv[i], &newpid)) {
4284             fprintf (stderr, "invalid pid argument %s\n", argv[i]);
4285             arg_errors++;
4286          } else if (arg_pid != -1) {
4287             fprintf (stderr, "multiple pid arguments given\n");
4288             arg_errors++;
4289          } else {
4290             arg_pid = newpid;
4291          }
4292       } else if (is_opt(argv[i], "--wait=")) {
4293          if (!numeric_val(argv[i], &check_trials)) {
4294             fprintf (stderr, "invalid wait argument %s\n", argv[i]);
4295             arg_errors++;
4296          }
4297       } else if (is_opt(argv[i], "--max-invoke-ms=")) {
4298          if (!numeric_val(argv[i], &max_invoke_ms)) {
4299             fprintf (stderr, "invalid max-invoke-ms argument %s\n", argv[i]);
4300             arg_errors++;
4301          }
4302       } else if (is_opt(argv[i], "--vgdb-prefix=")) {
4303          vgdb_prefix = argv[i] + 14;
4304       } else if (is_opt(argv[i], "-c")) {
4305          last_command++;
4306          commands[last_command] = vmalloc (1);
4307          commands[last_command][0] = '\0';
4308       } else if (0 == strncmp(argv[i], "-", 1)) {
4309          fprintf (stderr, "unknown or invalid argument %s\n", argv[i]);
4310          arg_errors++;
4311       } else {
4312          int len;
4313          if (last_command == -1) {
4314             /* only one command, no -c command indicator */
4315             last_command++;
4316             commands[last_command] = vmalloc (1);
4317             commands[last_command][0] = '\0';
4318          }
4319          len = strlen(commands[last_command]);
4320          commands[last_command] = vrealloc (commands[last_command], 
4321                                             len + 1 + strlen(argv[i]) + 1);
4322          if (len > 0)
4323             strcat (commands[last_command], " ");
4324          strcat (commands[last_command], argv[i]);
4325          if (packet_len_for_command(commands[last_command]) > PBUFSIZ) {
4326             fprintf (stderr, "command %s too long\n", commands[last_command]);
4327             arg_errors++;
4328          }
4329             
4330       }
4331    }
4332    if (arg_errors > 0) {
4333       fprintf (stderr, "args error. Try `vgdb --help` for more information\n");
4334       exit(1);
4335    }
4336
4337    *p_show_shared_mem = show_shared_mem;
4338    *p_arg_pid = arg_pid;
4339    *p_check_trials = check_trials;
4340    *p_last_command = last_command;
4341 }
4342
4343 int main(int argc, char** argv)
4344 {
4345    int i;
4346    int pid;
4347
4348    Bool show_shared_mem;
4349    int arg_pid;
4350    int check_trials;
4351    int last_command;
4352    char *commands[argc]; // we will never have more commands than args.
4353
4354    parse_options(argc, argv,
4355                  &show_shared_mem,
4356                  &arg_pid,
4357                  &check_trials,
4358                  &last_command,
4359                  commands);
4360   
4361    /* when we are working as a relay for gdb, handle some signals by
4362       only reporting them (according to debug level). Also handle these
4363       when ptrace will be used: vgdb must clean up the ptrace effect before
4364       dying. */
4365    if (max_invoke_ms > 0 || last_command == -1)
4366       install_handlers();
4367
4368    pid = search_arg_pid (arg_pid, check_trials);
4369
4370    prepare_fifos_and_shared_mem(pid);
4371
4372    if (show_shared_mem) {
4373       fprintf(stderr, 
4374               "vgdb %d "
4375               "written_by_vgdb %d "
4376               "seen_by_valgrind %d\n"
4377               "vgdb pid %d\n",
4378               VS_vgdb_pid,
4379               VS_written_by_vgdb,
4380               VS_seen_by_valgrind,
4381               VS_vgdb_pid);
4382       exit (0);
4383    }
4384
4385    if (last_command >= 0) {
4386       standalone_send_commands(pid, last_command, commands);
4387    } else {
4388       gdb_relay(pid);
4389    }
4390       
4391
4392    free (from_gdb_to_pid);
4393    free (to_gdb_from_pid);
4394    free (shared_mem);
4395
4396    for (i = 0; i <= last_command; i++)
4397       free (commands[i]);
4398    return 0;
4399 }