2 * See the dyninst/COPYRIGHT file for copyright information.
4 * We provide the Paradyn Tools (below described as "Paradyn")
5 * on an AS IS basis, and do not warrant its validity or performance.
6 * We reserve the right to update, modify, or discontinue this
7 * software at any time. We shall have no obligation to supply such
8 * updates or modifications or any other form of support to you.
10 * By your use of Paradyn, you understand and agree that we (or any
11 * other person or entity with proprietary rights in Paradyn) are
12 * under no obligation to provide either maintenance services,
13 * update services, notices of latent defects, or correction of
14 * defects for Paradyn.
16 * This library is free software; you can redistribute it and/or
17 * modify it under the terms of the GNU Lesser General Public
18 * License as published by the Free Software Foundation; either
19 * version 2.1 of the License, or (at your option) any later version.
21 * This library is distributed in the hope that it will be useful,
22 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24 * Lesser General Public License for more details.
26 * You should have received a copy of the GNU Lesser General Public
27 * License along with this library; if not, write to the Free Software
28 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31 #include <sys/types.h>
33 #include <sys/syscall.h>
44 #include "common/h/dyn_regs.h"
45 #include "common/h/dyntypes.h"
47 #include "common/src/pathName.h"
49 #include "Generator.h"
53 #include "PlatFeatures.h"
57 #include "int_thread_db.h"
59 #include "int_handler.h"
61 #include "int_event.h"
65 #include "common/src/linuxKludges.h"
66 #include "common/src/parseauxv.h"
68 #include "boost/shared_ptr.hpp"
70 //needed by GETREGSET/SETREGSET
71 #if defined(arch_aarch64)
73 #include<sys/procfs.h>
78 // Before glibc-2.7, sys/ptrace.h lacked PTRACE_O_* and PTRACE_EVENT_*, so we
79 // need them from linux/ptrace.h. (Conditionally, as later glibc conflicts.)
80 #if !__GLIBC_PREREQ(2,7)
81 #include <linux/ptrace.h>
84 using namespace Dyninst;
85 using namespace ProcControlAPI;
87 #if defined(WITH_SYMLITE)
88 #include "symlite/h/SymLite-elf.h"
89 #elif defined(WITH_SYMTAB_API)
90 #include "symtabAPI/h/SymtabReader.h"
92 #error "No defined symbol reader"
95 #if !defined(PTRACE_GETREGS) && defined(PPC_PTRACE_GETREGS)
96 #define PTRACE_GETREGS PPC_PTRACE_GETREGS
99 #if !defined(PTRACE_SETREGS) && defined(PPC_PTRACE_SETREGS)
100 #define PTRACE_SETREGS PPC_PTRACE_SETREGS
103 #if defined(arch_aarch64)
104 #define SYSCALL_EXIT_BREAKPOINT
107 static pid_t P_gettid();
108 static bool t_kill(int pid, int sig);
110 using namespace Dyninst;
113 static GeneratorLinux *gen = NULL;
115 Generator *Generator::getDefaultGenerator()
118 gen = new GeneratorLinux();
122 return static_cast<Generator *>(gen);
125 bool GeneratorLinux::initialize()
130 sigemptyset(&usr2_set);
131 sigaddset(&usr2_set, SIGUSR2);
132 result = pthread_sigmask(SIG_UNBLOCK, &usr2_set, NULL);
134 perr_printf("Unable to unblock SIGUSR2: %s\n", strerror(result));
137 generator_lwp = P_gettid();
138 generator_pid = P_getpid();
142 bool GeneratorLinux::canFastHandle()
147 ArchEvent *GeneratorLinux::getEvent(bool block)
151 //Block (or not block) in waitpid to receive a OS event
153 options |= block ? 0 : WNOHANG;
154 pthrd_printf("%s in waitpid\n", block ? "blocking" : "polling");
156 if (isExitingState())
158 int pid = waitpid(-1, &status, options);
160 ArchEventLinux *newevent = NULL;
163 if (errsv == EINTR) {
164 pthrd_printf("waitpid interrupted\n");
165 newevent = new ArchEventLinux(true);
168 perr_printf("Error. waitpid recieved error %s\n", strerror(errsv));
169 newevent = new ArchEventLinux(errsv);
173 if (dyninst_debug_proccontrol)
175 pthrd_printf("Waitpid return status %d for pid %d:\n", status, pid);
176 if (WIFEXITED(status))
177 pthrd_printf("Exited with %d\n", WEXITSTATUS(status));
178 else if (WIFSIGNALED(status))
179 pthrd_printf("Exited with signal %d\n", WTERMSIG(status));
180 else if (WIFSTOPPED(status))
181 pthrd_printf("Stopped with signal %d\n", WSTOPSIG(status));
182 #if defined(WIFCONTINUED)
183 else if (WIFCONTINUED(status))
184 perr_printf("Continued with signal SIGCONT (Unexpected)\n");
187 pthrd_printf("Unable to interpret waitpid return.\n");
190 newevent = new ArchEventLinux(pid, status);
194 GeneratorLinux::GeneratorLinux() :
195 GeneratorMT(std::string("Linux Generator")),
199 decoders.insert(new DecoderLinux());
202 static volatile int on_sigusr2_hit;
203 static void on_sigusr2(int)
208 void GeneratorLinux::evictFromWaitpid()
212 if (generator_pid != P_getpid())
215 //Throw a SIGUSR2 at the generator thread. This will kick it out of
216 // a waitpid with EINTR, and allow it to exit. Will do nothing if not
217 // blocked in waitpid.
219 //There's a subtle race condition here, which we can't easily fix.
220 // The generator thread could be just before waitpid, but after
221 // it's exit test when the signal hits. We won't throw EINTR because
222 // we're not in waitpid yet, and we won't retest the exiting state.
223 // This exact kind of race is why we have things like pselect, but
224 // waitpid doesn't have a pwaitpid, so we're stuck.
225 struct sigaction newact, oldact;
226 memset(&newact, 0, sizeof(struct sigaction));
227 memset(&oldact, 0, sizeof(struct sigaction));
228 newact.sa_handler = on_sigusr2;
230 int result = sigaction(SIGUSR2, &newact, &oldact);
233 perr_printf("Error signaling generator thread: %s\n", strerror(error));
237 bool bresult = t_kill(generator_lwp, SIGUSR2);
238 while (bresult && !on_sigusr2_hit) {
239 //Don't use a lock because pthread_mutex_unlock is not signal safe
243 result = sigaction(SIGUSR2, &oldact, NULL);
246 perr_printf("Error signaling generator thread: %s\n", strerror(error));
251 GeneratorLinux::~GeneratorLinux()
257 DecoderLinux::DecoderLinux()
261 DecoderLinux::~DecoderLinux()
265 unsigned DecoderLinux::getPriority() const
267 return Decoder::default_priority;
270 Dyninst::Address DecoderLinux::adjustTrapAddr(Dyninst::Address addr, Dyninst::Architecture arch)
272 if (arch == Dyninst::Arch_x86 || arch == Dyninst::Arch_x86_64) {
275 if (arch == Dyninst::Arch_aarch64){
281 bool DecoderLinux::decode(ArchEvent *ae, std::vector<Event::ptr> &events)
284 ArchEventLinux *archevent = static_cast<ArchEventLinux *>(ae);
286 int_process *proc = NULL;
287 linux_process *lproc = NULL;
288 int_thread *thread = ProcPool()->findThread(archevent->pid);
289 linux_thread *lthread = NULL;
291 proc = thread->llproc();
292 lthread = dynamic_cast<linux_thread *>(thread);
295 lproc = dynamic_cast<linux_process *>(proc);
299 pthrd_printf("Warning: could not find event for process %d\n", archevent->pid);
302 Event::ptr event = Event::ptr();
303 ArchEventLinux *child = NULL;
304 ArchEventLinux *parent = NULL;
306 pthrd_printf("Decoding event for %d/%d\n", proc ? proc->getPid() : -1,
307 thread ? thread->getLWP() : -1);
309 const int status = archevent->status;
310 pthrd_printf("ARM-debug: status 0x%x\n",status);
311 if (WIFSTOPPED(status))
313 const int stopsig = WSTOPSIG(status);
315 pthrd_printf("Decoded to signal %d\n", stopsig);
318 case (SIGTRAP | 0x80): //PTRACE_O_TRACESYSGOOD
319 if (!proc || !thread) {
320 //Legacy event on old process?
323 pthrd_printf("Decoded event to syscall-stop on %d/%d\n",
324 proc->getPid(), thread->getLWP());
325 if (lthread->hasPostponedSyscallEvent()) {
327 archevent = lthread->getPostponedSyscallEvent();
328 ext = archevent->event_ext;
330 // in case of a fake syscall exit BP is inserted,
331 // it should be cleared when the actual stop is received.
332 Dyninst::MachRegisterVal addr;
333 int result = thread->plat_getRegister(MachRegister::getPC(proc->getTargetArch()), addr);
335 perr_printf("Failed to read PC address upon SIGTRAP|0x80\n");
338 if( lthread->isSet_fakeSyscallExitBp &&
339 lthread->addr_fakeSyscallExitBp == addr){
340 // do not handle the bp and clear the bp.
341 bool rst = lthread->proc()->rmBreakpoint(addr, lthread->BPptr_fakeSyscallExitBp );
343 perr_printf("ARM-error: Failed to remove inserted BP, addr %p.\n",
346 lthread->isSet_fakeSyscallExitBp = false;
350 case PTRACE_EVENT_FORK:
351 case PTRACE_EVENT_CLONE:
352 pthrd_printf("Resuming %s event after syscall exit on %d/%d\n",
353 ext == PTRACE_EVENT_FORK ? "fork" : "clone",
354 proc->getPid(), thread->getLWP());
355 if (!archevent->findPairedEvent(parent, child)) {
356 pthrd_printf("Parent half of paired event, postponing decode "
357 "until child arrives\n");
358 archevent->postponePairedEvent();
362 case PTRACE_EVENT_EXEC:
363 pthrd_printf("Resuming exec event after syscall exit on %d/%d\n",
364 proc->getPid(), thread->getLWP());
365 event = Event::ptr(new EventExec(EventType::Post));
366 event->setSyncType(Event::sync_process);
371 // If we're expecting syscall events other than postponed ones, fall through the rest of
372 // the event handling
373 if(!thread->syscallMode())
375 perr_printf("Received an unexpected syscall TRAP\n");
381 //The child half of an event pair. Find the parent or postpone it.
382 if (!archevent->findPairedEvent(parent, child)) {
383 pthrd_printf("Child half of paired event, postponing decode "
384 "until parent arrives\n");
385 archevent->postponePairedEvent();
390 if (lthread->hasPendingStop()) {
391 pthrd_printf("Recieved pending SIGSTOP on %d/%d\n",
392 thread->llproc()->getPid(), thread->getLWP());
393 event = Event::ptr(new EventStop());
396 if (lthread->getGeneratorState().getState() == int_thread::neonatal ||
397 lthread->getGeneratorState().getState() == int_thread::neonatal_intermediate)
399 //Discovered thread from refresh
400 pthrd_printf("Decoded event to thread bootstrap on %d/%d\n",
401 proc->getPid(), thread->getLWP());
402 event = Event::ptr(new EventBootstrap());
409 Dyninst::MachRegisterVal addr;
410 result = thread->plat_getRegister(MachRegister::getPC(proc->getTargetArch()), addr);
412 fprintf(stderr, "Failed to read PC address upon crash\n");
414 fprintf(stderr, "Got SIGTRAP at %lx\n", addr);
415 Dyninst::MachRegisterVal X0;
416 result = thread->plat_getRegister(Dyninst::aarch64::x0 ,X0);
417 pthrd_printf("ARM-debug: x0 is 0x%lx/%u\n", X0, X0);
422 bool postpone = false;
424 case PTRACE_EVENT_EXIT:
425 if (!proc || !thread) {
426 //Legacy event on old process.
429 pthrd_printf("Decoded event to pre-exit on %d/%d\n",
430 proc->getPid(), thread->getLWP());
431 if (thread->getLWP() == proc->getPid())
433 unsigned long eventmsg = 0x0;
434 int result = do_ptrace((pt_req)PTRACE_GETEVENTMSG, (pid_t) thread->getLWP(),
439 perr_printf("Error getting event message from exit\n");
441 proc->setLastError(err_exited, "Process exited during operation");
444 int exitcode = (int)eventmsg;
445 exitcode = WEXITSTATUS(exitcode);
447 pthrd_printf("Decoded event to pre-exit of process %d/%d with code %i\n",
448 proc->getPid(), thread->getLWP(), exitcode);
449 event = Event::ptr(new EventExit(EventType::Pre, exitcode));
451 for (int_threadPool::iterator j = proc->threadPool()->begin();
452 j != proc->threadPool()->end(); ++j)
454 dynamic_cast<linux_thread*>(*j)->setGeneratorExiting();
458 EventLWPDestroy::ptr lwp_ev = EventLWPDestroy::ptr(new EventLWPDestroy(EventType::Pre));
460 event->setThread(thread->thread());
461 lproc->decodeTdbLWPExit(lwp_ev);
462 lthread->setGeneratorExiting();
464 thread->setExitingInGenerator(true);
466 case PTRACE_EVENT_FORK:
467 case PTRACE_EVENT_CLONE: {
468 if (!proc || !thread) {
469 //Legacy event on old process.
472 pthrd_printf("Decoded event to %s on %d/%d\n",
473 ext == PTRACE_EVENT_FORK ? "fork" : "clone",
474 proc->getPid(), thread->getLWP());
475 unsigned long cpid_l = 0x0;
476 int result = do_ptrace((pt_req) PTRACE_GETEVENTMSG, (pid_t) thread->getLWP(),
480 perr_printf("Error getting event message from fork/clone\n");
482 proc->setLastError(err_exited, "Process exited during operation");
485 pid_t cpid = (pid_t) cpid_l;
486 archevent->child_pid = cpid;
492 case PTRACE_EVENT_EXEC: {
493 if (!proc || !thread) {
494 //Legacy event on old process.
497 pthrd_printf("Decoded event to exec on %d/%d\n",
498 proc->getPid(), thread->getLWP());
505 * Due to arm kenel bug, if tracer continues the tracee with PTRACE_SYSCALL,
506 * the kernel doesn't check the changed flags again before exiting.
507 * Hence, I assume syscalls exit quietly and normally.
508 * And move the code for exit stop here.
509 * "Postpone" is actually "postponed" below.
511 #if defined(arch_aarch64)
512 #define DISABLE_POSTPONE
515 #if defined(DISABLE_POSTPONE)
516 #if defined(SYSCALL_EXIT_BREAKPOINT)
517 #undef DISABLE_POSTPONE
522 archevent->event_ext = ext;
524 #if !defined(DISABLE_POSTPONE)
525 pthrd_printf("Postponing event until syscall exit on %d/%d\n",
526 proc->getPid(), thread->getLWP());
527 event = Event::ptr(new EventPostponedSyscall());
528 lthread->postponeSyscallEvent(archevent);
531 #else //disable postpone
532 pthrd_printf("ARM-warning: syscall is not postponed on %d/%d.\n",
533 proc->getPid(), thread->getLWP() );
536 case PTRACE_EVENT_FORK:
537 case PTRACE_EVENT_CLONE:
538 pthrd_printf("Handle %s event after syscall enter on %d/%d\n",
539 ext == PTRACE_EVENT_FORK ? "fork" : "clone",
540 proc->getPid(), thread->getLWP());
541 if (!archevent->findPairedEvent(parent, child)) {
542 pthrd_printf("Parent half of paired event, postponing decode "
543 "until child arrives\n");
544 archevent->postponePairedEvent();
548 case PTRACE_EVENT_EXEC:
549 pthrd_printf("Resuming exec event after syscall exit on %d/%d\n",
550 proc->getPid(), thread->getLWP());
551 event = Event::ptr(new EventExec(EventType::Post));
552 event->setSyncType(Event::sync_process);
559 if (proc->getState() == int_process::neonatal_intermediate) {
560 pthrd_printf("Decoded event to bootstrap on %d/%d\n",
561 proc->getPid(), thread->getLWP());
562 event = Event::ptr(new EventBootstrap());
565 Dyninst::MachRegisterVal addr;
566 Dyninst::Address adjusted_addr;
568 result = thread->plat_getRegister(MachRegister::getPC(proc->getTargetArch()), addr);
571 pthrd_printf("ARM-debug: PC = 0x%lx\n", addr);
573 proc->plat_readMem(thread, buffer_inst, addr, 4);
574 printf("0x%8x\n", *((unsigned int*)buffer_inst) );
578 perr_printf("Failed to read PC address upon SIGTRAP\n");
581 adjusted_addr = adjustTrapAddr(addr, proc->getTargetArch());
583 // handle the fake syscall exit stop bp.
584 #if defined(SYSCALL_EXIT_BREAKPOINT)
585 if( lthread->addr_fakeSyscallExitBp == adjusted_addr
586 && lthread->isSet_fakeSyscallExitBp){
587 //do the same as syscall_exit_stop signal
588 if (lthread->hasPostponedSyscallEvent()) {
590 archevent = lthread->getPostponedSyscallEvent();
591 ext = archevent->event_ext;
593 case PTRACE_EVENT_FORK:
594 case PTRACE_EVENT_CLONE:
595 pthrd_printf("Resuming %s event after syscall exit on %d/%d\n",
596 ext == PTRACE_EVENT_FORK ? "fork" : "clone",
597 proc->getPid(), thread->getLWP());
598 if (!archevent->findPairedEvent(parent, child)) {
599 pthrd_printf("Parent half of paired event, postponing decode "
600 "until child arrives\n");
601 archevent->postponePairedEvent();
605 case PTRACE_EVENT_EXEC:
606 pthrd_printf("Resuming exec event after syscall exit on %d/%d\n",
607 proc->getPid(), thread->getLWP());
608 event = Event::ptr(new EventExec(EventType::Post));
609 event->setSyncType(Event::sync_process);
617 if (rpcMgr()->isRPCTrap(thread, adjusted_addr)) {
618 pthrd_printf("Decoded event to rpc completion on %d/%d at %lx\n",
619 proc->getPid(), thread->getLWP(), adjusted_addr);
620 event = Event::ptr(new EventRPC(thread->runningRPC()->getWrapperForDecode()));
624 bp_instance *clearingbp = thread->isClearingBreakpoint();
625 if (thread->singleStep() && clearingbp) {
626 pthrd_printf("Decoded event to breakpoint restore\n");
627 event = Event::ptr(new EventBreakpointRestore(new int_eventBreakpointRestore(clearingbp)));
628 if (thread->singleStepUserMode()) {
629 Event::ptr subservient_ss = EventSingleStep::ptr(new EventSingleStep());
630 subservient_ss->setProcess(proc->proc());
631 subservient_ss->setThread(thread->thread());
632 subservient_ss->setSyncType(Event::sync_thread);
633 event->addSubservientEvent(subservient_ss);
638 // Need to distinguish case where the thread is single-stepped to a
639 // breakpoint and when a single step hits a breakpoint.
641 // If no forward progress was made due to a single step, then a
642 // breakpoint was hit
643 sw_breakpoint *ibp = proc->getBreakpoint(adjusted_addr);
644 if (thread->singleStep() && !ibp) {
645 pthrd_printf("Decoded event to single step on %d/%d\n",
646 proc->getPid(), thread->getLWP());
647 event = Event::ptr(new EventSingleStep());
651 if (thread->syscallMode() && !ibp) {
652 if (thread->preSyscall()) {
653 pthrd_printf("Decoded event to pre-syscall on %d/%d\n",
654 proc->getPid(), thread->getLWP());
655 event = Event::ptr(new EventPreSyscall());
658 pthrd_printf("Decoded event to post-syscall on %d/%d\n",
659 proc->getPid(), thread->getLWP());
660 event = Event::ptr(new EventPostSyscall());
665 if (ibp && ibp != clearingbp) {
666 pthrd_printf("Decoded breakpoint on %d/%d at %lx\n", proc->getPid(),
667 thread->getLWP(), adjusted_addr);
668 EventBreakpoint::ptr event_bp = EventBreakpoint::ptr(new EventBreakpoint(new int_eventBreakpoint(adjusted_addr, ibp, thread)));
670 event->setThread(thread->thread());
672 if (thread->singleStepUserMode() && !proc->plat_breakpointAdvancesPC()) {
673 Event::ptr subservient_ss = EventSingleStep::ptr(new EventSingleStep());
674 subservient_ss->setProcess(proc->proc());
675 subservient_ss->setThread(thread->thread());
676 subservient_ss->setSyncType(Event::sync_thread);
677 event->addSubservientEvent(subservient_ss);
680 if (adjusted_addr == lproc->getLibBreakpointAddr()) {
681 pthrd_printf("Breakpoint is library load/unload\n");
682 EventLibrary::ptr lib_event = EventLibrary::ptr(new EventLibrary());
683 lib_event->setThread(thread->thread());
684 lib_event->setProcess(proc->proc());
685 lib_event->setSyncType(Event::sync_thread);
686 event->addSubservientEvent(lib_event);
690 async_ret_t result = lproc->decodeTdbBreakpoint(event_bp);
691 if (result == aret_error) {
692 //Not really an error, just how we say that it isn't
696 if (result == aret_success) {
697 //decodeTdbBreakpoint added a subservient event if this hits
698 pthrd_printf("Breakpoint was thread event\n");
701 if (result == aret_async) {
702 pthrd_printf("decodeTdbBreakpoint returned async\n");
703 set<response::ptr> resps;
704 lproc->getMemCache()->getPendingAsyncs(resps);
705 pthrd_printf("%d asyncs are pending\n", (int) resps.size());
706 int_process::waitForAsyncEvent(resps);
714 EventBreakpoint::ptr evhwbp = thread->decodeHWBreakpoint(resp);
716 pthrd_printf("Decoded SIGTRAP as hardware breakpoint\n");
723 pthrd_printf("Decoded event to signal %d on %d/%d\n",
724 stopsig, proc->getPid(), thread->getLWP());
727 if (stopsig == 11 || stopsig == 4) {
728 Dyninst::MachRegisterVal addr;
729 result = thread->plat_getRegister(MachRegister::getPC(proc->getTargetArch()), addr);
731 fprintf(stderr, "Failed to read PC address upon crash\n");
733 fprintf(stderr, "Got crash at %lx\n", addr);
737 event = Event::ptr(new EventSignal(stopsig));
739 if (event && event->getSyncType() == Event::unset)
740 event->setSyncType(Event::sync_thread);
742 else if ((WIFEXITED(status) || WIFSIGNALED(status)) &&
743 (!proc || !thread || thread->getGeneratorState().getState() == int_thread::exited))
745 //This can happen if the debugger process spawned the
746 // child, but then detached. We recieve the child process
747 // exit (because we're the parent), but are no longer debugging it.
748 // We'll just drop this event on the ground.
749 //Also seen when multiple termination signals hit a multi-threaded process
750 // we're debugging. We'll keep pulling termination signals from the
751 // a defunct process. Similar to above, we'll drop this event
755 else if (WIFEXITED(status) && proc->getPid() != thread->getLWP())
757 int exitcode = WEXITSTATUS(status);
759 pthrd_printf("Decoded exit of thread %d/%d with code %d\n",
760 proc->getPid(), thread->getLWP(), exitcode);
761 EventLWPDestroy::ptr lwp_ev = EventLWPDestroy::ptr(new EventLWPDestroy(EventType::Post));
763 event->setSyncType(Event::async);
764 event->setThread(thread->thread());
765 lproc->decodeTdbLWPExit(lwp_ev);
766 thread->getGeneratorState().setState(int_thread::exited);
768 else if (WIFEXITED(status) || WIFSIGNALED(status)) {
769 if (WIFEXITED(status)) {
770 int exitcode = WEXITSTATUS(status);
771 pthrd_printf("Decoded event to exit of process %d/%d with code %d\n",
772 proc->getPid(), thread->getLWP(), exitcode);
773 event = Event::ptr(new EventExit(EventType::Post, exitcode));
776 int termsig = WTERMSIG(status);
777 if( proc->wasForcedTerminated() ) {
778 pthrd_printf("Decoded event to force terminate of %d/%d\n",
779 proc->getPid(), thread->getLWP());
780 event = Event::ptr(new EventForceTerminate(termsig));
782 pthrd_printf("Decoded event to crash of %d/%d with signal %d\n",
783 proc->getPid(), thread->getLWP(), termsig);
784 event = Event::ptr(new EventCrash(termsig));
787 event->setSyncType(Event::sync_process);
788 int_threadPool::iterator i = proc->threadPool()->begin();
789 for (; i != proc->threadPool()->end(); i++) {
790 (*i)->getGeneratorState().setState(int_thread::exited);
796 //Paired event decoded
798 thread = ProcPool()->findThread(parent->pid);
800 proc = thread->llproc();
801 if (parent->event_ext == PTRACE_EVENT_FORK)
802 event = Event::ptr(new EventFork(EventType::Post, child->pid));
803 else if (parent->event_ext == PTRACE_EVENT_CLONE)
804 event = Event::ptr(new EventNewLWP(child->pid, (int) int_thread::as_created_attached));
807 event->setSyncType(Event::sync_thread);
808 ProcPool()->removeDeadThread(child->pid);
813 if (archevent && ProcPool()->deadThread(archevent->pid)) {
818 //Single event decoded
822 assert(proc->proc());
823 assert(thread->thread());
826 event->setThread(thread->thread());
827 event->setProcess(proc->proc());
828 events.push_back(event);
833 #if defined(arch_power)
834 #define DEFAULT_PROCESS_TYPE linux_ppc_process
835 #define DEFAULT_THREAD_TYPE linux_ppc_thread
836 #elif defined(arch_x86) || defined(arch_x86_64)
837 #define DEFAULT_PROCESS_TYPE linux_x86_process
838 #define DEFAULT_THREAD_TYPE linux_x86_thread
839 #elif defined(arch_aarch64) || defined(arch_aarch32)
840 #define DEFAULT_PROCESS_TYPE linux_arm_process
841 #define DEFAULT_THREAD_TYPE linux_arm_thread
844 int_process *int_process::createProcess(Dyninst::PID p, std::string e)
846 std::vector<std::string> a;
848 std::vector<std::string> envp;
849 LinuxPtrace::getPtracer(); //Make sure ptracer thread is initialized
850 linux_process *newproc = new DEFAULT_PROCESS_TYPE(p, e, a, envp, f);
852 return static_cast<int_process *>(newproc);
855 int_process *int_process::createProcess(std::string e, std::vector<std::string> a, std::vector<std::string> envp,
858 LinuxPtrace::getPtracer(); //Make sure ptracer thread is initialized
859 linux_process *newproc = new DEFAULT_PROCESS_TYPE(0, e, a, envp, f);
861 return static_cast<int_process *>(newproc);
864 int_process *int_process::createProcess(Dyninst::PID pid_, int_process *p)
866 linux_process *newproc = new DEFAULT_PROCESS_TYPE(pid_, p);
868 return static_cast<int_process *>(newproc);
871 int linux_process::computeAddrWidth()
875 * It's surprisingly difficult to figure out the word size of a process
876 * without looking at the files it loads (we want to avoid disk accesses).
878 * /proc/PID/auxv offers a hackish opportunity to do this. auxv contains
879 * a list of name value pairs. On 64 bit processes these name values are
880 * a uint64/uint64 combo and on 32 bit processes they're uint32/uint32.
882 * The names are from a set of small integers (ranging from 0 to 37 at
883 * the time of this writing). Since these are small numbers, the top half
884 * of name word will be 0x0 on 64 bit processes. On 32-bit process this
885 * word will contain a value, of which some should be non-zero.
887 * We'll thus check every word that is 1 mod 4 for little-endian machines,
888 * or 0 mod 4 for big-endian. If all words of either stripe are 0x0, we
889 * assume we're looking at a 64-bit process.
891 uint32_t buffer[256];
894 snprintf(auxv_name, 64, "/proc/%d/auxv", getPid());
895 int fd = open(auxv_name, O_RDONLY);
897 pthrd_printf("Couldn't open %s to determine address width: %s",
898 auxv_name, strerror(errno));
902 ssize_t result = read(fd, buffer, sizeof(buffer));
903 ssize_t words_read = (result / sizeof(uint32_t)) & ~3;
906 // We want to check the highest 4 bytes of each integer
907 // On big-endian systems, these come first in memory
908 bool be_zero = true, le_zero = true;
909 for (ssize_t i=0; i<words_read; i+= 4)
911 be_zero &= buffer[i] == 0;
912 le_zero &= buffer[i+1] == 0;
915 int word_size = (be_zero || le_zero) ? 8 : 4;
916 pthrd_printf("computeAddrWidth: word size is %d\n", word_size);
920 linux_process::linux_process(Dyninst::PID p, std::string e, std::vector<std::string> a,
921 std::vector<std::string> envp, std::map<int,int> f) :
922 int_process(p, e, a, envp, f),
923 resp_process(p, e, a, envp, f),
924 sysv_process(p, e, a, envp, f),
925 unix_process(p, e, a, envp, f),
926 thread_db_process(p, e, a, envp, f),
927 indep_lwp_control_process(p, e, a, envp, f),
928 mmap_alloc_process(p, e, a, envp, f),
929 int_followFork(p, e, a, envp, f),
930 int_signalMask(p, e, a, envp, f),
931 int_LWPTracking(p, e, a, envp, f),
932 int_memUsage(p, e, a, envp, f)
936 linux_process::linux_process(Dyninst::PID pid_, int_process *p) :
937 int_process(pid_, p),
938 resp_process(pid_, p),
939 sysv_process(pid_, p),
940 unix_process(pid_, p),
941 thread_db_process(pid_, p),
942 indep_lwp_control_process(pid_, p),
943 mmap_alloc_process(pid_, p),
944 int_followFork(pid_, p),
945 int_signalMask(pid_, p),
946 int_LWPTracking(pid_, p),
947 int_memUsage(pid_, p)
951 linux_process::~linux_process()
955 bool linux_process::plat_create()
957 //Triggers plat_create_int on ptracer thread.
958 return LinuxPtrace::getPtracer()->plat_create(this);
961 bool linux_process::plat_create_int()
967 pthrd_printf("Could not fork new process for %s: %s\n",
968 executable.c_str(), strerror(errnum));
969 setLastError(err_internal, "Unable to fork new process");
975 // Make sure cleanup on failure goes smoothly
976 ProcPool()->condvar()->unlock();
979 long int result = ptrace((pt_req) PTRACE_TRACEME, 0, 0, 0);
982 pthrd_printf("Failed to execute a PTRACE_TRACME. Odd.\n");
983 setLastError(err_internal, "Unable to debug trace new process");
993 bool linux_process::plat_getOSRunningStates(std::map<Dyninst::LWP, bool> &runningStates) {
994 vector<Dyninst::LWP> lwps;
995 if( !getThreadLWPs(lwps) ) {
996 pthrd_printf("Failed to determine lwps for process %d\n", getPid());
997 setLastError(err_noproc, "Failed to find /proc files for debuggee");
1001 for(vector<Dyninst::LWP>::iterator i = lwps.begin();
1002 i != lwps.end(); ++i)
1004 char proc_stat_name[128];
1007 int paren_level = 1;
1009 snprintf(proc_stat_name, 128, "/proc/%d/stat", *i);
1010 FILE *sfile = fopen(proc_stat_name, "r");
1012 if (sfile == NULL) {
1013 pthrd_printf("Failed to open /proc/%d/stat file\n", *i);
1014 setLastError(err_noproc, "Failed to find /proc files for debuggee");
1017 if( fread(sstat, 1, 256, sfile) == 0 ) {
1018 pthrd_printf("Failed to read /proc/%d/stat file \n", *i);
1019 setLastError(err_noproc, "Failed to find /proc files for debuggee");
1028 while (*status != '\0' && *(status++) != '(') ;
1029 while (*status != '\0' && paren_level != 0) {
1030 if (*status == '(') paren_level++;
1031 if (*status == ')') paren_level--;
1035 while (*status == ' ') status++;
1037 runningStates.insert(make_pair(*i, (*status != 'T')));
1043 // Ubuntu 10.10 and other hardened systems do not allow arbitrary ptrace_attaching; instead
1044 // you may only attach to a child process (https://wiki.ubuntu.com/SecurityTeam/Roadmap/KernelHardening)
1046 // We can detect this and warn the user; however, it takes root to disable it.
1050 static void warn_user_ptrace_restrictions() {
1051 ifstream ptrace_scope("/proc/sys/kernel/yama/ptrace_scope");
1052 if (ptrace_scope.is_open()) {
1054 ptrace_scope >> val;
1056 cerr << "Warning: your Linux system provides limited ptrace functionality as a security" << endl
1057 << "measure. This measure prevents ProcControl and Dyninst from attaching to binaries." << endl
1058 << "To temporarily disable this measure (until a reboot), execute the following command:" << endl
1059 << "\techo 0 > /proc/sys/kernel/yama/ptrace_scope" << endl;
1060 struct stat statbuf;
1061 if (!stat("/etc/sysctl.d/10-ptrace.conf", &statbuf)) {
1062 cerr << "To permanently disable this measure, edit the file \"/etc/sysctl.d/10-ptrace.conf\"" << endl
1063 << "and follow the directions in that file." << endl;
1065 cerr << "For more information, see https://wiki.ubuntu.com/SecurityTeam/Roadmap/KernelHardening" << endl;
1066 is_restricted_ptrace = true;
1072 bool linux_process::plat_attach(bool, bool &)
1074 pthrd_printf("Attaching to pid %d\n", pid);
1076 bool attachWillTriggerStop = plat_attachWillTriggerStop();
1078 int result = do_ptrace((pt_req) PTRACE_ATTACH, pid, NULL, NULL);
1081 pthrd_printf("Unable to attach to process %d: %s\n", pid, strerror(errnum));
1084 warn_user_ptrace_restrictions();
1085 setLastError(err_prem, "Do not have correct premissions to attach to pid");
1088 setLastError(err_noproc, "The specified process was not found");
1091 setLastError(err_internal, "Unable to attach to the specified process");
1097 if ( !attachWillTriggerStop ) {
1098 // Force the SIGSTOP delivered by the attach to be handled
1099 pthrd_printf("Attach will not trigger stop, calling PTRACE_CONT to flush out stop\n");
1100 int result = do_ptrace((pt_req) PTRACE_CONT, pid, NULL, NULL);
1103 pthrd_printf("Unable to continue process %d to flush out attach: %s\n",
1104 pid, strerror(errnum));
1105 if (errnum == ESRCH)
1106 setLastError(err_exited, "Process exited during operation");
1114 bool linux_process::plat_attachWillTriggerStop() {
1121 // Retrieve the state of the process and its controlling tty
1122 snprintf(procName, 64, "/proc/%d/stat", pid);
1124 boost::shared_ptr<FILE> sfile(fopen(procName, "r"), fclose);
1126 perr_printf("Failed to determine whether attach would trigger stop -- assuming it will\n");
1130 if(fscanf(sfile.get(), "%d %255s %c %d %d %d",
1131 &tmpPid, cmd, &state,
1132 &tmpPid, &tmpPid, &ttyNumber) < 0) {
1133 perr_printf("Failed to determine whether attach would trigger stop -- assuming it will\n");
1137 // If the process is stopped and it has a controlling tty, an attach
1138 // will not trigger a stop
1139 if ( state == 'T' && ttyNumber != 0 ) {
1146 bool linux_process::plat_execed()
1148 bool result = sysv_process::plat_execed();
1152 char proc_exec_name[128];
1153 snprintf(proc_exec_name, 128, "/proc/%d/exe", getPid());
1154 executable = resolve_file_path(proc_exec_name);
1158 bool linux_process::plat_forked()
1163 bool linux_process::plat_readMem(int_thread *thr, void *local,
1164 Dyninst::Address remote, size_t size)
1166 return LinuxPtrace::getPtracer()->ptrace_read(remote, size, local, thr->getLWP());
1169 bool linux_process::plat_writeMem(int_thread *thr, const void *local,
1170 Dyninst::Address remote, size_t size, bp_write_t)
1172 return LinuxPtrace::getPtracer()->ptrace_write(remote, size, local, thr->getLWP());
1175 linux_x86_process::linux_x86_process(Dyninst::PID p, std::string e, std::vector<std::string> a,
1176 std::vector<std::string> envp, std::map<int,int> f) :
1177 int_process(p, e, a, envp, f),
1178 resp_process(p, e, a, envp, f),
1179 linux_process(p, e, a, envp, f),
1180 x86_process(p, e, a, envp, f)
1184 linux_x86_process::linux_x86_process(Dyninst::PID pid_, int_process *p) :
1185 int_process(pid_, p),
1186 resp_process(pid_, p),
1187 linux_process(pid_, p),
1188 x86_process(pid_, p)
1193 linux_x86_process::~linux_x86_process()
1197 Dyninst::Architecture linux_x86_process::getTargetArch()
1199 if (arch != Dyninst::Arch_none) {
1202 int addr_width = computeAddrWidth();
1203 arch = (addr_width == 4) ? Dyninst::Arch_x86 : Dyninst::Arch_x86_64;
1207 bool linux_x86_process::plat_supportHWBreakpoint()
1212 linux_ppc_process::linux_ppc_process(Dyninst::PID p, std::string e, std::vector<std::string> a,
1213 std::vector<std::string> envp, std::map<int,int> f) :
1214 int_process(p, e, a, envp, f),
1215 resp_process(p, e, a, envp, f),
1216 linux_process(p, e, a, envp, f),
1217 ppc_process(p, e, a, envp, f)
1221 linux_ppc_process::linux_ppc_process(Dyninst::PID pid_, int_process *p) :
1222 int_process(pid_, p),
1223 resp_process(pid_, p),
1224 linux_process(pid_, p),
1225 ppc_process(pid_, p)
1230 linux_ppc_process::~linux_ppc_process()
1234 Dyninst::Architecture linux_ppc_process::getTargetArch()
1236 if (arch != Dyninst::Arch_none) {
1239 int addr_width = computeAddrWidth();
1240 arch = (addr_width == 4) ? Dyninst::Arch_ppc32 : Dyninst::Arch_ppc64;
1245 linux_arm_process::linux_arm_process(Dyninst::PID p, std::string e, std::vector<std::string> a,
1246 std::vector<std::string> envp, std::map<int,int> f) :
1247 int_process(p, e, a, envp, f),
1248 resp_process(p, e, a, envp, f),
1249 linux_process(p, e, a, envp, f),
1250 arm_process(p, e, a, envp, f)
1254 linux_arm_process::linux_arm_process(Dyninst::PID pid_, int_process *p) :
1255 int_process(pid_, p),
1256 resp_process(pid_, p),
1257 linux_process(pid_, p),
1258 arm_process(pid_, p)
1263 linux_arm_process::~linux_arm_process()
1267 Dyninst::Architecture linux_arm_process::getTargetArch()
1269 if (arch != Dyninst::Arch_none) {
1272 int addr_width = computeAddrWidth();
1273 arch = (addr_width == 4) ? Dyninst::Arch_aarch32 : Dyninst::Arch_aarch64;
1274 assert(arch == Dyninst::Arch_aarch64); //should be aarch64 at this stage
1278 static std::vector<unsigned int> fake_async_msgs;
1279 void linux_thread::fake_async_main(void *)
1282 //Sleep for a small amount of time.
1283 struct timespec sleep_time;
1284 sleep_time.tv_sec = 0;
1285 sleep_time.tv_nsec = 1000000; //One milisecond
1286 nanosleep(&sleep_time, NULL);
1288 if (fake_async_msgs.empty())
1291 getResponses().lock();
1293 //Pick a random async response to fill.
1294 int size = fake_async_msgs.size();
1295 int elem = rand() % size;
1296 unsigned int id = fake_async_msgs[elem];
1297 fake_async_msgs[elem] = fake_async_msgs[size-1];
1298 fake_async_msgs.pop_back();
1300 pthrd_printf("Faking response for event %d\n", id);
1301 //Pull the response from the list
1302 response::ptr resp = getResponses().rmResponse(id);
1303 assert(resp != response::ptr());
1305 //Add data to the response.
1306 reg_response::ptr regr = resp->getRegResponse();
1307 allreg_response::ptr allr = resp->getAllRegResponse();
1308 result_response::ptr resr = resp->getResultResponse();
1309 mem_response::ptr memr = resp->getMemResponse();
1311 regr->postResponse(regr->val);
1313 allr->postResponse();
1315 resr->postResponse(resr->b);
1317 memr->postResponse();
1321 Event::ptr ev = resp->getEvent();
1322 if (ev == Event::ptr()) {
1323 //Someone is blocking for this response, mark it ready
1324 pthrd_printf("Marking response %s ready\n", resp->name().c_str());
1328 //An event triggered this async, create a new Async event
1329 // with the original event as subservient.
1330 int_eventAsync *internal = new int_eventAsync(resp);
1331 EventAsync::ptr async_ev(new EventAsync(internal));
1332 async_ev->setProcess(ev->getProcess());
1333 async_ev->setThread(ev->getThread());
1334 async_ev->setSyncType(Event::async);
1335 async_ev->addSubservientEvent(ev);
1337 pthrd_printf("Enqueueing Async event with subservient %s to mailbox\n", ev->name().c_str());
1338 mbox()->enqueue(async_ev, true);
1341 getResponses().signal();
1342 getResponses().unlock();
1346 bool linux_process::plat_needsAsyncIO() const
1348 #if !defined(debug_async_simulate)
1351 static DThread *fake_async_thread = NULL;
1352 if (!fake_async_thread) {
1353 fake_async_thread = new DThread();
1354 bool result = fake_async_thread->spawn(linux_thread::fake_async_main, NULL);
1356 if(!result) return false;
1361 bool linux_process::plat_readMemAsync(int_thread *thr, Dyninst::Address addr, mem_response::ptr result)
1363 bool b = plat_readMem(thr, result->getBuffer(), addr, result->getSize());
1365 result->markError(getLastError());
1367 result->setLastBase(addr);
1368 fake_async_msgs.push_back(result->getID());
1372 bool linux_process::plat_writeMemAsync(int_thread *thr, const void *local, Dyninst::Address addr, size_t size,
1373 result_response::ptr result, bp_write_t bp_write)
1375 bool b = plat_writeMem(thr, local, addr, size, bp_write);
1377 result->markError(getLastError());
1383 fake_async_msgs.push_back(result->getID());
1387 bool linux_process::needIndividualThreadAttach()
1392 bool linux_process::getThreadLWPs(std::vector<Dyninst::LWP> &lwps)
1394 return findProcLWPs(pid, lwps);
1397 bool linux_process::plat_supportLWPCreate()
1402 bool linux_process::plat_supportLWPPreDestroy()
1407 bool linux_process::plat_supportLWPPostDestroy()
1412 void linux_thread::postponeSyscallEvent(ArchEventLinux *event)
1414 assert(!postponed_syscall_event);
1415 postponed_syscall_event = event;
1418 bool linux_thread::hasPostponedSyscallEvent()
1420 return postponed_syscall_event != NULL;
1423 ArchEventLinux *linux_thread::getPostponedSyscallEvent()
1425 ArchEventLinux *ret = postponed_syscall_event;
1426 postponed_syscall_event = NULL;
1431 bool linux_thread::plat_cont()
1433 pthrd_printf("Continuing thread %d\n", lwp);
1435 switch (getHandlerState().getState()) {
1441 perr_printf("Continue attempted on thread in invalid state %s\n",
1442 int_thread::stateStr(handler_state.getState()));
1444 case neonatal_intermediate:
1454 // The following case poses a problem:
1455 // 1) This thread has received a signal, but the event hasn't been handled yet
1456 // 2) An event that precedes the signal event triggers a callback where
1457 // the user requests that the whole process stop. This in turn causes
1458 // the thread to be sent a SIGSTOP because the Handler hasn't seen the
1459 // signal event yet.
1460 // 3) Before handling the pending signal event, this thread is continued to
1461 // clear out the pending stop and consequently, it is delivered the signal
1462 // which can cause the whole process to crash
1465 // Don't continue the thread with the pending signal if there is a pending stop.
1466 // Wait until the user sees the signal event to deliver the signal to the process.
1469 int tmpSignal = continueSig_;
1470 if( hasPendingStop()) {
1474 void *data = (tmpSignal == 0) ? NULL : (void *) (long) tmpSignal;
1476 if (hasPostponedSyscallEvent())
1478 /* This should be turned on to solve the arm kernel bug.
1479 * When it recognize the syscall enter event, insert a bp as the fake
1480 * syscall exit stop.
1482 #if defined(arch_aarch64) && defined(SYSCALL_EXIT_BREAKPOINT)
1483 if( postponed_syscall_event->event_ext == PTRACE_EVENT_FORK ||
1484 postponed_syscall_event->event_ext == PTRACE_EVENT_CLONE ){
1486 Dyninst::MachRegisterVal addr;
1487 result = plat_getRegister(MachRegister::getPC(this->llproc()->getTargetArch()), addr);
1489 fprintf(stderr, "Failed to read PC address upon crash\n");
1491 pthrd_printf("Got SIGTRAP at %lx\n", addr);
1492 pthrd_printf("Installing breakpoint for postpone syscall at %lx\n", addr);
1494 this->BPptr_fakeSyscallExitBp = Breakpoint::ptr();
1495 //int_breakpoint *fakeSyscallExitBp = new int_breakpoint(Breakpoint::ptr());
1496 int_breakpoint *fakeSyscallExitBp = new int_breakpoint(this->BPptr_fakeSyscallExitBp);
1497 fakeSyscallExitBp->setThreadSpecific(this->thread());
1498 fakeSyscallExitBp->setOneTimeBreakpoint(true);
1499 //this->llproc()->addBreakpoint(addr, fakeSyscallExitBp);
1500 this->proc()->addBreakpoint(addr, this->BPptr_fakeSyscallExitBp);
1501 this->addr_fakeSyscallExitBp = addr;
1502 this->isSet_fakeSyscallExitBp = true;
1506 pthrd_printf("Calling PTRACE_SYSCALL on %d with signal %d\n", lwp, tmpSignal);
1507 result = do_ptrace((pt_req) PTRACE_SYSCALL, lwp, NULL, data);
1509 else if (singleStep())
1511 pthrd_printf("Calling PTRACE_SINGLESTEP on %d with signal %d\n", lwp, tmpSignal);
1512 result = do_ptrace((pt_req) PTRACE_SINGLESTEP, lwp, NULL, data);
1514 else if (syscallMode())
1516 pthrd_printf("Calling PTRACE_SYSCALL on %d with signal %d\n", lwp, tmpSignal);
1517 result = do_ptrace((pt_req) PTRACE_SYSCALL, lwp, NULL, data);
1521 pthrd_printf("Calling PTRACE_CONT on %d with signal %d\n", lwp, tmpSignal);
1522 result = do_ptrace((pt_req) PTRACE_CONT, lwp, NULL, data);
1526 if (error == ESRCH) {
1527 pthrd_printf("Continue attempted on exited thread %d\n", lwp);
1528 setLastError(err_exited, "Continue on exited thread");
1531 perr_printf("low-level continue failed: %s\n", strerror(error));
1532 setLastError(err_internal, "Low-level continue failed\n");
1535 if( tmpSignal == continueSig_ ) continueSig_ = 0;
1540 SymbolReaderFactory *getElfReader()
1542 #if defined(WITH_SYMLITE)
1543 static SymbolReaderFactory *symreader_factory = NULL;
1544 if (symreader_factory)
1545 return symreader_factory;
1547 symreader_factory = (SymbolReaderFactory *) new SymElfFactory();
1548 return symreader_factory;
1549 #elif defined(WITH_SYMTAB_API)
1550 return SymtabAPI::getSymtabReaderFactory();
1552 #error "No defined symbol reader"
1556 SymbolReaderFactory *linux_process::plat_defaultSymReader()
1558 return getElfReader();
1563 #define SYS_tkill 238
1566 static pid_t P_gettid()
1568 static int gettid_not_valid = 0;
1571 if (gettid_not_valid)
1574 result = syscall(SYS_gettid);
1575 if (result == -1 && errno == ENOSYS)
1577 gettid_not_valid = 1;
1580 return (int) result;
1583 static bool t_kill(int pid, int sig)
1585 static bool has_tkill = true;
1586 long int result = 0;
1587 pthrd_printf("Sending %d to %d\n", sig, pid);
1589 result = syscall(SYS_tkill, pid, sig);
1590 if (result == -1 && errno == ENOSYS)
1592 pthrd_printf("Using kill instead of tkill on this system\n");
1597 result = kill(pid, sig);
1600 return (result == 0);
1603 int_thread *int_thread::createThreadPlat(int_process *proc,
1604 Dyninst::THR_ID thr_id,
1605 Dyninst::LWP lwp_id,
1609 lwp_id = proc->getPid();
1611 linux_thread *lthrd = new DEFAULT_THREAD_TYPE(proc, thr_id, lwp_id);
1613 return static_cast<int_thread *>(lthrd);
1616 linux_thread::linux_thread(int_process *p, Dyninst::THR_ID t, Dyninst::LWP l) :
1617 int_thread(p, t, l),
1618 thread_db_thread(p, t, l),
1619 postponed_syscall_event(NULL),
1620 generator_started_exit_processing(false)
1624 linux_thread::~linux_thread()
1626 delete postponed_syscall_event;
1629 bool linux_thread::plat_stop()
1633 assert(pending_stop.local());
1634 result = t_kill(lwp, SIGSTOP);
1638 pthrd_printf("t_kill failed on %d, thread doesn't exist\n", lwp);
1639 setLastError(err_exited, "Operation on exited thread");
1642 pthrd_printf("t_kill failed on %d: %s\n", lwp, strerror(err));
1643 setLastError(err_internal, "Could not send signal to process while stopping");
1650 void linux_thread::setOptions()
1653 options |= PTRACE_O_TRACEEXIT;
1654 options |= PTRACE_O_TRACEEXEC;
1655 options |= PTRACE_O_TRACESYSGOOD;
1656 if (llproc()->getLWPTracking()->lwp_getTracking())
1657 options |= PTRACE_O_TRACECLONE;
1658 if (llproc()->getFollowFork()->fork_isTracking() != FollowFork::ImmediateDetach)
1659 options |= PTRACE_O_TRACEFORK;
1662 int result = do_ptrace((pt_req) PTRACE_SETOPTIONS, lwp, NULL,
1666 pthrd_printf("Failed to set options for %lu: %s\n", tid, strerror(errno));
1668 setLastError(err_exited, "Process exited during operation");
1673 bool linux_thread::unsetOptions()
1677 int result = do_ptrace((pt_req) PTRACE_SETOPTIONS, lwp, NULL,
1681 pthrd_printf("Failed to set options for %lu: %s\n", tid, strerror(errno));
1683 setLastError(err_exited, "Process exited during operation");
1689 bool linux_process::plat_individualRegAccess()
1694 bool linux_process::plat_detach(result_response::ptr, bool leave_stopped)
1696 int_threadPool *tp = threadPool();
1697 bool had_error = false;
1698 bool first_thread_signaled = false;
1700 for (int_threadPool::iterator i = tp->begin(); i != tp->end(); i++) {
1701 int_thread *thr = *i;
1702 if (leave_stopped && !first_thread_signaled) {
1703 pthrd_printf("Signaling %d/%d with SIGSTOP during detach to leave stopped\n", getPid(), thr->getLWP());
1704 t_kill(thr->getLWP(), SIGSTOP);
1705 first_thread_signaled = true;
1707 pthrd_printf("PTRACE_DETACH on %d\n", thr->getLWP());
1708 long result = do_ptrace((pt_req) PTRACE_DETACH, thr->getLWP(), NULL, (void *) 0);
1712 perr_printf("Failed to PTRACE_DETACH on %d/%d (%s)\n", getPid(), thr->getLWP(), strerror(errno));
1714 setLastError(err_exited, "Process exited during operation");
1716 setLastError(err_internal, "PTRACE_DETACH operation failed\n");
1719 // Before we return from detach, make sure that we've gotten out of waitpid()
1720 // so that we don't steal events on that process.
1721 GeneratorLinux* g = dynamic_cast<GeneratorLinux*>(Generator::getDefaultGenerator());
1723 g->evictFromWaitpid();
1728 bool linux_process::plat_terminate(bool &needs_sync)
1730 //ProcPool lock should be held.
1731 //I had been using PTRACE_KILL here, but that was proving to be inconsistent.
1734 pthrd_printf("Terminating process %d\n", getPid());
1735 int result = kill(getPid(), SIGKILL);
1737 if (errno == ESRCH) {
1738 perr_printf("Process %d no longer exists\n", getPid());
1739 setLastError(err_noproc, "Process no longer exists");
1742 perr_printf("Failed to kill(%d, SIGKILL) process\n", getPid());
1743 setLastError(err_internal, "Unexpected failure of kill\n");
1752 bool linux_process::preTerminate() {
1754 pthrd_printf("Stopping process %d for pre-terminate handling\n", getPid());
1755 threadPool()->initialThread()->getInternalState().desyncStateProc(int_thread::stopped);
1756 bool threw_event = false;
1757 while (!threadPool()->allStopped(int_thread::InternalStateID)) {
1762 bool exited = false;
1763 auto pid = getPid();
1764 int_process::waitAndHandleForProc(true, this, exited);
1766 // Note, can't even call getPid() anymore, since 'this' is ironically deleted.
1767 perr_printf("Process %d exited during terminate handling. Is this irony?\n", pid);
1771 pthrd_printf("Putting process %d back into previous state\n", getPid());
1772 threadPool()->initialThread()->getInternalState().restoreStateProc();
1774 #if defined(bug_force_terminate_failure)
1775 // On some Linux versions (currently only identified on our power platform),
1776 // a force terminate can fail to actually kill a process due to some OS level
1777 // race condition. The result is that some threads in a process are stopped
1778 // instead of exited and for some reason, continues will not continue the
1779 // process. This can be detected because some OS level structures (such as pipes)
1780 // still exist for the terminated process
1782 // It appears that this bug largely results from the pre-LWP destroy and pre-Exit
1783 // events being delivered to the debugger, so we stop the process and disable these
1784 // events for all threads in the process
1786 int_threadPool::iterator i;
1787 for(i = threadPool()->begin(); i != threadPool()->end(); i++)
1789 linux_thread *thr = dynamic_cast<linux_thread *>(*i);
1790 pthrd_printf("Disabling syscall tracing events for thread %d/%d\n",
1791 getPid(), thr->getLWP());
1792 if( !thr->unsetOptions() ) {
1793 perr_printf("Failed to unset options for thread %d/%d in pre-terminate handling\n",
1794 getPid(), thr->getLWP());
1800 // We don't want to be mixing termination and breakpoint stepping.
1801 removeAllBreakpoints();
1803 // And put things back where we found them.
1806 pthrd_printf("Waiting for process %d to resynchronize before terminating\n", getPid());
1807 int_process::waitAndHandleEvents(false);
1812 OSType linux_process::getOS() const
1814 return Dyninst::Linux;
1817 Dyninst::Address linux_process::plat_mallocExecMemory(Dyninst::Address min, unsigned size) {
1818 Dyninst::Address result = 0x0;
1819 bool found_result = false;
1821 map_entries *maps = getVMMaps(getPid(), maps_size);
1822 assert(maps); //TODO, Perhaps go to libraries for address map if no /proc/
1823 for (unsigned i=0; i<maps_size; i++) {
1824 if (!(maps[i].prems & PREMS_EXEC))
1826 if (min + size > maps[i].end)
1828 if (maps[i].end - maps[i].start < size)
1831 if (maps[i].start > min)
1832 result = maps[i].start;
1835 found_result = true;
1838 assert(found_result);
1843 bool linux_process::fork_setTracking(FollowFork::follow_t f)
1845 int_threadPool::iterator i;
1846 for (i = threadPool()->begin(); i != threadPool()->end(); i++) {
1847 int_thread *thrd = *i;
1848 if (thrd->getUserState().getState() != int_thread::stopped) {
1849 perr_printf("Could not set fork tracking because thread %d/%d was not stopped\n",
1850 getPid(), thrd->getLWP());
1851 setLastError(err_notstopped, "All threads must be stopped to change fork tracking\n");
1855 if (f == FollowFork::None) {
1856 perr_printf("Could not set fork tracking on %d to None\n", getPid());
1857 setLastError(err_badparam, "Cannot set fork tracking to None");
1861 if (f == fork_tracking) {
1862 pthrd_printf("Leaving fork tracking for %d in state %d\n",
1867 for (i = threadPool()->begin(); i != threadPool()->end(); i++) {
1868 int_thread *thrd = *i;
1869 linux_thread *lthrd = dynamic_cast<linux_thread *>(thrd);
1870 pthrd_printf("Changing fork tracking for thread %d/%d to %d\n",
1871 getPid(), lthrd->getLWP(), (int) f);
1872 lthrd->setOptions();
1877 FollowFork::follow_t linux_process::fork_isTracking() {
1878 return fork_tracking;
1881 bool linux_process::plat_lwpChangeTracking(bool) {
1882 int_threadPool *pool = threadPool();
1883 if (!pool->allStopped(int_thread::UserStateID)) {
1884 perr_printf("Attempted to change lwpTracking, but not all threads stopped in %d", getPid());
1885 setLastError(err_notstopped, "Process not stopped before changing LWP tracking state");
1889 for (int_threadPool::iterator i = pool->begin(); i != pool->end(); i++) {
1890 int_thread *thrd = *i;
1891 linux_thread *lthrd = dynamic_cast<linux_thread *>(thrd);
1893 lthrd->setOptions();
1898 bool linux_process::allowSignal(int signal_no) {
1899 dyn_sigset_t mask = getSigMask();
1900 return sigismember(&mask, signal_no);
1903 bool linux_process::readStatM(unsigned long &stk, unsigned long &heap, unsigned long &shrd)
1906 snprintf(path, 64, "/proc/%d/statm", getPid());
1909 unsigned long size, resident, shared, text, lib, data, dt;
1910 boost::shared_ptr<FILE> f(fopen(path, "r"), fclose);
1912 perr_printf("Could not open %s: %s\n", path, strerror(errno));
1913 setLastError(err_internal, "Could not access /proc");
1916 if(fscanf(f.get(), "%lu %lu %lu %lu %lu %lu %lu", &size, &resident, &shared,
1917 &text, &lib, &data, &dt) < 0) {
1918 perr_printf("Could not read from %s: %s\n", path, strerror(errno));
1919 setLastError(err_internal, "Could not read from /proc");
1922 unsigned long page_size = getpagesize();
1925 shrd = (shared + text) * page_size;
1926 heap = data * page_size;
1930 bool linux_process::plat_getStackUsage(MemUsageResp_t *resp)
1932 unsigned long stk, heap, shrd;
1933 bool result = readStatM(stk, heap, shrd);
1941 bool linux_process::plat_getHeapUsage(MemUsageResp_t *resp)
1943 unsigned long stk, heap, shrd;
1944 bool result = readStatM(stk, heap, shrd);
1947 *resp->get() = heap;
1952 bool linux_process::plat_getSharedUsage(MemUsageResp_t *resp)
1954 unsigned long stk, heap, shrd;
1955 bool result = readStatM(stk, heap, shrd);
1958 *resp->get() = shrd;
1963 bool linux_process::plat_residentNeedsMemVals()
1968 bool linux_process::plat_getResidentUsage(unsigned long, unsigned long, unsigned long,
1974 #if !defined(OFFSETOF)
1975 #define OFFSETOF(STR, FLD) (unsigned long) (&(((STR *) 0x0)->FLD))
1978 dynreg_to_user_t dynreg_to_user;
1979 static void init_dynreg_to_user()
1981 static volatile bool initialized = false;
1982 static Mutex<> init_lock;
1992 //Match the order of the 'user' structure to map registers correctly.
1994 if (sizeof(void*) == 8) {
1996 * This is annoying, struct user is different for 64-bit processes debugging
2003 dynreg_to_user[x86::ebp] = make_pair(cur+=8, 4);
2004 dynreg_to_user[x86::ebx] = make_pair(cur+=8, 4);
2009 dynreg_to_user[x86::eax] = make_pair(cur+=8, 4);
2010 dynreg_to_user[x86::ecx] = make_pair(cur+=8, 4);
2011 dynreg_to_user[x86::edx] = make_pair(cur+=8, 4);
2012 dynreg_to_user[x86::esi] = make_pair(cur+=8, 4);
2013 dynreg_to_user[x86::edi] = make_pair(cur+=8, 4);
2014 dynreg_to_user[x86::oeax] = make_pair(cur+=8, 4);
2015 dynreg_to_user[x86::eip] = make_pair(cur+=8, 4);
2016 dynreg_to_user[x86::cs] = make_pair(cur+=8, 4);
2017 dynreg_to_user[x86::flags] = make_pair(cur+=8, 4);
2018 dynreg_to_user[x86::esp] = make_pair(cur+=8, 4);
2019 dynreg_to_user[x86::ss] = make_pair(cur+=8, 4);
2020 dynreg_to_user[x86::fsbase]= make_pair(cur+=8, 4);
2021 dynreg_to_user[x86::gsbase]= make_pair(cur+=8, 4);
2022 dynreg_to_user[x86::ds] = make_pair(cur+=8, 4);
2023 dynreg_to_user[x86::es] = make_pair(cur+=8, 4);
2024 dynreg_to_user[x86::fs] = make_pair(cur+=8, 4);
2025 dynreg_to_user[x86::gs] = make_pair(cur+=8, 4);
2026 #if defined(arch_x86) || defined(arch_x86_64)
2027 cur = OFFSETOF(user, u_debugreg);
2029 dynreg_to_user[x86::dr0] = make_pair(cur, 4);
2030 dynreg_to_user[x86::dr1] = make_pair(cur+=8, 4);
2031 dynreg_to_user[x86::dr2] = make_pair(cur+=8, 4);
2032 dynreg_to_user[x86::dr3] = make_pair(cur+=8, 4);
2033 dynreg_to_user[x86::dr4] = make_pair(cur+=8, 4);
2034 dynreg_to_user[x86::dr5] = make_pair(cur+=8, 4);
2035 dynreg_to_user[x86::dr6] = make_pair(cur+=8, 4);
2036 dynreg_to_user[x86::dr7] = make_pair(cur+=8, 4);
2039 dynreg_to_user[x86::ebx] = make_pair(cur, 4);
2040 dynreg_to_user[x86::ecx] = make_pair(cur+=4, 4);
2041 dynreg_to_user[x86::edx] = make_pair(cur+=4, 4);
2042 dynreg_to_user[x86::esi] = make_pair(cur+=4, 4);
2043 dynreg_to_user[x86::edi] = make_pair(cur+=4, 4);
2044 dynreg_to_user[x86::ebp] = make_pair(cur+=4, 4);
2045 dynreg_to_user[x86::eax] = make_pair(cur+=4, 4);
2046 dynreg_to_user[x86::ds] = make_pair(cur+=4, 4);
2047 dynreg_to_user[x86::es] = make_pair(cur+=4, 4);
2048 dynreg_to_user[x86::fs] = make_pair(cur+=4, 4);
2049 dynreg_to_user[x86::gs] = make_pair(cur+=4, 4);
2050 dynreg_to_user[x86::oeax] = make_pair(cur+=4, 4);
2051 dynreg_to_user[x86::eip] = make_pair(cur+=4, 4);
2052 dynreg_to_user[x86::cs] = make_pair(cur+=4, 4);
2053 dynreg_to_user[x86::flags] = make_pair(cur+=4, 4);
2054 dynreg_to_user[x86::esp] = make_pair(cur+=4, 4);
2055 dynreg_to_user[x86::ss] = make_pair(cur+=4, 4);
2056 #if defined(arch_x86) || defined(arch_x86_64)
2057 cur = OFFSETOF(user, u_debugreg);
2059 dynreg_to_user[x86::dr0] = make_pair(cur, 4);
2060 dynreg_to_user[x86::dr1] = make_pair(cur+=4, 4);
2061 dynreg_to_user[x86::dr2] = make_pair(cur+=4, 4);
2062 dynreg_to_user[x86::dr3] = make_pair(cur+=4, 4);
2063 dynreg_to_user[x86::dr4] = make_pair(cur+=4, 4);
2064 dynreg_to_user[x86::dr5] = make_pair(cur+=4, 4);
2065 dynreg_to_user[x86::dr6] = make_pair(cur+=4, 4);
2066 dynreg_to_user[x86::dr7] = make_pair(cur+=4, 4);
2069 dynreg_to_user[x86_64::r15] = make_pair(cur, 8);
2070 dynreg_to_user[x86_64::r14] = make_pair(cur+=8, 8);
2071 dynreg_to_user[x86_64::r13] = make_pair(cur+=8, 8);
2072 dynreg_to_user[x86_64::r12] = make_pair(cur+=8, 8);
2073 dynreg_to_user[x86_64::rbp] = make_pair(cur+=8, 8);
2074 dynreg_to_user[x86_64::rbx] = make_pair(cur+=8, 8);
2075 dynreg_to_user[x86_64::r11] = make_pair(cur+=8, 8);
2076 dynreg_to_user[x86_64::r10] = make_pair(cur+=8, 8);
2077 dynreg_to_user[x86_64::r9] = make_pair(cur+=8, 8);
2078 dynreg_to_user[x86_64::r8] = make_pair(cur+=8, 8);
2079 dynreg_to_user[x86_64::rax] = make_pair(cur+=8, 8);
2080 dynreg_to_user[x86_64::rcx] = make_pair(cur+=8, 8);
2081 dynreg_to_user[x86_64::rdx] = make_pair(cur+=8, 8);
2082 dynreg_to_user[x86_64::rsi] = make_pair(cur+=8, 8);
2083 dynreg_to_user[x86_64::rdi] = make_pair(cur+=8, 8);
2084 dynreg_to_user[x86_64::orax] = make_pair(cur+=8, 8);
2085 dynreg_to_user[x86_64::rip] = make_pair(cur+=8, 8);
2086 dynreg_to_user[x86_64::cs] = make_pair(cur+=8, 8);
2087 dynreg_to_user[x86_64::flags] = make_pair(cur+=8, 8);
2088 dynreg_to_user[x86_64::rsp] = make_pair(cur+=8, 8);
2089 dynreg_to_user[x86_64::ss] = make_pair(cur+=8, 8);
2090 dynreg_to_user[x86_64::fsbase] = make_pair(cur+=8, 8);
2091 dynreg_to_user[x86_64::gsbase] = make_pair(cur+=8, 8);
2092 dynreg_to_user[x86_64::ds] = make_pair(cur+=8, 8);
2093 dynreg_to_user[x86_64::es] = make_pair(cur+=8, 8);
2094 dynreg_to_user[x86_64::fs] = make_pair(cur+=8, 8);
2095 dynreg_to_user[x86_64::gs] = make_pair(cur+=8, 8);
2096 #if defined(arch_x86) || defined(arch_x86_64)
2097 cur = OFFSETOF(user, u_debugreg);
2099 dynreg_to_user[x86_64::dr0] = make_pair(cur, 8);
2100 dynreg_to_user[x86_64::dr1] = make_pair(cur+=8, 8);
2101 dynreg_to_user[x86_64::dr2] = make_pair(cur+=8, 8);
2102 dynreg_to_user[x86_64::dr3] = make_pair(cur+=8, 8);
2103 dynreg_to_user[x86_64::dr4] = make_pair(cur+=8, 8);
2104 dynreg_to_user[x86_64::dr5] = make_pair(cur+=8, 8);
2105 dynreg_to_user[x86_64::dr6] = make_pair(cur+=8, 8);
2106 dynreg_to_user[x86_64::dr7] = make_pair(cur+=8, 8);
2109 if(sizeof(void *) == 8 ) {
2110 dynreg_to_user[ppc32::r0] = make_pair(cur, 4);
2111 dynreg_to_user[ppc32::r1] = make_pair(cur+=8, 4);
2112 dynreg_to_user[ppc32::r2] = make_pair(cur+=8, 4);
2113 dynreg_to_user[ppc32::r3] = make_pair(cur+=8, 4);
2114 dynreg_to_user[ppc32::r4] = make_pair(cur+=8, 4);
2115 dynreg_to_user[ppc32::r5] = make_pair(cur+=8, 4);
2116 dynreg_to_user[ppc32::r6] = make_pair(cur+=8, 4);
2117 dynreg_to_user[ppc32::r7] = make_pair(cur+=8, 4);
2118 dynreg_to_user[ppc32::r8] = make_pair(cur+=8, 4);
2119 dynreg_to_user[ppc32::r9] = make_pair(cur+=8, 4);
2120 dynreg_to_user[ppc32::r10] = make_pair(cur+=8, 4);
2121 dynreg_to_user[ppc32::r11] = make_pair(cur+=8, 4);
2122 dynreg_to_user[ppc32::r12] = make_pair(cur+=8, 4);
2123 dynreg_to_user[ppc32::r13] = make_pair(cur+=8, 4);
2124 dynreg_to_user[ppc32::r14] = make_pair(cur+=8, 4);
2125 dynreg_to_user[ppc32::r15] = make_pair(cur+=8, 4);
2126 dynreg_to_user[ppc32::r16] = make_pair(cur+=8, 4);
2127 dynreg_to_user[ppc32::r17] = make_pair(cur+=8, 4);
2128 dynreg_to_user[ppc32::r18] = make_pair(cur+=8, 4);
2129 dynreg_to_user[ppc32::r19] = make_pair(cur+=8, 4);
2130 dynreg_to_user[ppc32::r20] = make_pair(cur+=8, 4);
2131 dynreg_to_user[ppc32::r21] = make_pair(cur+=8, 4);
2132 dynreg_to_user[ppc32::r22] = make_pair(cur+=8, 4);
2133 dynreg_to_user[ppc32::r23] = make_pair(cur+=8, 4);
2134 dynreg_to_user[ppc32::r24] = make_pair(cur+=8, 4);
2135 dynreg_to_user[ppc32::r25] = make_pair(cur+=8, 4);
2136 dynreg_to_user[ppc32::r26] = make_pair(cur+=8, 4);
2137 dynreg_to_user[ppc32::r27] = make_pair(cur+=8, 4);
2138 dynreg_to_user[ppc32::r28] = make_pair(cur+=8, 4);
2139 dynreg_to_user[ppc32::r29] = make_pair(cur+=8, 4);
2140 dynreg_to_user[ppc32::r30] = make_pair(cur+=8, 4);
2141 dynreg_to_user[ppc32::r31] = make_pair(cur+=8, 4);
2142 dynreg_to_user[ppc32::pc] = make_pair(cur+=8, 4);
2143 dynreg_to_user[ppc32::msr] = make_pair(cur+=8, 4);
2144 dynreg_to_user[ppc32::or3] = make_pair(cur+=8, 4);
2145 dynreg_to_user[ppc32::ctr] = make_pair(cur+=8, 4);
2146 dynreg_to_user[ppc32::lr] = make_pair(cur+=8, 4);
2147 dynreg_to_user[ppc32::xer] = make_pair(cur+=8, 4);
2148 dynreg_to_user[ppc32::cr] = make_pair(cur+=8, 4);
2149 dynreg_to_user[ppc32::mq] = make_pair(cur+=8, 4);
2150 dynreg_to_user[ppc32::trap] = make_pair(cur+=8, 4);
2151 dynreg_to_user[ppc32::dar] = make_pair(cur+=8, 4);
2152 dynreg_to_user[ppc32::dsisr] = make_pair(cur+=8, 4);
2154 dynreg_to_user[ppc32::r0] = make_pair(cur, 4);
2155 dynreg_to_user[ppc32::r1] = make_pair(cur+=4, 4);
2156 dynreg_to_user[ppc32::r2] = make_pair(cur+=4, 4);
2157 dynreg_to_user[ppc32::r3] = make_pair(cur+=4, 4);
2158 dynreg_to_user[ppc32::r4] = make_pair(cur+=4, 4);
2159 dynreg_to_user[ppc32::r5] = make_pair(cur+=4, 4);
2160 dynreg_to_user[ppc32::r6] = make_pair(cur+=4, 4);
2161 dynreg_to_user[ppc32::r7] = make_pair(cur+=4, 4);
2162 dynreg_to_user[ppc32::r8] = make_pair(cur+=4, 4);
2163 dynreg_to_user[ppc32::r9] = make_pair(cur+=4, 4);
2164 dynreg_to_user[ppc32::r10] = make_pair(cur+=4, 4);
2165 dynreg_to_user[ppc32::r11] = make_pair(cur+=4, 4);
2166 dynreg_to_user[ppc32::r12] = make_pair(cur+=4, 4);
2167 dynreg_to_user[ppc32::r13] = make_pair(cur+=4, 4);
2168 dynreg_to_user[ppc32::r14] = make_pair(cur+=4, 4);
2169 dynreg_to_user[ppc32::r15] = make_pair(cur+=4, 4);
2170 dynreg_to_user[ppc32::r16] = make_pair(cur+=4, 4);
2171 dynreg_to_user[ppc32::r17] = make_pair(cur+=4, 4);
2172 dynreg_to_user[ppc32::r18] = make_pair(cur+=4, 4);
2173 dynreg_to_user[ppc32::r19] = make_pair(cur+=4, 4);
2174 dynreg_to_user[ppc32::r20] = make_pair(cur+=4, 4);
2175 dynreg_to_user[ppc32::r21] = make_pair(cur+=4, 4);
2176 dynreg_to_user[ppc32::r22] = make_pair(cur+=4, 4);
2177 dynreg_to_user[ppc32::r23] = make_pair(cur+=4, 4);
2178 dynreg_to_user[ppc32::r24] = make_pair(cur+=4, 4);
2179 dynreg_to_user[ppc32::r25] = make_pair(cur+=4, 4);
2180 dynreg_to_user[ppc32::r26] = make_pair(cur+=4, 4);
2181 dynreg_to_user[ppc32::r27] = make_pair(cur+=4, 4);
2182 dynreg_to_user[ppc32::r28] = make_pair(cur+=4, 4);
2183 dynreg_to_user[ppc32::r29] = make_pair(cur+=4, 4);
2184 dynreg_to_user[ppc32::r30] = make_pair(cur+=4, 4);
2185 dynreg_to_user[ppc32::r31] = make_pair(cur+=4, 4);
2186 dynreg_to_user[ppc32::pc] = make_pair(cur+=4, 4);
2187 dynreg_to_user[ppc32::msr] = make_pair(cur+=4, 4);
2188 dynreg_to_user[ppc32::or3] = make_pair(cur+=4, 4);
2189 dynreg_to_user[ppc32::ctr] = make_pair(cur+=4, 4);
2190 dynreg_to_user[ppc32::lr] = make_pair(cur+=4, 4);
2191 dynreg_to_user[ppc32::xer] = make_pair(cur+=4, 4);
2192 dynreg_to_user[ppc32::cr] = make_pair(cur+=4, 4);
2193 dynreg_to_user[ppc32::mq] = make_pair(cur+=4, 4);
2194 dynreg_to_user[ppc32::trap] = make_pair(cur+=4, 4);
2195 dynreg_to_user[ppc32::dar] = make_pair(cur+=4, 4);
2196 dynreg_to_user[ppc32::dsisr] = make_pair(cur+=4, 4);
2199 dynreg_to_user[ppc64::r0] = make_pair(cur, 8);
2200 dynreg_to_user[ppc64::r1] = make_pair(cur+=8, 8);
2201 dynreg_to_user[ppc64::r2] = make_pair(cur+=8, 8);
2202 dynreg_to_user[ppc64::r3] = make_pair(cur+=8, 8);
2203 dynreg_to_user[ppc64::r4] = make_pair(cur+=8, 8);
2204 dynreg_to_user[ppc64::r5] = make_pair(cur+=8, 8);
2205 dynreg_to_user[ppc64::r6] = make_pair(cur+=8, 8);
2206 dynreg_to_user[ppc64::r7] = make_pair(cur+=8, 8);
2207 dynreg_to_user[ppc64::r8] = make_pair(cur+=8, 8);
2208 dynreg_to_user[ppc64::r9] = make_pair(cur+=8, 8);
2209 dynreg_to_user[ppc64::r10] = make_pair(cur+=8, 8);
2210 dynreg_to_user[ppc64::r11] = make_pair(cur+=8, 8);
2211 dynreg_to_user[ppc64::r12] = make_pair(cur+=8, 8);
2212 dynreg_to_user[ppc64::r13] = make_pair(cur+=8, 8);
2213 dynreg_to_user[ppc64::r14] = make_pair(cur+=8, 8);
2214 dynreg_to_user[ppc64::r15] = make_pair(cur+=8, 8);
2215 dynreg_to_user[ppc64::r16] = make_pair(cur+=8, 8);
2216 dynreg_to_user[ppc64::r17] = make_pair(cur+=8, 8);
2217 dynreg_to_user[ppc64::r18] = make_pair(cur+=8, 8);
2218 dynreg_to_user[ppc64::r19] = make_pair(cur+=8, 8);
2219 dynreg_to_user[ppc64::r20] = make_pair(cur+=8, 8);
2220 dynreg_to_user[ppc64::r21] = make_pair(cur+=8, 8);
2221 dynreg_to_user[ppc64::r22] = make_pair(cur+=8, 8);
2222 dynreg_to_user[ppc64::r23] = make_pair(cur+=8, 8);
2223 dynreg_to_user[ppc64::r24] = make_pair(cur+=8, 8);
2224 dynreg_to_user[ppc64::r25] = make_pair(cur+=8, 8);
2225 dynreg_to_user[ppc64::r26] = make_pair(cur+=8, 8);
2226 dynreg_to_user[ppc64::r27] = make_pair(cur+=8, 8);
2227 dynreg_to_user[ppc64::r28] = make_pair(cur+=8, 8);
2228 dynreg_to_user[ppc64::r29] = make_pair(cur+=8, 8);
2229 dynreg_to_user[ppc64::r30] = make_pair(cur+=8, 8);
2230 dynreg_to_user[ppc64::r31] = make_pair(cur+=8, 8);
2231 dynreg_to_user[ppc64::pc] = make_pair(cur+=8, 8);
2232 dynreg_to_user[ppc64::msr] = make_pair(cur+=8, 8);
2233 dynreg_to_user[ppc64::or3] = make_pair(cur+=8, 8);
2234 dynreg_to_user[ppc64::ctr] = make_pair(cur+=8, 8);
2235 dynreg_to_user[ppc64::lr] = make_pair(cur+=8, 8);
2236 dynreg_to_user[ppc64::xer] = make_pair(cur+=8, 8);
2237 dynreg_to_user[ppc64::cr] = make_pair(cur+=8, 8);
2238 dynreg_to_user[ppc64::mq] = make_pair(cur+=8, 8);
2239 dynreg_to_user[ppc64::trap] = make_pair(cur+=8, 8);
2240 dynreg_to_user[ppc64::dar] = make_pair(cur+=8, 8);
2241 dynreg_to_user[ppc64::dsisr] = make_pair(cur+=8, 8);
2244 //according to /sys/user.h
2247 dynreg_to_user[aarch64::x0] = make_pair(cur, 8);
2248 dynreg_to_user[aarch64::x1] = make_pair(cur+=step, 8);
2249 dynreg_to_user[aarch64::x2] = make_pair(cur+=step, 8);
2250 dynreg_to_user[aarch64::x3] = make_pair(cur+=step, 8);
2251 dynreg_to_user[aarch64::x4] = make_pair(cur+=step, 8);
2252 dynreg_to_user[aarch64::x5] = make_pair(cur+=step, 8);
2253 dynreg_to_user[aarch64::x6] = make_pair(cur+=step, 8);
2254 dynreg_to_user[aarch64::x7] = make_pair(cur+=step, 8);
2255 dynreg_to_user[aarch64::x8] = make_pair(cur+=step, 8);
2256 dynreg_to_user[aarch64::x9] = make_pair(cur+=step, 8);
2257 dynreg_to_user[aarch64::x10] = make_pair(cur+=step, 8);
2258 dynreg_to_user[aarch64::x11] = make_pair(cur+=step, 8);
2259 dynreg_to_user[aarch64::x12] = make_pair(cur+=step, 8);
2260 dynreg_to_user[aarch64::x13] = make_pair(cur+=step, 8);
2261 dynreg_to_user[aarch64::x14] = make_pair(cur+=step, 8);
2262 dynreg_to_user[aarch64::x15] = make_pair(cur+=step, 8);
2263 dynreg_to_user[aarch64::x16] = make_pair(cur+=step, 8);
2264 dynreg_to_user[aarch64::x17] = make_pair(cur+=step, 8);
2265 dynreg_to_user[aarch64::x18] = make_pair(cur+=step, 8);
2266 dynreg_to_user[aarch64::x19] = make_pair(cur+=step, 8);
2267 dynreg_to_user[aarch64::x20] = make_pair(cur+=step, 8);
2268 dynreg_to_user[aarch64::x21] = make_pair(cur+=step, 8);
2269 dynreg_to_user[aarch64::x22] = make_pair(cur+=step, 8);
2270 dynreg_to_user[aarch64::x23] = make_pair(cur+=step, 8);
2271 dynreg_to_user[aarch64::x24] = make_pair(cur+=step, 8);
2272 dynreg_to_user[aarch64::x25] = make_pair(cur+=step, 8);
2273 dynreg_to_user[aarch64::x26] = make_pair(cur+=step, 8);
2274 dynreg_to_user[aarch64::x27] = make_pair(cur+=step, 8);
2275 dynreg_to_user[aarch64::x28] = make_pair(cur+=step, 8);
2276 dynreg_to_user[aarch64::x29] = make_pair(cur+=step, 8);
2277 dynreg_to_user[aarch64::x30] = make_pair(cur+=step, 8);
2278 dynreg_to_user[aarch64::sp] = make_pair(cur+=step, 8);
2279 dynreg_to_user[aarch64::pc] = make_pair(cur+=step, 8);
2280 dynreg_to_user[aarch64::pstate] = make_pair(cur+=step, 8);
2287 #if defined(PT_GETREGS)
2288 #define MY_PTRACE_GETREGS PTRACE_GETREGS
2289 #elif defined(arch_power)
2290 //Kernel value for PPC_PTRACE_SETREGS 0x99
2291 #define MY_PTRACE_GETREGS 12
2292 #elif defined(arch_aarch64)
2296 #if defined(arch_aarch64)
2297 //31 GPR + SP + PC + PSTATE
2298 #define MAX_USER_REGS 34
2299 #define MAX_USER_SIZE (34*8)
2301 //912 is currently the x86_64 size, 128 bytes for just-because padding
2302 #define MAX_USER_SIZE (912+128)
2304 bool linux_thread::plat_getAllRegisters(int_registerPool ®pool)
2307 #if defined(MY_PTRACE_GETREGS)
2308 static bool have_getregs = true;
2310 #define MY_PTRACE_GETREGS 0
2311 static bool have_getregs = false;
2313 static bool tested_getregs = false;
2315 #if defined(bug_registers_after_exit)
2316 /* On some kernels, attempting to read registers from a thread in a pre-Exit
2317 * state causes an oops
2320 perr_printf("Cannot reliably retrieve registers from an exited thread\n");
2321 setLastError(err_exited, "Cannot retrieve registers from an exited thread");
2326 volatile unsigned int sentinel1 = 0xfeedface;
2327 unsigned char user_area[MAX_USER_SIZE];
2328 volatile unsigned int sentinel2 = 0xfeedface;
2329 memset(user_area, 0, MAX_USER_SIZE);
2331 Dyninst::Architecture curplat = llproc()->getTargetArch();
2332 init_dynreg_to_user();
2333 dynreg_to_user_t::iterator i;
2337 long result = do_ptrace((pt_req) MY_PTRACE_GETREGS, lwp, user_area, user_area);
2340 if (error == EIO && !tested_getregs) {
2341 pthrd_printf("PTRACE_GETREGS not working. Trying PTRACE_PEEKUSER\n");
2342 have_getregs = false;
2345 perr_printf("Error reading registers from %d\n", lwp);
2346 setLastError(err_internal, "Could not read user area from thread");
2350 tested_getregs = true;
2354 #if defined(arch_aarch64)
2357 iovec.iov_base = ®s;
2358 iovec.iov_len = sizeof(regs);
2359 long ret = do_ptrace((pt_req)PTRACE_GETREGSET, lwp, (void *)NT_PRSTATUS, &iovec);
2361 perr_printf("-AARCH64: Unable to fetch registers!\n");
2364 memcpy(user_area, regs, iovec.iov_len);
2366 for (i = dynreg_to_user.begin(); i != dynreg_to_user.end(); i++) {
2367 const MachRegister reg = i->first;
2368 if (reg.getArchitecture() != curplat)
2370 long result = do_ptrace((pt_req) PTRACE_PEEKUSER, lwp, (void *) (unsigned long) i->second.first, NULL);
2371 //errno == -1 is not sufficient here for aarch4
2372 //if (errno == -1) {
2373 if (errno == -1 || result == -1) {
2375 perr_printf("Error reading registers from %d at %x\n", lwp, i->second.first);
2377 setLastError(err_exited, "Process exited during operation");
2379 setLastError(err_internal, "Could not read user area from thread");
2382 if (Dyninst::getArchAddressWidth(curplat) == 4) {
2383 uint32_t val = (uint32_t) result;
2384 *((uint32_t *) (user_area + i->second.first)) = val;
2386 else if (Dyninst::getArchAddressWidth(curplat) == 8) {
2387 uint64_t val = (uint64_t) result;
2388 *((uint64_t *) (user_area + i->second.first)) = val;
2397 //If a sentinel assert fails, then someone forgot to increase MAX_USER_SIZE
2398 // for a new platform.
2399 assert(sentinel1 == 0xfeedface);
2400 assert(sentinel2 == 0xfeedface);
2401 if(sentinel1 != 0xfeedface || sentinel2 != 0xfeedface) return false;
2404 regpool.regs.clear();
2405 for (i = dynreg_to_user.begin(); i != dynreg_to_user.end(); i++)
2407 const MachRegister reg = i->first;
2408 MachRegisterVal val = 0;
2409 if (reg.getArchitecture() != curplat)
2411 const unsigned int offset = i->second.first;
2412 const unsigned int size = i->second.second;
2414 if( sizeof(void *) == 8 ) {
2415 // Avoid endian issues
2416 uint64_t tmpVal = *((uint64_t *) (user_area+offset));
2417 val = (uint32_t) tmpVal;
2419 val = *((uint32_t *) (user_area+offset));
2422 else if (size == 8) {
2423 val = *((uint64_t *) (user_area+offset));
2429 pthrd_printf("Register %2s has value %16lx, offset %d\n", reg.name().c_str(), val, offset);
2430 regpool.regs[reg] = val;
2435 bool linux_thread::plat_getRegister(Dyninst::MachRegister reg, Dyninst::MachRegisterVal &val)
2437 #if defined(bug_registers_after_exit)
2438 /* On some kernels, attempting to read registers from a thread in a pre-Exit
2439 * state causes an oops
2442 perr_printf("Cannot reliably retrieve registers from an exited thread\n");
2443 setLastError(err_exited, "Cannot retrieve registers from an exited thread");
2448 if (x86::fsbase == reg || x86::gsbase == reg
2449 || x86_64::fsbase == reg || x86_64::gsbase == reg) {
2450 return getSegmentBase(reg, val);
2453 init_dynreg_to_user();
2454 dynreg_to_user_t::iterator i = dynreg_to_user.find(reg);
2455 if (i == dynreg_to_user.end() || reg.getArchitecture() != llproc()->getTargetArch()) {
2456 perr_printf("Recieved unexpected register %s on thread %d\n", reg.name().c_str(), lwp);
2457 setLastError(err_badparam, "Invalid register");
2461 const unsigned offset = i->second.first;
2462 const unsigned size = i->second.second;
2463 assert(sizeof(val) >= size);
2464 if(sizeof(val) < size) return false;
2469 * Here it is different for aarch64,
2470 * I have to use GETREGSET instead of PEEKUSER
2472 unsigned long result;
2473 #if defined(arch_aarch64)
2476 iovec.iov_base = ®s;
2477 iovec.iov_len = sizeof(regs);
2478 long ret = do_ptrace((pt_req)PTRACE_GETREGSET, lwp, (void *)NT_PRSTATUS, &iovec);
2480 // perr_printf("ERROR-ARM: Unable to fetch registers!\n");
2483 result = regs[(int)(offset/8)]; //30, 31(sp), 32(pc), 33(pstate)
2485 result = do_ptrace((pt_req) PTRACE_PEEKUSER, lwp, (void *) (unsigned long) offset, NULL);
2487 //unsigned long result = do_ptrace((pt_req) PTRACE_PEEKUSER, lwp, (void *) (unsigned long) offset, NULL);
2490 perr_printf("Error reading registers from %d: %s\n", lwp, strerror(errno));
2491 //pthrd_printf("ARM-Info: offset(%d-%d)\n", (void *)(unsigned long)offset, offset/8);
2493 setLastError(err_internal, "Could not read register from thread");
2498 pthrd_printf("Register %s has value 0x%lx\n", reg.name().c_str(), val);
2502 #if defined(PT_SETREGS)
2503 #define MY_PTRACE_SETREGS PT_SETREGS
2504 #elif defined(arch_aarch64)
2506 //#define MY_PTRACE_SETREGS PTRACE_SETREGSET
2508 //Common kernel value for PTRACE_SETREGS
2509 #define MY_PTRACE_SETREGS 13
2512 bool linux_thread::plat_setAllRegisters(int_registerPool ®pool)
2514 #if defined(MY_PTRACE_SETREGS)
2515 static bool have_setregs = true;
2517 #define MY_PTRACE_SETREGS 0
2518 static bool have_setregs = false;
2520 static bool tested_setregs = false;
2521 #if defined(bug_registers_after_exit)
2522 /* On some kernels, attempting to read registers from a thread in a pre-Exit
2523 * state causes an oops
2526 perr_printf("Cannot reliably retrieve registers from an exited thread\n");
2527 setLastError(err_exited, "Cannot retrieve registers from an exited thread");
2535 unsigned char user_area[MAX_USER_SIZE];
2536 //Fill in 'user_area' with the contents of regpool.
2537 if( !plat_convertToSystemRegs(regpool, user_area) ) return false;
2539 //Double up the user_area parameter because if MY_PTRACE_SETREGS is
2540 // defined to PPC_PTRACE_SETREGS than the parameters data and addr
2541 // pointers get swapped (just because linux hates us). Since the
2542 // other is ignored, we pass it in twice.
2543 int result = do_ptrace((pt_req) MY_PTRACE_SETREGS, lwp, user_area, user_area);
2546 if (error == EIO && !tested_setregs) {
2547 pthrd_printf("PTRACE_SETREGS not working. Trying PTRACE_POKEUSER\n");
2548 have_setregs = false;
2551 perr_printf("Error setting registers for %d\n", lwp);
2552 setLastError(err_internal, "Could not read user area from thread");
2556 tested_setregs = true;
2560 #if defined(arch_aarch64)
2561 //pthrd_printf("ARM-info: setAllregisters.\n");
2565 iovec.iov_base = ®s;
2566 iovec.iov_len = sizeof(regs);
2569 for (int_registerPool::iterator i = regpool.regs.begin(); i != regpool.regs.end(); i++) {
2570 dynreg_to_user_t::iterator di = dynreg_to_user.find(i->first);
2571 assert(di != dynreg_to_user.end());
2572 int regs_pos = (int)(di->second.first / sizeof(unsigned long));
2573 assert( regs_pos < MAX_USER_REGS);
2574 regs[regs_pos] = i->second;
2578 ret = do_ptrace((pt_req)PTRACE_SETREGSET, lwp, (void *)NT_PRSTATUS, &iovec);
2581 //perr_printf("ERROR-ARM: Unable to set registers: %s\n", strerror(error) );
2583 setLastError(err_exited, "Process exited during operation");
2585 setLastError(err_internal, "Could not read user area from thread");
2589 Dyninst::Architecture curplat = llproc()->getTargetArch();
2590 init_dynreg_to_user();
2591 for (int_registerPool::iterator i = regpool.regs.begin(); i != regpool.regs.end(); i++) {
2592 assert(i->first.getArchitecture() == curplat);
2593 dynreg_to_user_t::iterator di = dynreg_to_user.find(i->first);
2594 assert(di != dynreg_to_user.end());
2596 //Don't treat errors on these registers as real errors.
2597 bool not_present = true;
2598 if (curplat == Arch_ppc32)
2599 not_present = (i->first == ppc32::mq || i->first == ppc32::dar ||
2600 i->first == ppc32::dsisr || i->first == ppc32::trap ||
2601 i->first == ppc32::or3);
2608 if (Dyninst::getArchAddressWidth(curplat) == 4) {
2609 res = (uint32_t) i->second;
2612 res = (uint64_t) i->second;
2614 result = do_ptrace((pt_req) PTRACE_POKEUSER, lwp, (void *) (unsigned long) di->second.first, (void *) res);
2616 //if (result != 0) {
2619 perr_printf("Error setting register %s for %d at %d: %s\n", i->first.name().c_str(),
2620 lwp, (int) di->second.first, strerror(error));
2622 setLastError(err_exited, "Process exited during operation");
2624 setLastError(err_internal, "Could not read user area from thread");
2631 pthrd_printf("Successfully set the values of all registers for %d\n", lwp);
2635 bool linux_thread::plat_convertToSystemRegs(const int_registerPool ®pool, unsigned char *user_area,
2638 init_dynreg_to_user();
2640 Architecture curplat = llproc()->getTargetArch();
2641 unsigned num_found = 0;
2642 for (dynreg_to_user_t::const_iterator i = dynreg_to_user.begin(); i != dynreg_to_user.end(); i++)
2644 const MachRegister reg = i->first;
2645 MachRegisterVal val;
2646 if (reg.getArchitecture() != curplat)
2651 int rclass = (int) reg.regClass();
2653 switch (llproc()->getTargetArch()) {
2654 //In this case our definition of GPR is anything stored in the elf_gregset_t of
2656 case Dyninst::Arch_x86:
2657 is_gpr = ((rclass == x86::GPR) || (rclass == x86::FLAG) ||
2658 (rclass == x86::MISC) || (rclass == x86::SEG) || !rclass);
2660 case Dyninst::Arch_x86_64:
2661 is_gpr = ((rclass == x86_64::GPR) || (rclass == x86_64::FLAG) ||
2662 (rclass == x86_64::MISC) || (rclass == x86_64::SEG) || !rclass);
2664 case Dyninst::Arch_ppc32:
2667 case Dyninst::Arch_ppc64:
2670 case Dyninst::Arch_aarch64:
2684 const unsigned int offset = i->second.first;
2685 const unsigned int size = i->second.second;
2686 assert(offset+size < MAX_USER_SIZE);
2688 if ((offset+size) > sizeof(prgregset_t)) continue;
2690 int_registerPool::reg_map_t::const_iterator j = regpool.regs.find(reg);
2691 assert(j != regpool.regs.end());
2695 if( sizeof(void *) == 8 ) {
2696 *((uint64_t *) (user_area+offset)) = (uint64_t) val;
2698 *((uint32_t *) (user_area+offset)) = (uint32_t) val;
2701 else if (size == 8) {
2702 *((uint64_t *) (user_area+offset)) = (uint64_t) val;
2707 pthrd_printf("Register %s gets value %lx, offset %d\n", reg.name().c_str(), val, offset);
2710 if (!gprs_only && (num_found != regpool.regs.size()))
2712 setLastError(err_badparam, "Invalid register set passed to setAllRegisters");
2713 perr_printf("Couldn't find all registers in the register set %u/%u\n", num_found,
2714 (unsigned int) regpool.regs.size());
2721 bool linux_thread::plat_setRegister(Dyninst::MachRegister reg, Dyninst::MachRegisterVal val)
2723 #if defined(bug_registers_after_exit)
2724 /* On some kernels, attempting to read registers from a thread in a pre-Exit
2725 * state causes an oops
2728 perr_printf("Cannot reliably retrieve registers from an exited thread\n");
2729 setLastError(err_exited, "Cannot retrieve registers from an exited thread");
2734 init_dynreg_to_user();
2735 dynreg_to_user_t::iterator i = dynreg_to_user.find(reg);
2736 if (reg.getArchitecture() != llproc()->getTargetArch() ||
2737 i == dynreg_to_user.end())
2739 setLastError(err_badparam, "Invalid register passed to setRegister");
2740 perr_printf("User passed invalid register %s to plat_setRegister, arch is %x\n",
2741 reg.name().c_str(), (unsigned int) reg.getArchitecture());
2745 const unsigned int offset = i->second.first;
2746 const unsigned int size = i->second.second;
2750 value = (uint32_t) val;
2752 else if (size == 8) {
2753 value = (uint64_t) val;
2761 #if defined(arch_aarch64)
2765 iovec.iov_base = ®s;
2766 iovec.iov_len = sizeof(regs);
2768 ret = do_ptrace((pt_req)PTRACE_GETREGSET, lwp, (void *)NT_PRSTATUS, &iovec);
2770 perr_printf("ERROR-ARM: Unable to fetch registers!\n");
2774 //set the corresponding reg
2775 assert( (int)(offset/8) < 34 );
2776 regs[(int)(offset/8)] = value;
2779 ret = do_ptrace((pt_req)PTRACE_SETREGSET, lwp, (void *)NT_PRSTATUS, &iovec);
2781 perr_printf("ERROR-ARM: Unable to set registers!\n");
2786 result = do_ptrace((pt_req) PTRACE_POKEUSER, lwp, (void *) (uintptr_t)offset, (void *) value);
2788 //result = do_ptrace((pt_req) PTRACE_POKEUSER, lwp, (void *) (uintptr_t)offset, (void *) value);
2789 pthrd_printf("Set register %s (size %u, offset %u) to value %lx\n", reg.name().c_str(), size, offset, val);
2793 setLastError(err_exited, "Process exited during operation");
2795 setLastError(err_internal, "Could not set register value");
2796 perr_printf("Unable to set value of register %s in thread %d: %s (%d)\n",
2797 reg.name().c_str(), lwp, strerror(error), error);
2804 bool linux_thread::plat_getAllRegistersAsync(allreg_response::ptr result)
2806 bool b = plat_getAllRegisters(*result->getRegPool());
2808 result->markError(getLastError());
2810 fake_async_msgs.push_back(result->getID());
2814 bool linux_thread::plat_getRegisterAsync(Dyninst::MachRegister reg,
2815 reg_response::ptr result)
2817 Dyninst::MachRegisterVal val = 0;
2818 bool b = plat_getRegister(reg, val);
2821 result->markError(getLastError());
2823 fake_async_msgs.push_back(result->getID());
2827 bool linux_thread::plat_setAllRegistersAsync(int_registerPool &pool,
2828 result_response::ptr result)
2830 bool b = plat_setAllRegisters(pool);
2832 result->markError(getLastError());
2838 fake_async_msgs.push_back(result->getID());
2842 bool linux_thread::plat_setRegisterAsync(Dyninst::MachRegister reg,
2843 Dyninst::MachRegisterVal val,
2844 result_response::ptr result)
2846 bool b = plat_setRegister(reg, val);
2848 result->markError(getLastError());
2854 fake_async_msgs.push_back(result->getID());
2858 bool linux_thread::attach()
2860 if (llproc()->threadPool()->initialThread() == this) {
2864 if (attach_status != as_needs_attach)
2866 pthrd_printf("thread::attach called on running thread %d/%d, should "
2867 "be auto-attached.\n", llproc()->getPid(), lwp);
2871 pthrd_printf("Calling PTRACE_ATTACH on thread %d/%d\n",
2872 llproc()->getPid(), lwp);
2873 int result = do_ptrace((pt_req) PTRACE_ATTACH, lwp, NULL, NULL);
2875 perr_printf("Failed to attach to thread: %s\n", strerror(errno));
2876 setLastError(err_internal, "Failed to attach to thread");
2882 #if !defined(ARCH_GET_FS)
2883 #define ARCH_GET_FS 0x1003
2885 #if !defined(ARCH_GET_GS)
2886 #define ARCH_GET_GS 0x1004
2888 #if !defined(PTRACE_GET_THREAD_AREA)
2889 #define PTRACE_GET_THREAD_AREA 25
2891 #if !defined(PTRACE_ARCH_PRCTL)
2892 #define PTRACE_ARCH_PRCTL 30
2894 #define FS_REG_NUM 25
2895 #define GS_REG_NUM 26
2897 #if !defined(PTRACE_ARM_GET_THREAD_AREA)
2898 #define PTRACE_ARM_GET_THREAD_AREA 22
2901 bool linux_thread::thrdb_getThreadArea(int val, Dyninst::Address &addr)
2903 Dyninst::Architecture arch = llproc()->getTargetArch();
2907 int result = do_ptrace((pt_req) PTRACE_GET_THREAD_AREA, lwp, (void *) (intptr_t)val, &addrv);
2910 perr_printf("Error doing PTRACE_GET_THREAD_AREA on %d/%d: %s\n", llproc()->getPid(), lwp, strerror(error));
2912 setLastError(err_exited, "Process exited during operation");
2914 setLastError(err_internal, "Error doing PTRACE_GET_THREAD_AREA\n");
2917 addr = (Dyninst::Address) addrv[1];
2922 if (val == FS_REG_NUM)
2924 else if (val == GS_REG_NUM)
2927 perr_printf("Bad value (%d) passed to thrdb_getThreadArea\n", val);
2931 int result = do_ptrace((pt_req) PTRACE_ARCH_PRCTL, lwp, &addrv, (void *) op);
2934 perr_printf("Error doing PTRACE_ARCH_PRCTL on %d/%d: %s\n", llproc()->getPid(), lwp, strerror(error));
2936 setLastError(err_exited, "Process exited during operation");
2938 setLastError(err_internal, "Error doing PTRACE_ARCH_PRCTL\n");
2941 addr = (Dyninst::Address) addrv;
2945 #if defined(arch_aarch64)
2949 iovec.iov_base = ®
2950 iovec.iov_len = sizeof (reg);
2952 int result = do_ptrace((pt_req) PTRACE_GETREGSET, lwp, (void *)NT_ARM_TLS, &iovec);
2955 perr_printf("Error doing PTRACE_ARM_GET_THREAD_AREA on %d/%d: %s\n", llproc()->getPid(), lwp, strerror(error));
2957 setLastError(err_exited, "Process exited during operation");
2959 setLastError(err_internal, "Error doing PTRACE_ARM_GET_THREAD_AREA\n");
2962 addr = (Dyninst::Address) (reg-val);
2969 assert(0); //Should not be needed on non-x86 and non-arm
2974 //Copied from /usr/include/asm/ldt.h, as it was not available on all machines
2975 struct linux_x86_user_desc {
2976 unsigned int entry_number;
2977 unsigned long base_addr;
2979 unsigned int seg_32bit:1;
2980 unsigned int contents:2;
2981 unsigned int read_exec_only:1;
2982 unsigned int limit_in_pages:1;
2983 unsigned int seg_not_present:1;
2984 unsigned int useable:1;
2987 bool linux_thread::getSegmentBase(Dyninst::MachRegister reg, Dyninst::MachRegisterVal &val)
2989 switch (llproc()->getTargetArch())
2993 // use ptrace_arch_prctl
2994 pthrd_printf("Segment bases on x86_64 not implemented\n");
2997 MachRegister segmentSelectorReg;
2998 MachRegisterVal segmentSelectorVal;
2999 unsigned long entryNumber;
3000 struct linux_x86_user_desc entryDesc;
3004 case x86::ifsbase: segmentSelectorReg = x86::fs; break;
3005 case x86::igsbase: segmentSelectorReg = x86::gs; break;
3007 pthrd_printf("Failed to get unrecognized segment base\n");
3012 if (!plat_getRegister(segmentSelectorReg, segmentSelectorVal))
3014 pthrd_printf("Failed to get segment base with selector %s\n", segmentSelectorReg.name().c_str());
3017 entryNumber = segmentSelectorVal / 8;
3019 pthrd_printf("Get segment base doing PTRACE with entry %lu\n", entryNumber);
3020 long result = do_ptrace((pt_req) PTRACE_GET_THREAD_AREA,
3021 lwp, (void *) entryNumber, (void *) &entryDesc);
3022 if (result == -1 && errno != 0) {
3024 pthrd_printf("PTRACE to get segment base failed: %s\n", strerror(errno));
3026 setLastError(err_exited, "Process exited during operation");
3030 val = entryDesc.base_addr;
3031 pthrd_printf("Got segment base: 0x%lx\n", val);
3035 assert(!"This is not implemented on this architecture");
3040 bool linux_thread::suppressSanityChecks()
3042 return generator_started_exit_processing;
3045 linux_x86_thread::linux_x86_thread(int_process *p, Dyninst::THR_ID t, Dyninst::LWP l) :
3046 int_thread(p, t, l),
3047 thread_db_thread(p, t, l),
3048 linux_thread(p, t, l),
3053 linux_x86_thread::~linux_x86_thread()
3057 linux_ppc_thread::linux_ppc_thread(int_process *p, Dyninst::THR_ID t, Dyninst::LWP l) :
3058 int_thread(p, t, l),
3059 thread_db_thread(p, t, l),
3060 linux_thread(p, t, l),
3065 linux_ppc_thread::~linux_ppc_thread()
3069 linux_arm_thread::linux_arm_thread(int_process *p, Dyninst::THR_ID t, Dyninst::LWP l) :
3070 int_thread(p, t, l),
3071 thread_db_thread(p, t, l),
3072 linux_thread(p, t, l),
3077 linux_arm_thread::~linux_arm_thread()
3081 ArchEventLinux::ArchEventLinux(bool inter_) :
3084 interrupted(inter_),
3086 child_pid(NULL_PID),
3091 ArchEventLinux::ArchEventLinux(pid_t p, int s) :
3096 child_pid(NULL_PID),
3101 ArchEventLinux::ArchEventLinux(int e) :
3106 child_pid(NULL_PID),
3111 ArchEventLinux::~ArchEventLinux()
3115 std::vector<ArchEventLinux *> ArchEventLinux::pending_events;
3117 bool ArchEventLinux::findPairedEvent(ArchEventLinux* &parent, ArchEventLinux* &child)
3120 if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGTRAP) {
3121 //'this' event is a parent, search list for a child
3124 else if (WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP) {
3125 //'this' event is a child, search list for a parent
3134 vector<ArchEventLinux *>::iterator i;
3135 for (i = pending_events.begin(); i != pending_events.end(); i++) {
3136 parent = is_parent ? this : *i;
3137 child = is_parent ? *i : this;
3138 if (parent->child_pid == child->pid) {
3139 pending_events.erase(i);
3146 void ArchEventLinux::postponePairedEvent()
3148 pending_events.push_back(this);
3151 LinuxHandleNewThr::LinuxHandleNewThr() :
3152 Handler("Linux New Thread")
3156 LinuxHandleNewThr::~LinuxHandleNewThr()
3160 Handler::handler_ret_t LinuxHandleNewThr::handleEvent(Event::ptr ev)
3162 linux_thread *thr = NULL;
3163 if (ev->getEventType().code() == EventType::Bootstrap) {
3164 thr = dynamic_cast<linux_thread *>(ev->getThread()->llthrd());
3166 else if (ev->getEventType().code() == EventType::ThreadCreate) {
3167 Dyninst::LWP lwp = static_cast<EventNewThread *>(ev.get())->getLWP();
3168 ProcPool()->condvar()->lock();
3169 thr = dynamic_cast<linux_thread *>(ProcPool()->findThread(lwp));
3170 ProcPool()->condvar()->unlock();
3174 pthrd_printf("Setting ptrace options for new thread %d\n", thr->getLWP());
3179 int LinuxHandleNewThr::getPriority() const
3181 return PostPlatformPriority;
3184 void LinuxHandleNewThr::getEventTypesHandled(std::vector<EventType> &etypes)
3186 etypes.push_back(EventType(EventType::None, EventType::ThreadCreate));
3187 etypes.push_back(EventType(EventType::None, EventType::Bootstrap));
3190 LinuxHandleLWPDestroy::LinuxHandleLWPDestroy()
3191 : Handler("Linux LWP Destroy")
3195 LinuxHandleLWPDestroy::~LinuxHandleLWPDestroy()
3199 Handler::handler_ret_t LinuxHandleLWPDestroy::handleEvent(Event::ptr ev) {
3200 int_thread *thrd = ev->getThread()->llthrd();
3202 // This handler is necessary because SIGSTOPS cannot be sent to pre-destroyed
3203 // threads -- these stops will never be delivered to the debugger
3205 // Setting the exiting state in the thread will avoid any waiting for pending stops
3208 thrd->setExiting(true);
3210 // If there is a pending stop, need to handle it here because there is
3211 // no guarantee that the stop will ever be received
3212 if( thrd->hasPendingStop() ) {
3213 thrd->setPendingStop(false);
3219 int LinuxHandleLWPDestroy::getPriority() const
3221 return PostPlatformPriority;
3224 void LinuxHandleLWPDestroy::getEventTypesHandled(std::vector<EventType> &etypes)
3226 etypes.push_back(EventType(EventType::Pre, EventType::LWPDestroy));
3229 LinuxHandleForceTerminate::LinuxHandleForceTerminate() :
3230 Handler("Linux Force Termination") {};
3232 LinuxHandleForceTerminate::~LinuxHandleForceTerminate() {}
3234 Handler::handler_ret_t LinuxHandleForceTerminate::handleEvent(Event::ptr ev) {
3235 int_process *proc = ev->getProcess()->llproc();
3237 for (int_threadPool::iterator iter = proc->threadPool()->begin();
3238 iter != proc->threadPool()->end(); ++iter) {
3239 do_ptrace((pt_req) PTRACE_DETACH, (*iter)->getLWP(), NULL, NULL);
3244 int LinuxHandleForceTerminate::getPriority() const
3246 return PostPlatformPriority;
3249 void LinuxHandleForceTerminate::getEventTypesHandled(std::vector<EventType> &etypes)
3251 etypes.push_back(EventType(EventType::Post, EventType::ForceTerminate));
3254 HandlerPool *linux_createDefaultHandlerPool(HandlerPool *hpool)
3256 static bool initialized = false;
3257 static LinuxHandleNewThr *lbootstrap = NULL;
3258 static LinuxHandleForceTerminate *lterm = NULL;
3260 lbootstrap = new LinuxHandleNewThr();
3261 lterm = new LinuxHandleForceTerminate();
3264 hpool->addHandler(lbootstrap);
3265 hpool->addHandler(lterm);
3266 thread_db_process::addThreadDBHandlers(hpool);
3267 sysv_process::addSysVHandlers(hpool);
3271 HandlerPool *plat_createDefaultHandlerPool(HandlerPool *hpool)
3273 return linux_createDefaultHandlerPool(hpool);
3276 bool ProcessPool::LWPIDsAreUnique()
3281 LinuxPtrace *LinuxPtrace::linuxptrace = NULL;
3283 long do_ptrace(pt_req request, pid_t pid, void *addr, void *data)
3285 return LinuxPtrace::getPtracer()->ptrace_int(request, pid, addr, data);
3288 LinuxPtrace *LinuxPtrace::getPtracer()
3291 linuxptrace = new LinuxPtrace();
3292 assert(linuxptrace);
3293 linuxptrace->start();
3299 LinuxPtrace::LinuxPtrace() :
3300 ptrace_request(unknown),
3301 request((pt_req) 0),
3314 LinuxPtrace::~LinuxPtrace()
3318 static void start_ptrace(void *lp)
3320 LinuxPtrace *linuxptrace = (LinuxPtrace *) (lp);
3321 linuxptrace->main();
3324 void LinuxPtrace::start()
3327 thrd.spawn(start_ptrace, this);
3332 void LinuxPtrace::main()
3341 switch(ptrace_request) {
3343 bret = proc->plat_create_int();
3346 ret = ptrace(request, pid, addr, data);
3348 case ptrace_bulkread:
3349 bret = PtraceBulkRead(remote_addr, size, data, pid);
3351 case ptrace_bulkwrite:
3352 bret = PtraceBulkWrite(remote_addr, size, data, pid);
3363 void LinuxPtrace::start_request()
3365 request_lock.lock();
3370 void LinuxPtrace::waitfor_ret()
3377 void LinuxPtrace::end_request()
3380 request_lock.unlock();
3383 long LinuxPtrace::ptrace_int(pt_req request_, pid_t pid_, void *addr_, void *data_)
3387 ptrace_request = ptrace_req;
3404 bool LinuxPtrace::plat_create(linux_process *p)
3407 ptrace_request = create_req;
3415 bool LinuxPtrace::ptrace_read(Dyninst::Address inTrace, unsigned size_,
3416 void *inSelf, int pid_)
3419 ptrace_request = ptrace_bulkread;
3420 remote_addr = inTrace;
3430 bool LinuxPtrace::ptrace_write(Dyninst::Address inTrace, unsigned size_,
3431 const void *inSelf, int pid_)
3434 ptrace_request = ptrace_bulkwrite;
3435 remote_addr = inTrace;
3436 data = const_cast<void *>(inSelf);
3446 void linux_process::plat_adjustSyncType(Event::ptr ev, bool gen)
3450 if (ev->getEventType().code() != EventType::LWPDestroy ||
3451 ev->getEventType().time() != EventType::Pre)
3454 int_thread *thrd = ev->getThread()->llthrd();
3455 if (thrd->getGeneratorState().getState() != int_thread::running)
3458 // So we have a pre-LWP destroy and a running generator; this means
3459 // that someone continued the thread during decode and it is now
3460 // gone. So set the event to async and set the generator state to
3463 pthrd_printf("plat_adjustSyncType: thread %d raced with exit, setting event to async\n",
3466 //thrd->getGeneratorState().setState(int_thread::exited);
3467 ev->setSyncType(Event::async);
3468 //thrd->getHandlerState().setState(int_thread::exited);