drd/drd_pthread_intercepts: Add a workaround for what is probably a compiler bug
[valgrind.git] / coregrind / vgdb-invoker-ptrace.c
blobcb37677d5cb596d6193bf9b9dbf911bbab9b2cf0
1 /*--------------------------------------------------------------------*/
2 /*--- Implementation of vgdb invoker subsystem via ptrace() calls. ---*/
3 /*--------------------------------------------------------------------*/
5 /*
6 This file is part of Valgrind, a dynamic binary instrumentation
7 framework.
9 Copyright (C) 2011-2017 Philippe Waroquiers
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.
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.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, see <http://www.gnu.org/licenses/>.
24 The GNU General Public License is contained in the file COPYING.
27 #include "config.h"
29 #include "vgdb.h"
30 #include "pub_core_threadstate.h"
32 #include <alloca.h>
33 #include <assert.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <sys/ptrace.h>
39 #include <sys/time.h>
40 #include <sys/user.h>
41 #include <sys/wait.h>
43 #ifdef PTRACE_GETREGSET
44 // TBD: better have a configure test instead ?
45 #define HAVE_PTRACE_GETREGSET
47 // A bi-arch build using PTRACE_GET/SETREGSET needs
48 // some conversion code for register structures.
49 // So, better do not use PTRACE_GET/SETREGSET
50 // Rather we use PTRACE_GETREGS or PTRACE_PEEKUSER.
52 // The only platform on which we must use PTRACE_GETREGSET is arm64.
53 // The resulting vgdb cannot work in a bi-arch setup.
54 // -1 means we will check that PTRACE_GETREGSET works.
55 # if defined(VGA_arm64)
56 #define USE_PTRACE_GETREGSET
57 # endif
58 #endif
60 #include <sys/uio.h>
61 #include <elf.h>
63 #include <sys/procfs.h>
65 // glibc versions prior to 2.5 do not define PTRACE_GETSIGINFO on
66 // the platforms we support.
67 #if !((__GLIBC__ > 2) || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 5))
68 # ifndef PTRACE_GETSIGINFO
69 # define PTRACE_GETSIGINFO 0x4202
70 # endif
71 #endif
73 // 32-bit or 64-bit wide, depending on primary architecture.
74 typedef Addr CORE_ADDR;
75 typedef Addr PTRACE_XFER_TYPE;
76 typedef void* PTRACE_ARG3_TYPE;
78 // if > 0, pid for which registers have to be restored.
79 // if == 0, means we have not yet called setregs (or have already
80 // restored the registers).
81 static int pid_of_save_regs = 0;
82 /* True if we have continued pid_of_save_regs after PTRACE_ATTACH. */
83 static Bool pid_of_save_regs_continued = False;
84 // When setregs has been called to change the registers of pid_of_save_regs,
85 // vgdb cannot transmit the signals intercepted during ptrace.
86 // So, we queue them, and will deliver them when detaching.
87 // See function waitstopped for more info.
88 static int signal_queue_sz = 0;
89 static siginfo_t *signal_queue;
91 /* True when loss of connection indicating that the Valgrind
92 process is dying. */
93 static Bool dying = False;
95 /* ptrace_(read|write)_memory are modified extracts of linux-low.c
96 from gdb 6.6. Copyrighted FSF */
97 /* Copy LEN bytes from valgrind memory starting at MEMADDR
98 to vgdb memory starting at MYADDR. */
99 static
100 int ptrace_read_memory (pid_t inferior_pid, CORE_ADDR memaddr,
101 void *myaddr, size_t len)
103 register int i;
104 /* Round starting address down to longword boundary. */
105 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
106 /* Round ending address up; get number of longwords that makes. */
107 register int count
108 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
109 / sizeof (PTRACE_XFER_TYPE);
110 /* Allocate buffer of that many longwords. */
111 register PTRACE_XFER_TYPE *buffer
112 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
114 /* Read all the longwords */
115 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
116 errno = 0;
117 buffer[i] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
118 (PTRACE_ARG3_TYPE) addr, 0);
119 if (errno)
120 return errno;
123 /* Copy appropriate bytes out of the buffer. */
124 memcpy (myaddr,
125 (char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)), len);
127 return 0;
130 /* Copy LEN bytes of data from vgdb memory at MYADDR
131 to valgrind memory at MEMADDR.
132 On failure (cannot write the valgrind memory)
133 returns the value of errno. */
134 __attribute__((unused)) /* not used on all platforms */
135 static
136 int ptrace_write_memory (pid_t inferior_pid, CORE_ADDR memaddr,
137 const void *myaddr, size_t len)
139 register int i;
140 /* Round starting address down to longword boundary. */
141 register CORE_ADDR addr = memaddr & -(CORE_ADDR) sizeof (PTRACE_XFER_TYPE);
142 /* Round ending address up; get number of longwords that makes. */
143 register int count
144 = (((memaddr + len) - addr) + sizeof (PTRACE_XFER_TYPE) - 1)
145 / sizeof (PTRACE_XFER_TYPE);
146 /* Allocate buffer of that many longwords. */
147 register PTRACE_XFER_TYPE *buffer
148 = (PTRACE_XFER_TYPE *) alloca (count * sizeof (PTRACE_XFER_TYPE));
150 if (debuglevel >= 1) {
151 DEBUG (1, "Writing ");
152 for (i = 0; i < len; i++)
153 PDEBUG (1, "%02x", ((const unsigned char*)myaddr)[i]);
154 PDEBUG(1, " to %p\n", (void *) memaddr);
157 /* Fill start and end extra bytes of buffer with existing memory data. */
159 buffer[0] = ptrace (PTRACE_PEEKTEXT, inferior_pid,
160 (PTRACE_ARG3_TYPE) addr, 0);
162 if (count > 1) {
163 buffer[count - 1]
164 = ptrace (PTRACE_PEEKTEXT, inferior_pid,
165 (PTRACE_ARG3_TYPE) (addr + (count - 1)
166 * sizeof (PTRACE_XFER_TYPE)),
170 /* Copy data to be written over corresponding part of buffer */
172 memcpy ((char *) buffer + (memaddr & (sizeof (PTRACE_XFER_TYPE) - 1)),
173 myaddr, len);
175 /* Write the entire buffer. */
177 for (i = 0; i < count; i++, addr += sizeof (PTRACE_XFER_TYPE)) {
178 errno = 0;
179 ptrace (PTRACE_POKETEXT, inferior_pid,
180 (PTRACE_ARG3_TYPE) addr, buffer[i]);
181 if (errno)
182 return errno;
185 return 0;
188 /* subset of VG_(threads) needed for vgdb ptrace.
189 This is initialized when process is attached. */
190 typedef struct {
191 ThreadStatus status;
192 Int lwpid;
194 VgdbThreadState;
195 static VgdbThreadState *vgdb_threads;
196 static int vg_n_threads;
198 static const
199 HChar* name_of_ThreadStatus ( ThreadStatus status )
201 switch (status) {
202 case VgTs_Empty: return "VgTs_Empty";
203 case VgTs_Init: return "VgTs_Init";
204 case VgTs_Runnable: return "VgTs_Runnable";
205 case VgTs_WaitSys: return "VgTs_WaitSys";
206 case VgTs_Yielding: return "VgTs_Yielding";
207 case VgTs_Zombie: return "VgTs_Zombie";
208 default: return "VgTs_???";
212 static
213 char *status_image (int status)
215 static char result[256]; // large enough
216 int sz = 0;
217 #define APPEND(...) sz += snprintf (result+sz, 256 - sz - 1, __VA_ARGS__)
219 result[0] = 0;
221 if (WIFEXITED(status))
222 APPEND ("WIFEXITED %d ", WEXITSTATUS(status));
224 if (WIFSIGNALED(status)) {
225 APPEND ("WIFSIGNALED %d ", WTERMSIG(status));
226 if (WCOREDUMP(status)) APPEND ("WCOREDUMP ");
229 if (WIFSTOPPED(status))
230 APPEND ("WIFSTOPPED %d ", WSTOPSIG(status));
232 #ifdef WIFCONTINUED
233 if (WIFCONTINUED(status))
234 APPEND ("WIFCONTINUED ");
235 #endif
237 return result;
238 #undef APPEND
241 /* Wait till the process pid is reported as stopped with signal_expected.
242 If other signal(s) than signal_expected are received, waitstopped
243 will pass them to pid, waiting for signal_expected to stop pid.
244 Returns True when process is in stopped state with signal_expected.
245 Returns False if a problem was encountered while waiting for pid
246 to be stopped.
248 If pid is reported as being dead/exited, waitstopped will return False.
250 static
251 Bool waitstopped (pid_t pid, int signal_expected, const char *msg)
253 pid_t p;
254 int status = 0;
255 int signal_received;
256 int res;
258 while (1) {
259 DEBUG(1, "waitstopped %s before waitpid signal_expected %d\n",
260 msg, signal_expected);
261 p = waitpid(pid, &status, __WALL);
262 DEBUG(1, "after waitpid pid %d p %d status 0x%x %s\n", pid, p,
263 status, status_image (status));
264 if (p != pid) {
265 ERROR(errno, "%s waitpid pid %d in waitstopped %d status 0x%x %s\n",
266 msg, pid, p, status, status_image (status));
267 return False;
270 if (WIFEXITED(status)) {
271 shutting_down = True;
272 return False;
275 assert (WIFSTOPPED(status));
276 signal_received = WSTOPSIG(status);
277 if (signal_received == signal_expected)
278 break;
280 /* pid received a signal which is not the signal we are waiting for.
281 If we have not (yet) changed the registers of the inferior
282 or we have (already) reset them, we can transmit the signal.
284 If we have already set the registers of the inferior, we cannot
285 transmit the signal, as this signal would arrive when the
286 gdbserver code runs. And valgrind only expects signals to
287 arrive in a small code portion around
288 client syscall logic, where signal are unmasked (see e.g.
289 m_syswrap/syscall-x86-linux.S ML_(do_syscall_for_client_WRK).
291 As ptrace is forcing a call to gdbserver by jumping
292 'out of this region', signals are not masked, but
293 will arrive outside of the allowed/expected code region.
294 So, if we have changed the registers of the inferior, we
295 rather queue the signal to transmit them when detaching,
296 after having restored the registers to the initial values. */
297 if (pid_of_save_regs) {
298 siginfo_t *newsiginfo;
300 // realloc a bigger queue, and store new signal at the end.
301 // This is not very efficient but we assume not many sigs are queued.
302 signal_queue_sz++;
303 signal_queue = vrealloc(signal_queue,
304 sizeof(siginfo_t) * signal_queue_sz);
305 newsiginfo = signal_queue + (signal_queue_sz - 1);
307 res = ptrace (PTRACE_GETSIGINFO, pid, NULL, newsiginfo);
308 if (res != 0) {
309 ERROR(errno, "PTRACE_GETSIGINFO failed: signal lost !!!!\n");
310 signal_queue_sz--;
311 } else
312 DEBUG(1, "waitstopped PTRACE_CONT, queuing signal %d"
313 " si_signo %d si_pid %d\n",
314 signal_received, newsiginfo->si_signo, newsiginfo->si_pid);
315 res = ptrace (PTRACE_CONT, pid, NULL, 0);
316 } else {
317 DEBUG(1, "waitstopped PTRACE_CONT with signal %d\n", signal_received);
318 res = ptrace (PTRACE_CONT, pid, NULL, signal_received);
320 if (res != 0) {
321 ERROR(errno, "waitstopped PTRACE_CONT\n");
322 return False;
326 return True;
329 /* Stops the given pid, wait for the process to be stopped.
330 Returns True if successful, False otherwise.
331 msg is used in tracing and error reporting. */
332 static
333 Bool stop (pid_t pid, const char *msg)
335 long res;
337 DEBUG(1, "%s SIGSTOP pid %d\n", msg, pid);
338 res = kill (pid, SIGSTOP);
339 if (res != 0) {
340 ERROR(errno, "%s SIGSTOP pid %d %ld\n", msg, pid, res);
341 return False;
344 return waitstopped (pid, SIGSTOP, msg);
348 /* Attaches to given pid, wait for the process to be stopped.
349 Returns True if successful, False otherwise.
350 msg is used in tracing and error reporting. */
351 static
352 Bool attach (pid_t pid, const char *msg)
354 long res;
355 static Bool output_error = True;
356 static Bool initial_attach = True;
357 // For a ptrace_scope protected system, we do not want to output
358 // repetitively attach error. We will output once an error
359 // for the initial_attach. Once the 1st attach has succeeded, we
360 // again show all errors.
362 DEBUG(1, "%s PTRACE_ATTACH pid %d\n", msg, pid);
363 res = ptrace (PTRACE_ATTACH, pid, NULL, NULL);
364 if (res != 0) {
365 if (output_error || debuglevel > 0) {
366 ERROR(errno, "%s PTRACE_ATTACH pid %d %ld\n", msg, pid, res);
367 if (initial_attach)
368 output_error = False;
370 return False;
373 initial_attach = False;
374 output_error = True;
375 return waitstopped(pid, SIGSTOP, msg);
378 /* once we are attached to the pid, get the list of threads and stop
379 them all.
380 Returns True if all threads properly suspended, False otherwise. */
381 static
382 Bool acquire_and_suspend_threads (pid_t pid)
384 int i;
385 int rw;
386 Bool pid_found = False;
387 Addr vgt;
388 int sz_tst;
389 int off_status;
390 int off_lwpid;
391 int nr_live_threads = 0;
393 if (shared32 != NULL) {
394 vgt = shared32->threads;
395 vg_n_threads = shared32->vg_n_threads;
396 sz_tst = shared32->sizeof_ThreadState;
397 off_status = shared32->offset_status;
398 off_lwpid = shared32->offset_lwpid;
400 else if (shared64 != NULL) {
401 vgt = shared64->threads;
402 vg_n_threads = shared64->vg_n_threads;
403 sz_tst = shared64->sizeof_ThreadState;
404 off_status = shared64->offset_status;
405 off_lwpid = shared64->offset_lwpid;
406 } else {
407 assert (0);
410 vgdb_threads = vmalloc(vg_n_threads * sizeof vgdb_threads[0]);
412 /* note: the entry 0 is unused */
413 DEBUG(1, "examining thread entries from tid 1 to tid %d\n", vg_n_threads-1);
414 for (i = 1; i < vg_n_threads; i++) {
415 vgt += sz_tst;
416 rw = ptrace_read_memory(pid, vgt+off_status,
417 &(vgdb_threads[i].status),
418 sizeof(ThreadStatus));
419 if (rw != 0) {
420 ERROR(rw, "status ptrace_read_memory\n");
421 return False;
424 rw = ptrace_read_memory(pid, vgt+off_lwpid,
425 &(vgdb_threads[i].lwpid),
426 sizeof(Int));
427 if (rw != 0) {
428 ERROR(rw, "lwpid ptrace_read_memory\n");
429 return False;
432 if (vgdb_threads[i].status != VgTs_Empty) {
433 DEBUG(1, "found tid %d status %s lwpid %d\n",
434 i, name_of_ThreadStatus(vgdb_threads[i].status),
435 vgdb_threads[i].lwpid);
436 nr_live_threads++;
437 if (vgdb_threads[i].lwpid <= 1) {
438 if (vgdb_threads[i].lwpid == 0
439 && vgdb_threads[i].status == VgTs_Init) {
440 DEBUG(1, "not set lwpid tid %d status %s lwpid %d\n",
441 i, name_of_ThreadStatus(vgdb_threads[i].status),
442 vgdb_threads[i].lwpid);
443 } else {
444 ERROR(1, "unexpected lwpid tid %d status %s lwpid %d\n",
445 i, name_of_ThreadStatus(vgdb_threads[i].status),
446 vgdb_threads[i].lwpid);
448 /* in case we have a VtTs_Init thread with lwpid not yet set,
449 we try again later. */
450 return False;
452 if (vgdb_threads[i].lwpid == pid) {
453 assert (!pid_found);
454 assert (i == 1);
455 pid_found = True;
456 } else {
457 if (!attach(vgdb_threads[i].lwpid, "attach_thread")) {
458 ERROR(0, "ERROR attach pid %d tid %d\n",
459 vgdb_threads[i].lwpid, i);
460 return False;
465 /* If we found no thread, it means the process is stopping, and
466 we better do not force anything to happen during that. */
467 if (nr_live_threads > 0)
468 return True;
469 else
470 return False;
473 static
474 void detach_from_all_threads (pid_t pid)
476 int i;
477 long res;
478 Bool pid_found = False;
480 /* detach from all the threads */
481 for (i = 1; i < vg_n_threads; i++) {
482 if (vgdb_threads[i].status != VgTs_Empty) {
483 if (vgdb_threads[i].status == VgTs_Init
484 && vgdb_threads[i].lwpid == 0) {
485 DEBUG(1, "skipping PTRACE_DETACH pid %d tid %d status %s\n",
486 vgdb_threads[i].lwpid, i,
487 name_of_ThreadStatus (vgdb_threads[i].status));
488 } else {
489 if (vgdb_threads[i].lwpid == pid) {
490 assert (!pid_found);
491 pid_found = True;
493 DEBUG(1, "PTRACE_DETACH pid %d tid %d status %s\n",
494 vgdb_threads[i].lwpid, i,
495 name_of_ThreadStatus (vgdb_threads[i].status));
496 res = ptrace (PTRACE_DETACH, vgdb_threads[i].lwpid, NULL, NULL);
497 if (res != 0) {
498 ERROR(errno, "PTRACE_DETACH pid %d tid %d status %s res %ld\n",
499 vgdb_threads[i].lwpid, i,
500 name_of_ThreadStatus (vgdb_threads[i].status),
501 res);
507 free (vgdb_threads);
509 if (!pid_found && pid) {
510 /* No threads are live. Process is busy stopping.
511 We need to detach from pid explicitly. */
512 DEBUG(1, "no thread live => PTRACE_DETACH pid %d\n", pid);
513 res = ptrace (PTRACE_DETACH, pid, NULL, NULL);
514 if (res != 0)
515 ERROR(errno, "PTRACE_DETACH pid %d res %ld\n", pid, res);
519 # if defined(VGA_arm64)
520 /* arm64 is extra special, old glibc defined kernel user_pt_regs, but
521 newer glibc instead define user_regs_struct. */
522 # ifdef HAVE_SYS_USER_REGS
523 static struct user_regs_struct user_save;
524 # else
525 static struct user_pt_regs user_save;
526 # endif
527 # else
528 static struct user user_save;
529 # endif
530 // The below indicates if ptrace_getregs (and ptrace_setregs) can be used.
531 // Note that some linux versions are defining PTRACE_GETREGS but using
532 // it gives back EIO.
533 // has_working_ptrace_getregs can take the following values:
534 // -1 : PTRACE_GETREGS is defined
535 // runtime check not yet done.
536 // 0 : PTRACE_GETREGS runtime check has failed.
537 // 1 : PTRACE_GETREGS defined and runtime check ok.
538 #ifdef HAVE_PTRACE_GETREGS
539 static int has_working_ptrace_getregs = -1;
540 #endif
541 // Similar but for PTRACE_GETREGSET
542 #ifdef HAVE_PTRACE_GETREGSET
543 static int has_working_ptrace_getregset = -1;
544 #endif
546 /* Get the registers from pid into regs.
547 regs_bsz value gives the length of *regs.
548 Returns True if all ok, otherwise False. */
549 static
550 Bool getregs (pid_t pid, void *regs, long regs_bsz)
552 DEBUG(1, "getregs regs_bsz %ld\n", regs_bsz);
553 # ifdef HAVE_PTRACE_GETREGSET
554 # ifndef USE_PTRACE_GETREGSET
555 if (has_working_ptrace_getregset)
556 DEBUG(1, "PTRACE_GETREGSET defined, not used (yet?) by vgdb\n");
557 has_working_ptrace_getregset = 0;
558 # endif
559 if (has_working_ptrace_getregset) {
560 // Platforms having GETREGSET
561 long res;
562 elf_gregset_t elf_regs;
563 struct iovec iovec;
565 DEBUG(1, "getregs PTRACE_GETREGSET sizeof(elf_regs) %zu\n",
566 sizeof(elf_regs));
567 iovec.iov_base = regs;
568 iovec.iov_len = sizeof(elf_regs);
570 res = ptrace (PTRACE_GETREGSET, pid, NT_PRSTATUS, &iovec);
571 if (res == 0) {
572 if (has_working_ptrace_getregset == -1) {
573 // First call to PTRACE_GETREGSET successful =>
574 has_working_ptrace_getregset = 1;
575 DEBUG(1, "detected a working PTRACE_GETREGSET\n");
577 assert (has_working_ptrace_getregset == 1);
578 return True;
580 else if (has_working_ptrace_getregset == 1) {
581 // We had a working call, but now it fails.
582 // This is unexpected.
583 ERROR(errno, "PTRACE_GETREGSET %ld\n", res);
584 return False;
585 } else {
586 // Check this is the first call:
587 assert (has_working_ptrace_getregset == -1);
588 if (errno == EIO) {
589 DEBUG(1, "detected a broken PTRACE_GETREGSET with EIO\n");
590 has_working_ptrace_getregset = 0;
591 // Fall over to the PTRACE_GETREGS or PTRACE_PEEKUSER case.
592 } else {
593 ERROR(errno, "broken PTRACE_GETREGSET unexpected errno %ld\n", res);
594 return False;
598 # endif
600 # ifdef HAVE_PTRACE_GETREGS
601 if (has_working_ptrace_getregs) {
602 // Platforms having GETREGS
603 long res;
604 DEBUG(1, "getregs PTRACE_GETREGS\n");
605 res = ptrace (PTRACE_GETREGS, pid, NULL, regs);
606 if (res == 0) {
607 if (has_working_ptrace_getregs == -1) {
608 // First call to PTRACE_GETREGS successful =>
609 has_working_ptrace_getregs = 1;
610 DEBUG(1, "detected a working PTRACE_GETREGS\n");
612 assert (has_working_ptrace_getregs == 1);
613 return True;
615 else if (has_working_ptrace_getregs == 1) {
616 // We had a working call, but now it fails.
617 // This is unexpected.
618 ERROR(errno, "PTRACE_GETREGS %ld\n", res);
619 return False;
620 } else {
621 // Check this is the first call:
622 assert (has_working_ptrace_getregs == -1);
623 if (errno == EIO) {
624 DEBUG(1, "detected a broken PTRACE_GETREGS with EIO\n");
625 has_working_ptrace_getregs = 0;
626 // Fall over to the PTRACE_PEEKUSER case.
627 } else {
628 ERROR(errno, "broken PTRACE_GETREGS unexpected errno %ld\n", res);
629 return False;
633 # endif
635 // We assume PTRACE_PEEKUSER is defined everywhere.
637 # ifdef PT_ENDREGS
638 long peek_bsz = PT_ENDREGS;
639 assert (peek_bsz <= regs_bsz);
640 # else
641 long peek_bsz = regs_bsz-1;
642 # endif
643 char *pregs = (char *) regs;
644 long offset;
645 errno = 0;
646 DEBUG(1, "getregs PTRACE_PEEKUSER(s) peek_bsz %ld\n", peek_bsz);
647 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
648 *(long *)(pregs+offset) = ptrace(PTRACE_PEEKUSER, pid, offset, NULL);
649 if (errno != 0) {
650 ERROR(errno, "PTRACE_PEEKUSER offset %ld\n", offset);
651 return False;
654 return True;
657 // If neither of PTRACE_GETREGSET PTRACE_GETREGS PTRACE_PEEKUSER have
658 // returned, then we are in serious trouble.
659 assert (0);
662 /* Set the registers of pid to regs.
663 regs_bsz value gives the length of *regs.
664 Returns True if all ok, otherwise False. */
665 static
666 Bool setregs (pid_t pid, void *regs, long regs_bsz)
668 DEBUG(1, "setregs regs_bsz %ld\n", regs_bsz);
670 // Note : the below is checking for GETREGSET, not SETREGSET
671 // as if one is defined and working, the other one should also work.
672 # ifdef HAVE_PTRACE_GETREGSET
673 if (has_working_ptrace_getregset) {
674 // Platforms having SETREGSET
675 long res;
676 elf_gregset_t elf_regs;
677 struct iovec iovec;
679 // setregset can never be called before getregset has done a runtime check.
680 assert (has_working_ptrace_getregset == 1);
681 DEBUG(1, "setregs PTRACE_SETREGSET sizeof(elf_regs) %zu\n",
682 sizeof(elf_regs));
683 iovec.iov_base = regs;
684 iovec.iov_len = sizeof(elf_regs);
685 res = ptrace (PTRACE_SETREGSET, pid, NT_PRSTATUS, &iovec);
686 if (res != 0) {
687 ERROR(errno, "PTRACE_SETREGSET %ld\n", res);
688 return False;
690 return True;
692 # endif
694 // Note : the below is checking for GETREGS, not SETREGS
695 // as if one is defined and working, the other one should also work.
696 # ifdef HAVE_PTRACE_GETREGS
697 if (has_working_ptrace_getregs) {
698 // Platforms having SETREGS
699 long res;
700 // setregs can never be called before getregs has done a runtime check.
701 assert (has_working_ptrace_getregs == 1);
702 DEBUG(1, "setregs PTRACE_SETREGS\n");
703 res = ptrace (PTRACE_SETREGS, pid, NULL, regs);
704 if (res != 0) {
705 ERROR(errno, "PTRACE_SETREGS %ld\n", res);
706 return False;
708 return True;
710 # endif
713 char *pregs = (char *) regs;
714 long offset;
715 long res;
716 # ifdef PT_ENDREGS
717 long peek_bsz = PT_ENDREGS;
718 assert (peek_bsz <= regs_bsz);
719 # else
720 long peek_bsz = regs_bsz-1;
721 # endif
722 errno = 0;
723 DEBUG(1, "setregs PTRACE_POKEUSER(s) %ld\n", peek_bsz);
724 for (offset = 0; offset < peek_bsz; offset = offset + sizeof(long)) {
725 res = ptrace(PTRACE_POKEUSER, pid, offset, *(long*)(pregs+offset));
726 if (errno != 0) {
727 ERROR(errno, "PTRACE_POKEUSER offset %ld res %ld\n", offset, res);
728 return False;
731 return True;
734 // If neither PTRACE_SETREGS not PTRACE_POKEUSER have returned,
735 // then we are in serious trouble.
736 assert (0);
739 /* Restore the registers to the saved value, then detaches from all threads */
740 static
741 void restore_and_detach (pid_t pid)
743 int res;
745 DEBUG(1, "restore_and_detach pid %d pid_of_save_regs %d\n",
746 pid, pid_of_save_regs);
748 if (pid_of_save_regs) {
749 /* In case the 'main pid' has been continued, we need to stop it
750 before resetting the registers. */
751 if (pid_of_save_regs_continued) {
752 pid_of_save_regs_continued = False;
753 if (!stop(pid_of_save_regs, "sigstop before reset regs"))
754 DEBUG(0, "Could not sigstop before reset");
757 DEBUG(1, "setregs restore registers pid %d\n", pid_of_save_regs);
758 if (!setregs(pid_of_save_regs, &user_save.regs, sizeof(user_save.regs))) {
759 ERROR(errno, "setregs restore registers pid %d after cont\n",
760 pid_of_save_regs);
763 /* Now, we transmit all the signals we have queued. */
764 if (signal_queue_sz > 0) {
765 int i;
766 for (i = 0; i < signal_queue_sz; i++) {
767 DEBUG(1, "PTRACE_CONT to transmit queued signal %d\n",
768 signal_queue[i].si_signo);
769 res = ptrace (PTRACE_CONT, pid_of_save_regs, NULL,
770 signal_queue[i].si_signo);
771 if (res != 0)
772 ERROR(errno, "PTRACE_CONT with signal %d\n",
773 signal_queue[i].si_signo);
774 if (!stop(pid_of_save_regs, "sigstop after transmit sig"))
775 DEBUG(0, "Could not sigstop after transmit sig");
777 free (signal_queue);
778 signal_queue = NULL;
779 signal_queue_sz = 0;
781 pid_of_save_regs = 0;
782 } else {
783 DEBUG(1, "PTRACE_SETREGS restore registers: no pid\n");
785 if (signal_queue)
786 ERROR (0, "One or more signals queued were not delivered. "
787 "First signal: %d\n", signal_queue[0].si_signo);
788 detach_from_all_threads(pid);
791 Bool invoker_invoke_gdbserver (pid_t pid)
793 long res;
794 Bool stopped;
795 # if defined(VGA_arm64)
796 /* arm64 is extra special, old glibc defined kernel user_pt_regs, but
797 newer glibc instead define user_regs_struct. */
798 # ifdef HAVE_SYS_USER_REGS
799 struct user_regs_struct user_mod;
800 # else
801 struct user_pt_regs user_mod;
802 # endif
803 # else
804 struct user user_mod;
805 # endif
806 Addr sp __attribute__((unused)); // Not used on all platforms.
808 /* A specific int value is passed to invoke_gdbserver, to check
809 everything goes according to the plan. */
810 const int check = 0x8BADF00D; // ate bad food.
812 const Addr bad_return = 0;
813 // A bad return address will be pushed on the stack.
814 // The function invoke_gdbserver cannot return. If ever it returns, a NULL
815 // address pushed on the stack should ensure this is detected.
817 /* Not yet attached. If problem, vgdb can abort,
818 no cleanup needed. */
820 DEBUG(1, "attach to 'main' pid %d\n", pid);
821 if (!attach(pid, "attach main pid")) {
822 ERROR(0, "error attach main pid %d\n", pid);
823 return False;
826 /* Now, we are attached. If problem, detach and return. */
828 if (!acquire_and_suspend_threads(pid)) {
829 detach_from_all_threads(pid);
830 /* if the pid does not exist anymore, we better stop */
831 if (kill(pid, 0) != 0)
832 XERROR (errno, "invoke_gdbserver: check for pid %d existence failed\n",
833 pid);
834 return False;
837 if (!getregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
838 detach_from_all_threads(pid);
839 return False;
841 user_save = user_mod;
843 #if defined(VGA_x86)
844 sp = user_mod.regs.esp;
845 #elif defined(VGA_amd64)
846 sp = user_mod.regs.rsp;
847 if (shared32 != NULL) {
848 /* 64bit vgdb speaking with a 32bit executable.
849 To have system call restart properly, we need to sign extend rax.
850 For more info:
851 web search '[patch] Fix syscall restarts for amd64->i386 biarch'
852 e.g. http://sourceware.org/ml/gdb-patches/2009-11/msg00592.html */
853 *(long *)&user_save.regs.rax = *(int*)&user_save.regs.rax;
854 DEBUG(1, "Sign extending %8.8lx to %8.8lx\n",
855 user_mod.regs.rax, user_save.regs.rax);
857 #elif defined(VGA_arm)
858 sp = user_mod.regs.uregs[13];
859 #elif defined(VGA_arm64)
860 sp = user_mod.sp;
861 #elif defined(VGA_ppc32)
862 sp = user_mod.regs.gpr[1];
863 #elif defined(VGA_ppc64be) || defined(VGA_ppc64le)
864 sp = user_mod.regs.gpr[1];
865 #elif defined(VGA_s390x)
866 sp = user_mod.regs.gprs[15];
867 #elif defined(VGA_mips32) || defined(VGA_nanomips)
868 long long *p = (long long *)user_mod.regs;
869 sp = p[29];
870 #elif defined(VGA_mips64)
871 sp = user_mod.regs[29];
872 #else
873 I_die_here : (sp) architecture missing in vgdb-invoker-ptrace.c
874 #endif
877 // the magic below is derived from spying what gdb sends to
878 // the (classical) gdbserver when invoking a C function.
879 if (shared32 != NULL) {
880 // vgdb speaking with a 32bit executable.
881 #if defined(VGA_x86) || defined(VGA_amd64)
882 const int regsize = 4;
883 int rw;
884 /* push check arg on the stack */
885 sp = sp - regsize;
886 DEBUG(1, "push check arg ptrace_write_memory\n");
887 assert(regsize == sizeof(check));
888 rw = ptrace_write_memory(pid, sp,
889 &check,
890 regsize);
891 if (rw != 0) {
892 ERROR(rw, "push check arg ptrace_write_memory");
893 detach_from_all_threads(pid);
894 return False;
897 sp = sp - regsize;
898 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
899 // Note that for a 64 bits vgdb, only 4 bytes of NULL bad_return
900 // are written.
901 rw = ptrace_write_memory(pid, sp,
902 &bad_return,
903 regsize);
904 if (rw != 0) {
905 ERROR(rw, "push bad_return return address ptrace_write_memory");
906 detach_from_all_threads(pid);
907 return False;
909 #if defined(VGA_x86)
910 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
911 // compiled in 32bits, speaking with a 32bits exe
912 user_mod.regs.ebp = sp; // bp set to sp
913 user_mod.regs.esp = sp;
914 user_mod.regs.eip = shared32->invoke_gdbserver;
915 user_mod.regs.orig_eax = -1L;
916 #elif defined(VGA_amd64)
917 /* set ebp, esp, eip and orig_eax to invoke gdbserver */
918 // compiled in 64bits, speaking with a 32bits exe
919 user_mod.regs.rbp = sp; // bp set to sp
920 user_mod.regs.rsp = sp;
921 user_mod.regs.rip = shared32->invoke_gdbserver;
922 user_mod.regs.orig_rax = -1L;
923 #else
924 I_die_here : not x86 or amd64 in x86/amd64 section/
925 #endif
927 #elif defined(VGA_ppc32) || defined(VGA_ppc64be) || defined(VGA_ppc64le)
928 user_mod.regs.nip = shared32->invoke_gdbserver;
929 user_mod.regs.trap = -1L;
930 /* put check arg in register 3 */
931 user_mod.regs.gpr[3] = check;
932 /* put NULL return address in Link Register */
933 user_mod.regs.link = bad_return;
935 #elif defined(VGA_arm)
936 /* put check arg in register 0 */
937 user_mod.regs.uregs[0] = check;
938 /* put NULL return address in Link Register */
939 user_mod.regs.uregs[14] = bad_return;
940 user_mod.regs.uregs[15] = shared32->invoke_gdbserver;
942 #elif defined(VGA_arm64)
943 XERROR(0, "TBD arm64: vgdb a 32 bits executable with a 64 bits exe");
945 #elif defined(VGA_s390x)
946 XERROR(0, "(fn32) s390x has no 32bits implementation");
947 #elif defined(VGA_mips32) || defined(VGA_nanomips)
948 /* put check arg in register 4 */
949 p[4] = check;
950 /* put NULL return address in ra */
951 p[31] = bad_return;
952 p[34] = shared32->invoke_gdbserver;
953 p[25] = shared32->invoke_gdbserver;
954 /* make stack space for args */
955 p[29] = sp - 32;
957 #elif defined(VGA_mips64)
958 assert(0); // cannot vgdb a 32 bits executable with a 64 bits exe
959 #else
960 I_die_here : architecture missing in vgdb-invoker-ptrace.c
961 #endif
964 else if (shared64 != NULL) {
965 #if defined(VGA_x86)
966 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
967 #elif defined(VGA_amd64)
968 // vgdb speaking with a 64 bit executable.
969 const int regsize = 8;
970 int rw;
972 /* give check arg in rdi */
973 user_mod.regs.rdi = check;
975 /* push return address on stack : return to breakaddr */
976 sp &= ~0xf; // keep the stack aligned on 16 bytes ...
977 sp = sp - 128; // do not touch the amd64 redzone
978 sp = sp - regsize;
979 DEBUG(1, "push bad_return return address ptrace_write_memory\n");
980 rw = ptrace_write_memory(pid, sp,
981 &bad_return,
982 sizeof(bad_return));
983 if (rw != 0) {
984 ERROR(rw, "push bad_return return address ptrace_write_memory");
985 detach_from_all_threads(pid);
986 return False;
989 /* set rbp, rsp, rip and orig_rax to invoke gdbserver */
990 user_mod.regs.rbp = sp; // bp set to sp
991 user_mod.regs.rsp = sp;
992 user_mod.regs.rip = shared64->invoke_gdbserver;
993 user_mod.regs.orig_rax = -1L;
995 #elif defined(VGA_arm)
996 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
997 #elif defined(VGA_arm64)
998 user_mod.regs[0] = check;
999 user_mod.sp = sp;
1000 user_mod.pc = shared64->invoke_gdbserver;
1001 /* put NULL return address in Link Register */
1002 user_mod.regs[30] = bad_return;
1004 #elif defined(VGA_ppc32)
1005 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
1006 #elif defined(VGA_ppc64be)
1007 Addr func_addr;
1008 Addr toc_addr;
1009 int rw;
1010 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver,
1011 &func_addr,
1012 sizeof(Addr));
1013 if (rw != 0) {
1014 ERROR(rw, "ppc64 read func_addr\n");
1015 detach_from_all_threads(pid);
1016 return False;
1018 rw = ptrace_read_memory(pid, shared64->invoke_gdbserver+8,
1019 &toc_addr,
1020 sizeof(Addr));
1021 if (rw != 0) {
1022 ERROR(rw, "ppc64 read toc_addr\n");
1023 detach_from_all_threads(pid);
1024 return False;
1026 // We are not pushing anything on the stack, so it is not
1027 // very clear why the sp has to be decreased, but it seems
1028 // needed. The ppc64 ABI might give some lights on this ?
1029 user_mod.regs.gpr[1] = sp - 220;
1030 user_mod.regs.gpr[2] = toc_addr;
1031 user_mod.regs.nip = func_addr;
1032 user_mod.regs.trap = -1L;
1033 /* put check arg in register 3 */
1034 user_mod.regs.gpr[3] = check;
1035 /* put bad_return return address in Link Register */
1036 user_mod.regs.link = bad_return;
1037 #elif defined(VGA_ppc64le)
1038 /* LE does not use the function pointer structure used in BE */
1039 user_mod.regs.nip = shared64->invoke_gdbserver;
1040 user_mod.regs.gpr[1] = sp - 512;
1041 user_mod.regs.gpr[12] = user_mod.regs.nip;
1042 user_mod.regs.trap = -1L;
1043 /* put check arg in register 3 */
1044 user_mod.regs.gpr[3] = check;
1045 /* put bad_return return address in Link Register */
1046 user_mod.regs.link = bad_return;
1047 #elif defined(VGA_s390x)
1048 /* put check arg in register r2 */
1049 user_mod.regs.gprs[2] = check;
1050 /* bad_return Return address is in r14 */
1051 user_mod.regs.gprs[14] = bad_return;
1052 /* minimum stack frame */
1053 sp = sp - 160;
1054 user_mod.regs.gprs[15] = sp;
1055 /* set program counter */
1056 user_mod.regs.psw.addr = shared64->invoke_gdbserver;
1057 #elif defined(VGA_mips32) || defined(VGA_nanomips)
1058 assert(0); // cannot vgdb a 64 bits executable with a 32 bits exe
1059 #elif defined(VGA_mips64)
1060 /* put check arg in register 4 */
1061 user_mod.regs[4] = check;
1062 /* put NULL return address in ra */
1063 user_mod.regs[31] = bad_return;
1064 user_mod.regs[34] = shared64->invoke_gdbserver;
1065 user_mod.regs[25] = shared64->invoke_gdbserver;
1066 #else
1067 I_die_here: architecture missing in vgdb-invoker-ptrace.c
1068 #endif
1070 else {
1071 assert(0);
1074 if (!setregs(pid, &user_mod.regs, sizeof(user_mod.regs))) {
1075 detach_from_all_threads(pid);
1076 return False;
1078 /* Now that we have modified the registers, we set
1079 pid_of_save_regs to indicate that restore_and_detach
1080 must restore the registers in case of cleanup. */
1081 pid_of_save_regs = pid;
1082 pid_of_save_regs_continued = False;
1085 /* We PTRACE_CONT-inue pid.
1086 Either gdbserver will be invoked directly (if all
1087 threads are interruptible) or gdbserver will be
1088 called soon by the scheduler. In the first case,
1089 pid will stop on the break inserted above when
1090 gdbserver returns. In the 2nd case, the break will
1091 be encountered directly. */
1092 DEBUG(1, "PTRACE_CONT to invoke\n");
1093 res = ptrace (PTRACE_CONT, pid, NULL, NULL);
1094 if (res != 0) {
1095 ERROR(errno, "PTRACE_CONT\n");
1096 restore_and_detach(pid);
1097 return False;
1099 pid_of_save_regs_continued = True;
1100 /* Wait for SIGSTOP generated by m_gdbserver.c give_control_back_to_vgdb */
1101 stopped = waitstopped (pid, SIGSTOP,
1102 "waitpid status after PTRACE_CONT to invoke");
1103 if (stopped) {
1104 /* Here pid has properly stopped on the break. */
1105 pid_of_save_regs_continued = False;
1106 restore_and_detach(pid);
1107 return True;
1108 } else {
1109 /* Whatever kind of problem happened. We shutdown. */
1110 shutting_down = True;
1111 return False;
1115 void invoker_cleanup_restore_and_detach(void *v_pid)
1117 DEBUG(1, "invoker_cleanup_restore_and_detach dying: %d\n", dying);
1118 if (!dying)
1119 restore_and_detach(*(int*)v_pid);
1122 void invoker_restrictions_msg(void)
1126 void invoker_valgrind_dying(void)
1128 /* Avoid messing up with registers of valgrind when it is dying. */
1129 pid_of_save_regs_continued = False;
1130 dying = True;