1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "NativeProcessLinux.h"
23 #include <unordered_map>
25 // Other libraries and framework includes
26 #include "lldb/Core/EmulateInstruction.h"
27 #include "lldb/Core/Error.h"
28 #include "lldb/Core/ModuleSpec.h"
29 #include "lldb/Core/RegisterValue.h"
30 #include "lldb/Core/State.h"
31 #include "lldb/Host/Host.h"
32 #include "lldb/Host/HostProcess.h"
33 #include "lldb/Host/ThreadLauncher.h"
34 #include "lldb/Host/common/NativeBreakpoint.h"
35 #include "lldb/Host/common/NativeRegisterContext.h"
36 #include "lldb/Host/linux/ProcessLauncherLinux.h"
37 #include "lldb/Symbol/ObjectFile.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/ProcessLaunchInfo.h"
40 #include "lldb/Target/Target.h"
41 #include "lldb/Utility/LLDBAssert.h"
42 #include "lldb/Utility/PseudoTerminal.h"
43 #include "lldb/Utility/StringExtractor.h"
45 #include "NativeThreadLinux.h"
46 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
47 #include "ProcFileReader.h"
50 // System includes - They have to be included after framework includes because
52 // macros which collide with variable names in other modules
53 #include <linux/unistd.h>
54 #include <sys/socket.h>
56 #include <sys/syscall.h>
57 #include <sys/types.h>
61 #include "lldb/Host/linux/Ptrace.h"
62 #include "lldb/Host/linux/Uio.h"
64 // Support hardware breakpoints in case it has not been defined
70 using namespace lldb_private;
71 using namespace lldb_private::process_linux;
74 // Private bits we only need internally.
76 static bool ProcessVmReadvSupported() {
77 static bool is_supported;
78 static std::once_flag flag;
80 std::call_once(flag, [] {
81 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
83 uint32_t source = 0x47424742;
86 struct iovec local, remote;
87 remote.iov_base = &source;
88 local.iov_base = &dest;
89 remote.iov_len = local.iov_len = sizeof source;
91 // We shall try if cross-process-memory reads work by attempting to read a
92 // value from our own process.
93 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
94 is_supported = (res == sizeof(source) && source == dest);
97 log->Printf("%s: Detected kernel support for process_vm_readv syscall. "
98 "Fast memory reads enabled.",
101 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast "
102 "memory reads disabled.",
103 __FUNCTION__, strerror(errno));
111 void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) {
112 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
116 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
117 log->Printf("%s: setting STDIN to '%s'", __FUNCTION__,
118 action->GetFileSpec().GetCString());
120 log->Printf("%s leaving STDIN as is", __FUNCTION__);
122 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
123 log->Printf("%s setting STDOUT to '%s'", __FUNCTION__,
124 action->GetFileSpec().GetCString());
126 log->Printf("%s leaving STDOUT as is", __FUNCTION__);
128 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
129 log->Printf("%s setting STDERR to '%s'", __FUNCTION__,
130 action->GetFileSpec().GetCString());
132 log->Printf("%s leaving STDERR as is", __FUNCTION__);
135 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args;
137 log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i,
138 *args ? *args : "nullptr");
141 void DisplayBytes(StreamString &s, void *bytes, uint32_t count) {
142 uint8_t *ptr = (uint8_t *)bytes;
143 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
144 for (uint32_t i = 0; i < loop_count; i++) {
145 s.Printf("[%x]", *ptr);
150 void PtraceDisplayBytes(int &req, void *data, size_t data_size) {
152 Log *verbose_log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(
153 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
157 case PTRACE_POKETEXT: {
158 DisplayBytes(buf, &data, 8);
159 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
162 case PTRACE_POKEDATA: {
163 DisplayBytes(buf, &data, 8);
164 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
167 case PTRACE_POKEUSER: {
168 DisplayBytes(buf, &data, 8);
169 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
172 case PTRACE_SETREGS: {
173 DisplayBytes(buf, data, data_size);
174 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
177 case PTRACE_SETFPREGS: {
178 DisplayBytes(buf, data, data_size);
179 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
182 case PTRACE_SETSIGINFO: {
183 DisplayBytes(buf, data, sizeof(siginfo_t));
184 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
187 case PTRACE_SETREGSET: {
188 // Extract iov_base from data, which is a pointer to the struct IOVEC
189 DisplayBytes(buf, *(void **)data, data_size);
190 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
198 static constexpr unsigned k_ptrace_word_size = sizeof(void *);
199 static_assert(sizeof(long) >= k_ptrace_word_size,
200 "Size of long must be larger than ptrace word size");
201 } // end of anonymous namespace
203 // Simple helper function to ensure flags are enabled on the given file
205 static Error EnsureFDFlags(int fd, int flags) {
208 int status = fcntl(fd, F_GETFL);
210 error.SetErrorToErrno();
214 if (fcntl(fd, F_SETFL, status | flags) == -1) {
215 error.SetErrorToErrno();
222 // -----------------------------------------------------------------------------
223 // Public Static Methods
224 // -----------------------------------------------------------------------------
226 Error NativeProcessProtocol::Launch(
227 ProcessLaunchInfo &launch_info,
228 NativeProcessProtocol::NativeDelegate &native_delegate, MainLoop &mainloop,
229 NativeProcessProtocolSP &native_process_sp) {
230 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
234 // Verify the working directory is valid if one was specified.
235 FileSpec working_dir{launch_info.GetWorkingDirectory()};
237 (!working_dir.ResolvePath() ||
238 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
239 error.SetErrorStringWithFormat("No such file or directory: %s",
240 working_dir.GetCString());
244 // Create the NativeProcessLinux in launch mode.
245 native_process_sp.reset(new NativeProcessLinux());
247 if (!native_process_sp->RegisterNativeDelegate(native_delegate)) {
248 native_process_sp.reset();
249 error.SetErrorStringWithFormat("failed to register the native delegate");
253 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)
254 ->LaunchInferior(mainloop, launch_info);
257 native_process_sp.reset();
259 log->Printf("NativeProcessLinux::%s failed to launch process: %s",
260 __FUNCTION__, error.AsCString());
264 launch_info.SetProcessID(native_process_sp->GetID());
269 Error NativeProcessProtocol::Attach(
270 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate,
271 MainLoop &mainloop, NativeProcessProtocolSP &native_process_sp) {
272 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
273 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
274 log->Printf("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
276 // Retrieve the architecture for the running process.
277 ArchSpec process_arch;
278 Error error = ResolveProcessArchitecture(pid, process_arch);
279 if (!error.Success())
282 std::shared_ptr<NativeProcessLinux> native_process_linux_sp(
283 new NativeProcessLinux());
285 if (!native_process_linux_sp->RegisterNativeDelegate(native_delegate)) {
286 error.SetErrorStringWithFormat("failed to register the native delegate");
290 native_process_linux_sp->AttachToInferior(mainloop, pid, error);
291 if (!error.Success())
294 native_process_sp = native_process_linux_sp;
298 // -----------------------------------------------------------------------------
299 // Public Instance Methods
300 // -----------------------------------------------------------------------------
302 NativeProcessLinux::NativeProcessLinux()
303 : NativeProcessProtocol(LLDB_INVALID_PROCESS_ID), m_arch(),
304 m_supports_mem_region(eLazyBoolCalculate), m_mem_region_cache(),
305 m_pending_notification_tid(LLDB_INVALID_THREAD_ID) {}
307 void NativeProcessLinux::AttachToInferior(MainLoop &mainloop, lldb::pid_t pid,
309 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
311 log->Printf("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__,
314 m_sigchld_handle = mainloop.RegisterSignal(
315 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
316 if (!m_sigchld_handle)
319 error = ResolveProcessArchitecture(pid, m_arch);
320 if (!error.Success())
323 // Set the architecture to the exe architecture.
325 log->Printf("NativeProcessLinux::%s (pid = %" PRIi64
326 ") detected architecture %s",
327 __FUNCTION__, pid, m_arch.GetArchitectureName());
330 SetState(eStateAttaching);
335 Error NativeProcessLinux::LaunchInferior(MainLoop &mainloop,
336 ProcessLaunchInfo &launch_info) {
338 m_sigchld_handle = mainloop.RegisterSignal(
339 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
340 if (!m_sigchld_handle)
343 SetState(eStateLaunching);
345 MaybeLogLaunchInfo(launch_info);
348 ProcessLauncherLinux().LaunchProcess(launch_info, error).GetProcessId();
352 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
354 // Wait for the child process to trap on its call to execve.
357 if ((wpid = waitpid(pid, &status, 0)) < 0) {
358 error.SetErrorToErrno();
360 log->Printf("NativeProcessLinux::%s waitpid for inferior failed with %s",
361 __FUNCTION__, error.AsCString());
363 // Mark the inferior as invalid.
364 // FIXME this could really use a new state - eStateLaunchFailure. For now,
365 // using eStateInvalid.
366 SetState(StateType::eStateInvalid);
370 assert(WIFSTOPPED(status) && (wpid == static_cast<::pid_t>(pid)) &&
371 "Could not sync with inferior process.");
374 log->Printf("NativeProcessLinux::%s inferior started, now in stopped state",
377 error = SetDefaultPtraceOpts(pid);
380 log->Printf("NativeProcessLinux::%s inferior failed to set default "
381 "ptrace options: %s",
382 __FUNCTION__, error.AsCString());
384 // Mark the inferior as invalid.
385 // FIXME this could really use a new state - eStateLaunchFailure. For now,
386 // using eStateInvalid.
387 SetState(StateType::eStateInvalid);
392 // Release the master terminal descriptor and pass it off to the
393 // NativeProcessLinux instance. Similarly stash the inferior pid.
394 m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
396 launch_info.SetProcessID(pid);
398 if (m_terminal_fd != -1) {
399 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
402 log->Printf("NativeProcessLinux::%s inferior EnsureFDFlags failed for "
403 "ensuring terminal O_NONBLOCK setting: %s",
404 __FUNCTION__, error.AsCString());
406 // Mark the inferior as invalid.
407 // FIXME this could really use a new state - eStateLaunchFailure. For
408 // now, using eStateInvalid.
409 SetState(StateType::eStateInvalid);
416 log->Printf("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__,
419 ResolveProcessArchitecture(m_pid, m_arch);
420 NativeThreadLinuxSP thread_sp = AddThread(pid);
421 assert(thread_sp && "AddThread() returned a nullptr thread");
422 thread_sp->SetStoppedBySignal(SIGSTOP);
423 ThreadWasCreated(*thread_sp);
425 // Let our process instance know the thread has stopped.
426 SetCurrentThreadID(thread_sp->GetID());
427 SetState(StateType::eStateStopped);
431 log->Printf("NativeProcessLinux::%s inferior launching succeeded",
434 log->Printf("NativeProcessLinux::%s inferior launching failed: %s",
435 __FUNCTION__, error.AsCString());
440 ::pid_t NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) {
441 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
443 // Use a map to keep track of the threads which we have attached/need to
445 Host::TidMap tids_to_attach;
447 error.SetErrorToGenericError();
448 error.SetErrorString("Attaching to process 1 is not allowed.");
452 while (Host::FindProcessThreads(pid, tids_to_attach)) {
453 for (Host::TidMap::iterator it = tids_to_attach.begin();
454 it != tids_to_attach.end();) {
455 if (it->second == false) {
456 lldb::tid_t tid = it->first;
458 // Attach to the requested process.
459 // An attach will cause the thread to stop with a SIGSTOP.
460 error = PtraceWrapper(PTRACE_ATTACH, tid);
462 // No such thread. The thread may have exited.
463 // More error handling may be needed.
464 if (error.GetError() == ESRCH) {
465 it = tids_to_attach.erase(it);
472 // Need to use __WALL otherwise we receive an error with errno=ECHLD
473 // At this point we should have a thread stopped if waitpid succeeds.
474 if ((status = waitpid(tid, NULL, __WALL)) < 0) {
475 // No such thread. The thread may have exited.
476 // More error handling may be needed.
477 if (errno == ESRCH) {
478 it = tids_to_attach.erase(it);
481 error.SetErrorToErrno();
486 error = SetDefaultPtraceOpts(tid);
491 log->Printf("NativeProcessLinux::%s() adding tid = %" PRIu64,
496 // Create the thread, mark it as stopped.
497 NativeThreadLinuxSP thread_sp(AddThread(static_cast<lldb::tid_t>(tid)));
498 assert(thread_sp && "AddThread() returned a nullptr");
500 // This will notify this is a new thread and tell the system it is
502 thread_sp->SetStoppedBySignal(SIGSTOP);
503 ThreadWasCreated(*thread_sp);
504 SetCurrentThreadID(thread_sp->GetID());
507 // move the loop forward
512 if (tids_to_attach.size() > 0) {
514 // Let our process instance know the thread has stopped.
515 SetState(StateType::eStateStopped);
517 error.SetErrorToGenericError();
518 error.SetErrorString("No such process.");
525 Error NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) {
526 long ptrace_opts = 0;
528 // Have the child raise an event on exit. This is used to keep the child in
529 // limbo until it is destroyed.
530 ptrace_opts |= PTRACE_O_TRACEEXIT;
532 // Have the tracer trace threads which spawn in the inferior process.
533 // TODO: if we want to support tracing the inferiors' child, add the
534 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
535 ptrace_opts |= PTRACE_O_TRACECLONE;
537 // Have the tracer notify us before execve returns
538 // (needed to disable legacy SIGTRAP generation)
539 ptrace_opts |= PTRACE_O_TRACEEXEC;
541 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts);
544 static ExitType convert_pid_status_to_exit_type(int status) {
545 if (WIFEXITED(status))
546 return ExitType::eExitTypeExit;
547 else if (WIFSIGNALED(status))
548 return ExitType::eExitTypeSignal;
549 else if (WIFSTOPPED(status))
550 return ExitType::eExitTypeStop;
552 // We don't know what this is.
553 return ExitType::eExitTypeInvalid;
557 static int convert_pid_status_to_return_code(int status) {
558 if (WIFEXITED(status))
559 return WEXITSTATUS(status);
560 else if (WIFSIGNALED(status))
561 return WTERMSIG(status);
562 else if (WIFSTOPPED(status))
563 return WSTOPSIG(status);
565 // We don't know what this is.
566 return ExitType::eExitTypeInvalid;
570 // Handles all waitpid events from the inferior process.
571 void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited,
572 int signal, int status) {
573 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
575 // Certain activities differ based on whether the pid is the tid of the main
577 const bool is_main_thread = (pid == GetID());
579 // Handle when the thread exits.
583 "NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64
585 __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
587 // This is a thread that exited. Ensure we're not tracking it anymore.
588 const bool thread_found = StopTrackingThread(pid);
590 if (is_main_thread) {
591 // We only set the exit status and notify the delegate if we haven't
592 // already set the process
593 // state to an exited state. We normally should have received a SIGTRAP |
594 // (PTRACE_EVENT_EXIT << 8)
595 // for the main thread.
596 const bool already_notified = (GetState() == StateType::eStateExited) ||
597 (GetState() == StateType::eStateCrashed);
598 if (!already_notified) {
600 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
601 " handling main thread exit (%s), expected exit state "
602 "already set but state was %s instead, setting exit "
605 thread_found ? "stopped tracking thread metadata"
606 : "thread metadata not found",
607 StateAsCString(GetState()));
608 // The main thread exited. We're done monitoring. Report to delegate.
609 SetExitStatus(convert_pid_status_to_exit_type(status),
610 convert_pid_status_to_return_code(status), nullptr, true);
612 // Notify delegate that our process has exited.
613 SetState(StateType::eStateExited, true);
616 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
617 " main thread now exited (%s)",
619 thread_found ? "stopped tracking thread metadata"
620 : "thread metadata not found");
623 // Do we want to report to the delegate in this case? I think not. If
624 // this was an orderly
625 // thread exit, we would already have received the SIGTRAP |
626 // (PTRACE_EVENT_EXIT << 8) signal,
627 // and we would have done an all-stop then.
629 log->Printf("NativeProcessLinux::%s() tid = %" PRIu64
630 " handling non-main thread exit (%s)",
632 thread_found ? "stopped tracking thread metadata"
633 : "thread metadata not found");
639 const auto info_err = GetSignalInfo(pid, &info);
640 auto thread_sp = GetThreadByID(pid);
643 // Normally, the only situation when we cannot find the thread is if we have
645 // received a new thread notification. This is indicated by GetSignalInfo()
647 // si_code == SI_USER and si_pid == 0
649 log->Printf("NativeProcessLinux::%s received notification about an "
650 "unknown tid %" PRIu64 ".",
653 if (info_err.Fail()) {
655 log->Printf("NativeProcessLinux::%s (tid %" PRIu64
656 ") GetSignalInfo failed (%s). Ingoring this notification.",
657 __FUNCTION__, pid, info_err.AsCString());
661 if (log && (info.si_code != SI_USER || info.si_pid != 0))
662 log->Printf("NativeProcessLinux::%s (tid %" PRIu64
663 ") unexpected signal info (si_code: %d, si_pid: %d). "
664 "Treating as a new thread notification anyway.",
665 __FUNCTION__, pid, info.si_code, info.si_pid);
667 auto thread_sp = AddThread(pid);
668 // Resume the newly created thread.
669 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
670 ThreadWasCreated(*thread_sp);
674 // Get details on the signal raised.
675 if (info_err.Success()) {
676 // We have retrieved the signal info. Dispatch appropriately.
677 if (info.si_signo == SIGTRAP)
678 MonitorSIGTRAP(info, *thread_sp);
680 MonitorSignal(info, *thread_sp, exited);
682 if (info_err.GetError() == EINVAL) {
683 // This is a group stop reception for this tid.
684 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU
686 // tracee, triggering the group-stop mechanism. Normally receiving these
688 // the process, pending a SIGCONT. Simulating this state in a debugger is
690 // generally not needed (one use case is debugging background task being
692 // shell). For general use, it is sufficient to stop the process in a
694 // stop which happens before the group stop. This done by MonitorSignal
696 // correctly for all signals.
699 "NativeProcessLinux::%s received a group stop for pid %" PRIu64
700 " tid %" PRIu64 ". Transparent handling of group stops not "
701 "supported, resuming the thread.",
702 __FUNCTION__, GetID(), pid);
703 ResumeThread(*thread_sp, thread_sp->GetState(),
704 LLDB_INVALID_SIGNAL_NUMBER);
706 // ptrace(GETSIGINFO) failed (but not due to group-stop).
708 // A return value of ESRCH means the thread/process is no longer on the
710 // so it was killed somehow outside of our control. Either way, we can't
714 // Stop tracking the metadata for the thread since it's entirely off the
716 const bool thread_found = StopTrackingThread(pid);
720 "NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64
721 ", signal = %d, status = %d (%s, %s, %s)",
722 __FUNCTION__, info_err.AsCString(), pid, signal, status,
723 info_err.GetError() == ESRCH ? "thread/process killed"
725 is_main_thread ? "is main thread" : "is not main thread",
726 thread_found ? "thread metadata removed"
727 : "thread metadata not found");
729 if (is_main_thread) {
730 // Notify the delegate - our process is not available but appears to
731 // have been killed outside
732 // our control. Is eStateExited the right exit state in this case?
733 SetExitStatus(convert_pid_status_to_exit_type(status),
734 convert_pid_status_to_return_code(status), nullptr, true);
735 SetState(StateType::eStateExited, true);
737 // This thread was pulled out from underneath us. Anything to do here?
738 // Do we want to do an all stop?
740 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
741 " non-main thread exit occurred, didn't tell delegate "
742 "anything since thread disappeared out from underneath "
744 __FUNCTION__, GetID(), pid);
750 void NativeProcessLinux::WaitForNewThread(::pid_t tid) {
751 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
753 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
756 // We are already tracking the thread - we got the event on the new thread
758 // MonitorSignal) before this one. We are done.
762 // The thread is not tracked yet, let's wait for it to appear.
767 log->Printf("NativeProcessLinux::%s() received thread creation event for "
769 ". tid not tracked yet, waiting for thread to appear...",
771 wait_pid = waitpid(tid, &status, __WALL);
772 } while (wait_pid == -1 && errno == EINTR);
773 // Since we are waiting on a specific tid, this must be the creation event.
775 // some checks just in case.
776 if (wait_pid != tid) {
779 "NativeProcessLinux::%s() waiting for tid %" PRIu32
780 " failed. Assuming the thread has disappeared in the meantime",
782 // The only way I know of this could happen is if the whole process was
783 // SIGKILLed in the mean time. In any case, we can't do anything about that
787 if (WIFEXITED(status)) {
789 log->Printf("NativeProcessLinux::%s() waiting for tid %" PRIu32
790 " returned an 'exited' event. Not tracking the thread.",
792 // Also a very improbable event.
797 Error error = GetSignalInfo(tid, &info);
801 "NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
802 " failed. Assuming the thread has disappeared in the meantime.",
807 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) {
808 // We should be getting a thread creation signal here, but we received
810 // else. There isn't much we can do about it now, so we will just log that.
812 // thread is alive and we are receiving events from it, we shall pretend
815 log->Printf("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32
816 " received unexpected signal with code %d from pid %d.",
817 __FUNCTION__, tid, info.si_code, info.si_pid);
821 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
822 ": tracking new thread tid %" PRIu32,
823 __FUNCTION__, GetID(), tid);
825 new_thread_sp = AddThread(tid);
826 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
827 ThreadWasCreated(*new_thread_sp);
830 void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info,
831 NativeThreadLinux &thread) {
832 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
833 const bool is_main_thread = (thread.GetID() == GetID());
835 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
837 switch (info.si_code) {
838 // TODO: these two cases are required if we want to support tracing of the
839 // inferiors' children. We'd need this to debug a monitor.
840 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
841 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
843 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): {
844 // This is the notification on the parent thread which informs us of new
847 // We don't want to do anything with the parent thread so we just resume it.
849 // want to implement "break on thread creation" functionality, we would need
853 unsigned long event_message = 0;
854 if (GetEventMessage(thread.GetID(), &event_message).Fail()) {
856 log->Printf("NativeProcessLinux::%s() pid %" PRIu64
857 " received thread creation event but GetEventMessage "
858 "failed so we don't know the new tid",
859 __FUNCTION__, thread.GetID());
861 WaitForNewThread(event_message);
863 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
867 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): {
868 NativeThreadLinuxSP main_thread_sp;
870 log->Printf("NativeProcessLinux::%s() received exec event, code = %d",
871 __FUNCTION__, info.si_code ^ SIGTRAP);
873 // Exec clears any pending notifications.
874 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
876 // Remove all but the main thread here. Linux fork creates a new process
877 // which only copies the main thread.
879 log->Printf("NativeProcessLinux::%s exec received, stop tracking all but "
883 for (auto thread_sp : m_threads) {
884 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID();
885 if (is_main_thread) {
886 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
889 "NativeProcessLinux::%s found main thread with tid %" PRIu64
891 __FUNCTION__, main_thread_sp->GetID());
895 "NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64
897 __FUNCTION__, thread_sp->GetID());
903 if (main_thread_sp) {
904 m_threads.push_back(main_thread_sp);
905 SetCurrentThreadID(main_thread_sp->GetID());
906 main_thread_sp->SetStoppedByExec();
908 SetCurrentThreadID(LLDB_INVALID_THREAD_ID);
910 log->Printf("NativeProcessLinux::%s pid %" PRIu64
911 "no main thread found, discarded all threads, we're in a "
913 __FUNCTION__, GetID());
916 // Tell coordinator about about the "new" (since exec) stopped main thread.
917 ThreadWasCreated(*main_thread_sp);
919 // Let our delegate know we have just exec'd.
922 // If we have a main thread, indicate we are stopped.
923 assert(main_thread_sp && "exec called during ptraced process but no main "
924 "thread metadata tracked");
926 // Let the process know we're stopped.
927 StopRunningThreads(main_thread_sp->GetID());
932 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): {
933 // The inferior process or one of its threads is about to exit.
934 // We don't want to do anything with the thread so we just resume it. In
936 // want to implement "break on thread exit" functionality, we would need to
940 unsigned long data = 0;
941 if (GetEventMessage(thread.GetID(), &data).Fail())
945 log->Printf("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = "
946 "%lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
947 __FUNCTION__, data, WIFEXITED(data) ? "true" : "false",
948 WIFSIGNALED(data) ? "true" : "false", thread.GetID(),
949 is_main_thread ? "is main thread" : "not main thread");
952 if (is_main_thread) {
953 SetExitStatus(convert_pid_status_to_exit_type(data),
954 convert_pid_status_to_return_code(data), nullptr, true);
957 StateType state = thread.GetState();
958 if (!StateIsRunningState(state)) {
959 // Due to a kernel bug, we may sometimes get this stop after the inferior
961 // SIGKILL. This confuses our state tracking logic in ResumeThread(),
963 // we should not be receiving any ptrace events while the inferior is
965 // makes sure that the inferior is resumed and exits normally.
966 state = eStateRunning;
968 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
974 case TRAP_TRACE: // We receive this on single stepping.
975 case TRAP_HWBKPT: // We receive this on watchpoint hit
977 // If a watchpoint was hit, report it
979 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
980 wp_index, (uintptr_t)info.si_addr);
981 if (error.Fail() && log)
982 log->Printf("NativeProcessLinux::%s() "
983 "received error while checking for watchpoint hits, "
984 "pid = %" PRIu64 " error = %s",
985 __FUNCTION__, thread.GetID(), error.AsCString());
986 if (wp_index != LLDB_INVALID_INDEX32) {
987 MonitorWatchpoint(thread, wp_index);
991 // Otherwise, report step over
992 MonitorTrace(thread);
998 // For mips there is no special signal for watchpoint
999 // So we check for watchpoint in kernel trap
1001 // If a watchpoint was hit, report it
1003 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(
1004 wp_index, LLDB_INVALID_ADDRESS);
1005 if (error.Fail() && log)
1006 log->Printf("NativeProcessLinux::%s() "
1007 "received error while checking for watchpoint hits, "
1008 "pid = %" PRIu64 " error = %s",
1009 __FUNCTION__, thread.GetID(), error.AsCString());
1010 if (wp_index != LLDB_INVALID_INDEX32) {
1011 MonitorWatchpoint(thread, wp_index);
1018 MonitorBreakpoint(thread);
1022 case (SIGTRAP | 0x80):
1024 log->Printf("NativeProcessLinux::%s() received unknown SIGTRAP system "
1025 "call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming",
1026 __FUNCTION__, GetID(), thread.GetID());
1028 // Ignore these signals until we know more about them.
1029 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1033 assert(false && "Unexpected SIGTRAP code!");
1035 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64
1036 " received unhandled SIGTRAP code: 0x%d",
1037 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1042 void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) {
1043 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1045 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64
1046 " (single stepping)",
1047 __FUNCTION__, thread.GetID());
1049 // This thread is currently stopped.
1050 thread.SetStoppedByTrace();
1052 StopRunningThreads(thread.GetID());
1055 void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) {
1057 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1060 "NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1061 __FUNCTION__, thread.GetID());
1063 // Mark the thread as stopped at breakpoint.
1064 thread.SetStoppedByBreakpoint();
1065 Error error = FixupBreakpointPCAsNeeded(thread);
1068 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1069 __FUNCTION__, thread.GetID(), error.AsCString());
1071 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) !=
1072 m_threads_stepping_with_breakpoint.end())
1073 thread.SetStoppedByTrace();
1075 StopRunningThreads(thread.GetID());
1078 void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread,
1079 uint32_t wp_index) {
1081 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1083 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1084 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1085 __FUNCTION__, thread.GetID(), wp_index);
1087 // Mark the thread as stopped at watchpoint.
1088 // The address is at (lldb::addr_t)info->si_addr if we need it.
1089 thread.SetStoppedByWatchpoint(wp_index);
1091 // We need to tell all other running threads before we notify the delegate
1093 StopRunningThreads(thread.GetID());
1096 void NativeProcessLinux::MonitorSignal(const siginfo_t &info,
1097 NativeThreadLinux &thread, bool exited) {
1098 const int signo = info.si_signo;
1099 const bool is_from_llgs = info.si_pid == getpid();
1101 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1103 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1104 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1105 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1107 // IOW, user generated signals never generate what we consider to be a
1110 // Similarly, ACK signals generated by this monitor.
1112 // Handle the signal.
1113 if (info.si_code == SI_TKILL || info.si_code == SI_USER) {
1115 log->Printf("NativeProcessLinux::%s() received signal %s (%d) with code "
1116 "%s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1117 __FUNCTION__, Host::GetSignalAsCString(signo), signo,
1118 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1119 info.si_pid, is_from_llgs ? "from llgs" : "not from llgs",
1123 // Check for thread stop notification.
1124 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) {
1125 // This is a tgkill()-based stop.
1127 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1129 __FUNCTION__, GetID(), thread.GetID());
1131 // Check that we're not already marked with a stop reason.
1132 // Note this thread really shouldn't already be marked as stopped - if we
1133 // were, that would imply that
1134 // the kernel signaled us with the thread stopping which we handled and
1135 // marked as stopped,
1136 // and that, without an intervening resume, we received another stop. It is
1138 // that we are missing the marking of a run state somewhere if we find that
1140 // marked as stopped.
1141 const StateType thread_state = thread.GetState();
1142 if (!StateIsStoppedState(thread_state, false)) {
1143 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1144 // Generally, these are not important stops and we don't want to report
1146 // they are just used to stop other threads when one thread (the one with
1148 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in
1150 // case of an asynchronous Interrupt(), this *is* the real stop reason, so
1152 // leave the signal intact if this is the thread that was chosen as the
1153 // triggering thread.
1154 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) {
1155 if (m_pending_notification_tid == thread.GetID())
1156 thread.SetStoppedBySignal(SIGSTOP, &info);
1158 thread.SetStoppedWithNoReason();
1160 SetCurrentThreadID(thread.GetID());
1161 SignalIfAllThreadsStopped();
1163 // We can end up here if stop was initiated by LLGS but by this time a
1164 // thread stop has occurred - maybe initiated by another event.
1165 Error error = ResumeThread(thread, thread.GetState(), 0);
1166 if (error.Fail() && log) {
1168 "NativeProcessLinux::%s failed to resume thread tid %" PRIu64
1170 __FUNCTION__, thread.GetID(), error.AsCString());
1175 // Retrieve the signal name if the thread was stopped by a signal.
1177 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1178 const char *signal_name = stopped_by_signal
1179 ? Host::GetSignalAsCString(stop_signo)
1180 : "<not stopped by signal>";
1182 signal_name = "<no-signal-name>";
1184 log->Printf("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64
1185 ", thread was already marked as a stopped state (state=%s, "
1186 "signal=%d (%s)), leaving stop signal as is",
1187 __FUNCTION__, GetID(), thread.GetID(),
1188 StateAsCString(thread_state), stop_signo, signal_name);
1190 SignalIfAllThreadsStopped();
1198 log->Printf("NativeProcessLinux::%s() received signal %s", __FUNCTION__,
1199 Host::GetSignalAsCString(signo));
1201 // This thread is stopped.
1202 thread.SetStoppedBySignal(signo, &info);
1204 // Send a stop to the debugger after we get all other threads to stop.
1205 StopRunningThreads(thread.GetID());
1210 struct EmulatorBaton {
1211 NativeProcessLinux *m_process;
1212 NativeRegisterContext *m_reg_context;
1214 // eRegisterKindDWARF -> RegsiterValue
1215 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1217 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context)
1218 : m_process(process), m_reg_context(reg_context) {}
1221 } // anonymous namespace
1223 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
1224 const EmulateInstruction::Context &context,
1225 lldb::addr_t addr, void *dst, size_t length) {
1226 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1229 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1233 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
1234 const RegisterInfo *reg_info,
1235 RegisterValue ®_value) {
1236 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1238 auto it = emulator_baton->m_register_values.find(
1239 reg_info->kinds[eRegisterKindDWARF]);
1240 if (it != emulator_baton->m_register_values.end()) {
1241 reg_value = it->second;
1245 // The emulator only fill in the dwarf regsiter numbers (and in some case
1246 // the generic register numbers). Get the full register info from the
1247 // register context based on the dwarf register numbers.
1248 const RegisterInfo *full_reg_info =
1249 emulator_baton->m_reg_context->GetRegisterInfo(
1250 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1253 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1254 if (error.Success())
1260 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
1261 const EmulateInstruction::Context &context,
1262 const RegisterInfo *reg_info,
1263 const RegisterValue ®_value) {
1264 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
1265 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
1270 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
1271 const EmulateInstruction::Context &context,
1272 lldb::addr_t addr, const void *dst,
1277 static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) {
1278 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo(
1279 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1280 return regsiter_context->ReadRegisterAsUnsigned(flags_info,
1281 LLDB_INVALID_ADDRESS);
1284 Error NativeProcessLinux::SetupSoftwareSingleStepping(
1285 NativeThreadLinux &thread) {
1287 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1289 std::unique_ptr<EmulateInstruction> emulator_ap(
1290 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying,
1293 if (emulator_ap == nullptr)
1294 return Error("Instruction emulator not found!");
1296 EmulatorBaton baton(this, register_context_sp.get());
1297 emulator_ap->SetBaton(&baton);
1298 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1299 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1300 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1301 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1303 if (!emulator_ap->ReadInstruction())
1304 return Error("Read instruction failed!");
1306 bool emulation_result =
1307 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1309 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1310 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1311 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo(
1312 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1315 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1317 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1319 lldb::addr_t next_pc;
1320 lldb::addr_t next_flags;
1321 if (emulation_result) {
1322 assert(pc_it != baton.m_register_values.end() &&
1323 "Emulation was successfull but PC wasn't updated");
1324 next_pc = pc_it->second.GetAsUInt64();
1326 if (flags_it != baton.m_register_values.end())
1327 next_flags = flags_it->second.GetAsUInt64();
1329 next_flags = ReadFlags(register_context_sp.get());
1330 } else if (pc_it == baton.m_register_values.end()) {
1331 // Emulate instruction failed and it haven't changed PC. Advance PC
1332 // with the size of the current opcode because the emulation of all
1333 // PC modifying instruction should be successful. The failure most
1334 // likely caused by a not supported instruction which don't modify PC.
1336 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1337 next_flags = ReadFlags(register_context_sp.get());
1339 // The instruction emulation failed after it modified the PC. It is an
1340 // unknown error where we can't continue because the next instruction is
1341 // modifying the PC but we don't know how.
1342 return Error("Instruction emulation failed unexpectedly.");
1345 if (m_arch.GetMachine() == llvm::Triple::arm) {
1346 if (next_flags & 0x20) {
1348 error = SetSoftwareBreakpoint(next_pc, 2);
1351 error = SetSoftwareBreakpoint(next_pc, 4);
1353 } else if (m_arch.GetMachine() == llvm::Triple::mips64 ||
1354 m_arch.GetMachine() == llvm::Triple::mips64el ||
1355 m_arch.GetMachine() == llvm::Triple::mips ||
1356 m_arch.GetMachine() == llvm::Triple::mipsel)
1357 error = SetSoftwareBreakpoint(next_pc, 4);
1359 // No size hint is given for the next breakpoint
1360 error = SetSoftwareBreakpoint(next_pc, 0);
1363 // If setting the breakpoint fails because next_pc is out of
1364 // the address space, ignore it and let the debugee segfault.
1365 if (error.GetError() == EIO || error.GetError() == EFAULT) {
1367 } else if (error.Fail())
1370 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1375 bool NativeProcessLinux::SupportHardwareSingleStepping() const {
1376 if (m_arch.GetMachine() == llvm::Triple::arm ||
1377 m_arch.GetMachine() == llvm::Triple::mips64 ||
1378 m_arch.GetMachine() == llvm::Triple::mips64el ||
1379 m_arch.GetMachine() == llvm::Triple::mips ||
1380 m_arch.GetMachine() == llvm::Triple::mipsel)
1385 Error NativeProcessLinux::Resume(const ResumeActionList &resume_actions) {
1386 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1388 log->Printf("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__,
1391 bool software_single_step = !SupportHardwareSingleStepping();
1393 if (software_single_step) {
1394 for (auto thread_sp : m_threads) {
1395 assert(thread_sp && "thread list should not contain NULL threads");
1397 const ResumeAction *const action =
1398 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1399 if (action == nullptr)
1402 if (action->state == eStateStepping) {
1403 Error error = SetupSoftwareSingleStepping(
1404 static_cast<NativeThreadLinux &>(*thread_sp));
1411 for (auto thread_sp : m_threads) {
1412 assert(thread_sp && "thread list should not contain NULL threads");
1414 const ResumeAction *const action =
1415 resume_actions.GetActionForThread(thread_sp->GetID(), true);
1417 if (action == nullptr) {
1420 "NativeProcessLinux::%s no action specified for pid %" PRIu64
1422 __FUNCTION__, GetID(), thread_sp->GetID());
1427 log->Printf("NativeProcessLinux::%s processing resume action state %s "
1428 "for pid %" PRIu64 " tid %" PRIu64,
1429 __FUNCTION__, StateAsCString(action->state), GetID(),
1430 thread_sp->GetID());
1433 switch (action->state) {
1435 case eStateStepping: {
1436 // Run the thread, possibly feeding it the signal.
1437 const int signo = action->signal;
1438 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state,
1443 case eStateSuspended:
1445 lldbassert(0 && "Unexpected state");
1448 return Error("NativeProcessLinux::%s (): unexpected state %s specified "
1449 "for pid %" PRIu64 ", tid %" PRIu64,
1450 __FUNCTION__, StateAsCString(action->state), GetID(),
1451 thread_sp->GetID());
1458 Error NativeProcessLinux::Halt() {
1461 if (kill(GetID(), SIGSTOP) != 0)
1462 error.SetErrorToErrno();
1467 Error NativeProcessLinux::Detach() {
1470 // Stop monitoring the inferior.
1471 m_sigchld_handle.reset();
1473 // Tell ptrace to detach from the process.
1474 if (GetID() == LLDB_INVALID_PROCESS_ID)
1477 for (auto thread_sp : m_threads) {
1478 Error e = Detach(thread_sp->GetID());
1481 e; // Save the error, but still attempt to detach from other threads.
1487 Error NativeProcessLinux::Signal(int signo) {
1490 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1493 "NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1494 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1496 if (kill(GetID(), signo))
1497 error.SetErrorToErrno();
1502 Error NativeProcessLinux::Interrupt() {
1503 // Pick a running thread (or if none, a not-dead stopped thread) as
1504 // the chosen thread that will be the stop-reason thread.
1505 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1507 NativeThreadProtocolSP running_thread_sp;
1508 NativeThreadProtocolSP stopped_thread_sp;
1512 "NativeProcessLinux::%s selecting running thread for interrupt target",
1515 for (auto thread_sp : m_threads) {
1516 // The thread shouldn't be null but lets just cover that here.
1520 // If we have a running or stepping thread, we'll call that the
1521 // target of the interrupt.
1522 const auto thread_state = thread_sp->GetState();
1523 if (thread_state == eStateRunning || thread_state == eStateStepping) {
1524 running_thread_sp = thread_sp;
1526 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) {
1527 // Remember the first non-dead stopped thread. We'll use that as a backup
1528 // if there are no running threads.
1529 stopped_thread_sp = thread_sp;
1533 if (!running_thread_sp && !stopped_thread_sp) {
1534 Error error("found no running/stepping or live stopped threads as target "
1537 log->Printf("NativeProcessLinux::%s skipping due to error: %s",
1538 __FUNCTION__, error.AsCString());
1543 NativeThreadProtocolSP deferred_signal_thread_sp =
1544 running_thread_sp ? running_thread_sp : stopped_thread_sp;
1547 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64
1548 " chosen for interrupt target",
1549 __FUNCTION__, GetID(),
1550 running_thread_sp ? "running" : "stopped",
1551 deferred_signal_thread_sp->GetID());
1553 StopRunningThreads(deferred_signal_thread_sp->GetID());
1558 Error NativeProcessLinux::Kill() {
1559 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1561 log->Printf("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__,
1567 case StateType::eStateInvalid:
1568 case StateType::eStateExited:
1569 case StateType::eStateCrashed:
1570 case StateType::eStateDetached:
1571 case StateType::eStateUnloaded:
1572 // Nothing to do - the process is already dead.
1574 log->Printf("NativeProcessLinux::%s ignored for PID %" PRIu64
1575 " due to current state: %s",
1576 __FUNCTION__, GetID(), StateAsCString(m_state));
1579 case StateType::eStateConnected:
1580 case StateType::eStateAttaching:
1581 case StateType::eStateLaunching:
1582 case StateType::eStateStopped:
1583 case StateType::eStateRunning:
1584 case StateType::eStateStepping:
1585 case StateType::eStateSuspended:
1586 // We can try to kill a process in these states.
1590 if (kill(GetID(), SIGKILL) != 0) {
1591 error.SetErrorToErrno();
1599 ParseMemoryRegionInfoFromProcMapsLine(const std::string &maps_line,
1600 MemoryRegionInfo &memory_region_info) {
1601 memory_region_info.Clear();
1603 StringExtractor line_extractor(maps_line.c_str());
1605 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode
1607 // perms: rwxp (letter is present if set, '-' if not, final character is
1608 // p=private, s=shared).
1610 // Parse out the starting address
1611 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0);
1613 // Parse out hyphen separating start and end address from range.
1614 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-'))
1616 "malformed /proc/{pid}/maps entry, missing dash between address range");
1618 // Parse out the ending address
1619 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address);
1621 // Parse out the space after the address.
1622 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' '))
1623 return Error("malformed /proc/{pid}/maps entry, missing space after range");
1626 memory_region_info.GetRange().SetRangeBase(start_address);
1627 memory_region_info.GetRange().SetRangeEnd(end_address);
1629 // Any memory region in /proc/{pid}/maps is by definition mapped into the
1631 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1633 // Parse out each permission entry.
1634 if (line_extractor.GetBytesLeft() < 4)
1635 return Error("malformed /proc/{pid}/maps entry, missing some portion of "
1638 // Handle read permission.
1639 const char read_perm_char = line_extractor.GetChar();
1640 if (read_perm_char == 'r')
1641 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
1642 else if (read_perm_char == '-')
1643 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1645 return Error("unexpected /proc/{pid}/maps read permission char");
1647 // Handle write permission.
1648 const char write_perm_char = line_extractor.GetChar();
1649 if (write_perm_char == 'w')
1650 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
1651 else if (write_perm_char == '-')
1652 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1654 return Error("unexpected /proc/{pid}/maps write permission char");
1656 // Handle execute permission.
1657 const char exec_perm_char = line_extractor.GetChar();
1658 if (exec_perm_char == 'x')
1659 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
1660 else if (exec_perm_char == '-')
1661 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1663 return Error("unexpected /proc/{pid}/maps exec permission char");
1665 line_extractor.GetChar(); // Read the private bit
1666 line_extractor.SkipSpaces(); // Skip the separator
1667 line_extractor.GetHexMaxU64(false, 0); // Read the offset
1668 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1669 line_extractor.GetChar(); // Read the device id separator
1670 line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1671 line_extractor.SkipSpaces(); // Skip the separator
1672 line_extractor.GetU64(0, 10); // Read the inode number
1674 line_extractor.SkipSpaces();
1675 const char *name = line_extractor.Peek();
1677 memory_region_info.SetName(name);
1682 Error NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr,
1683 MemoryRegionInfo &range_info) {
1684 // FIXME review that the final memory region returned extends to the end of
1685 // the virtual address space,
1686 // with no perms if it is not mapped.
1688 // Use an approach that reads memory regions from /proc/{pid}/maps.
1689 // Assume proc maps entries are in ascending order.
1690 // FIXME assert if we find differently.
1692 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1695 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
1697 error.SetErrorString("unsupported");
1701 // If our cache is empty, pull the latest. There should always be at least
1702 // one memory region
1703 // if memory region handling is supported.
1704 if (m_mem_region_cache.empty()) {
1705 error = ProcFileReader::ProcessLineByLine(
1706 GetID(), "maps", [&](const std::string &line) -> bool {
1707 MemoryRegionInfo info;
1708 const Error parse_error =
1709 ParseMemoryRegionInfoFromProcMapsLine(line, info);
1710 if (parse_error.Success()) {
1711 m_mem_region_cache.push_back(info);
1715 log->Printf("NativeProcessLinux::%s failed to parse proc maps "
1717 __FUNCTION__, line.c_str(), error.AsCString());
1722 // If we had an error, we'll mark unsupported.
1724 m_supports_mem_region = LazyBool::eLazyBoolNo;
1726 } else if (m_mem_region_cache.empty()) {
1727 // No entries after attempting to read them. This shouldn't happen if
1729 // is supported. Assume we don't support map entries via procfs.
1731 log->Printf("NativeProcessLinux::%s failed to find any procfs maps "
1732 "entries, assuming no support for memory region metadata "
1735 m_supports_mem_region = LazyBool::eLazyBoolNo;
1736 error.SetErrorString("not supported");
1741 log->Printf("NativeProcessLinux::%s read %" PRIu64
1742 " memory region entries from /proc/%" PRIu64 "/maps",
1744 static_cast<uint64_t>(m_mem_region_cache.size()), GetID());
1746 // We support memory retrieval, remember that.
1747 m_supports_mem_region = LazyBool::eLazyBoolYes;
1750 log->Printf("NativeProcessLinux::%s reusing %" PRIu64
1751 " cached memory region entries",
1753 static_cast<uint64_t>(m_mem_region_cache.size()));
1756 lldb::addr_t prev_base_address = 0;
1758 // FIXME start by finding the last region that is <= target address using
1759 // binary search. Data is sorted.
1760 // There can be a ton of regions on pthreads apps with lots of threads.
1761 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
1763 MemoryRegionInfo &proc_entry_info = *it;
1765 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1766 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
1767 "descending /proc/pid/maps entries detected, unexpected");
1768 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
1770 // If the target address comes before this entry, indicate distance to next
1772 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
1773 range_info.GetRange().SetRangeBase(load_addr);
1774 range_info.GetRange().SetByteSize(
1775 proc_entry_info.GetRange().GetRangeBase() - load_addr);
1776 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1777 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1778 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1779 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1782 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
1783 // The target address is within the memory region we're processing here.
1784 range_info = proc_entry_info;
1788 // The target memory address comes somewhere after the region we just
1792 // If we made it here, we didn't find an entry that contained the given
1793 // address. Return the
1794 // load_addr as start and the amount of bytes betwwen load address and the end
1797 range_info.GetRange().SetRangeBase(load_addr);
1798 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
1799 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
1800 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
1801 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
1802 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1806 void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) {
1807 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1809 log->Printf("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called",
1810 __FUNCTION__, newBumpId);
1813 log->Printf("NativeProcessLinux::%s clearing %" PRIu64
1814 " entries from the cache",
1815 __FUNCTION__, static_cast<uint64_t>(m_mem_region_cache.size()));
1816 m_mem_region_cache.clear();
1819 Error NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions,
1820 lldb::addr_t &addr) {
1821 // FIXME implementing this requires the equivalent of
1822 // InferiorCallPOSIX::InferiorCallMmap, which depends on
1823 // functional ThreadPlans working with Native*Protocol.
1825 return Error("not implemented yet");
1827 addr = LLDB_INVALID_ADDRESS;
1830 if (permissions & lldb::ePermissionsReadable)
1831 prot |= eMmapProtRead;
1832 if (permissions & lldb::ePermissionsWritable)
1833 prot |= eMmapProtWrite;
1834 if (permissions & lldb::ePermissionsExecutable)
1835 prot |= eMmapProtExec;
1837 // TODO implement this directly in NativeProcessLinux
1838 // (and lift to NativeProcessPOSIX if/when that class is
1840 if (InferiorCallMmap(this, addr, 0, size, prot,
1841 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1842 m_addr_to_mmap_size[addr] = size;
1845 addr = LLDB_INVALID_ADDRESS;
1846 return Error("unable to allocate %" PRIu64
1847 " bytes of memory with permissions %s",
1848 size, GetPermissionsAsCString(permissions));
1853 Error NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) {
1854 // FIXME see comments in AllocateMemory - required lower-level
1855 // bits not in place yet (ThreadPlans)
1856 return Error("not implemented");
1859 lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() {
1860 // punt on this for now
1861 return LLDB_INVALID_ADDRESS;
1864 size_t NativeProcessLinux::UpdateThreads() {
1865 // The NativeProcessLinux monitoring threads are always up to date
1866 // with respect to thread state and they keep the thread list
1867 // populated properly. All this method needs to do is return the
1869 return m_threads.size();
1872 bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const {
1877 Error NativeProcessLinux::GetSoftwareBreakpointPCOffset(
1878 uint32_t &actual_opcode_size) {
1879 // FIXME put this behind a breakpoint protocol class that can be
1880 // set per architecture. Need ARM, MIPS support here.
1881 static const uint8_t g_i386_opcode[] = {0xCC};
1882 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1884 switch (m_arch.GetMachine()) {
1885 case llvm::Triple::x86:
1886 case llvm::Triple::x86_64:
1887 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
1890 case llvm::Triple::systemz:
1891 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode));
1894 case llvm::Triple::arm:
1895 case llvm::Triple::aarch64:
1896 case llvm::Triple::mips64:
1897 case llvm::Triple::mips64el:
1898 case llvm::Triple::mips:
1899 case llvm::Triple::mipsel:
1900 // On these architectures the PC don't get updated for breakpoint hits
1901 actual_opcode_size = 0;
1905 assert(false && "CPU type not supported!");
1906 return Error("CPU type not supported");
1910 Error NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size,
1913 return Error("NativeProcessLinux does not support hardware breakpoints");
1915 return SetSoftwareBreakpoint(addr, size);
1918 Error NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(
1919 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
1920 const uint8_t *&trap_opcode_bytes) {
1921 // FIXME put this behind a breakpoint protocol class that can be set per
1922 // architecture. Need MIPS support here.
1923 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1924 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1925 // linux kernel does otherwise.
1926 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1927 static const uint8_t g_i386_opcode[] = {0xCC};
1928 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1929 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1930 static const uint8_t g_s390x_opcode[] = {0x00, 0x01};
1931 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1933 switch (m_arch.GetMachine()) {
1934 case llvm::Triple::aarch64:
1935 trap_opcode_bytes = g_aarch64_opcode;
1936 actual_opcode_size = sizeof(g_aarch64_opcode);
1939 case llvm::Triple::arm:
1940 switch (trap_opcode_size_hint) {
1942 trap_opcode_bytes = g_thumb_breakpoint_opcode;
1943 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1946 trap_opcode_bytes = g_arm_breakpoint_opcode;
1947 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
1950 assert(false && "Unrecognised trap opcode size hint!");
1951 return Error("Unrecognised trap opcode size hint!");
1954 case llvm::Triple::x86:
1955 case llvm::Triple::x86_64:
1956 trap_opcode_bytes = g_i386_opcode;
1957 actual_opcode_size = sizeof(g_i386_opcode);
1960 case llvm::Triple::mips:
1961 case llvm::Triple::mips64:
1962 trap_opcode_bytes = g_mips64_opcode;
1963 actual_opcode_size = sizeof(g_mips64_opcode);
1966 case llvm::Triple::mipsel:
1967 case llvm::Triple::mips64el:
1968 trap_opcode_bytes = g_mips64el_opcode;
1969 actual_opcode_size = sizeof(g_mips64el_opcode);
1972 case llvm::Triple::systemz:
1973 trap_opcode_bytes = g_s390x_opcode;
1974 actual_opcode_size = sizeof(g_s390x_opcode);
1978 assert(false && "CPU type not supported!");
1979 return Error("CPU type not supported");
1984 ProcessMessage::CrashReason
1985 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
1987 ProcessMessage::CrashReason reason;
1988 assert(info->si_signo == SIGSEGV);
1990 reason = ProcessMessage::eInvalidCrashReason;
1992 switch (info->si_code)
1995 assert(false && "unexpected si_code for SIGSEGV");
1998 // Linux will occasionally send spurious SI_KERNEL codes.
1999 // (this is poorly documented in sigaction)
2000 // One way to get this is via unaligned SIMD loads.
2001 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2004 reason = ProcessMessage::eInvalidAddress;
2007 reason = ProcessMessage::ePrivilegedAddress;
2016 ProcessMessage::CrashReason
2017 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2019 ProcessMessage::CrashReason reason;
2020 assert(info->si_signo == SIGILL);
2022 reason = ProcessMessage::eInvalidCrashReason;
2024 switch (info->si_code)
2027 assert(false && "unexpected si_code for SIGILL");
2030 reason = ProcessMessage::eIllegalOpcode;
2033 reason = ProcessMessage::eIllegalOperand;
2036 reason = ProcessMessage::eIllegalAddressingMode;
2039 reason = ProcessMessage::eIllegalTrap;
2042 reason = ProcessMessage::ePrivilegedOpcode;
2045 reason = ProcessMessage::ePrivilegedRegister;
2048 reason = ProcessMessage::eCoprocessorError;
2051 reason = ProcessMessage::eInternalStackError;
2060 ProcessMessage::CrashReason
2061 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2063 ProcessMessage::CrashReason reason;
2064 assert(info->si_signo == SIGFPE);
2066 reason = ProcessMessage::eInvalidCrashReason;
2068 switch (info->si_code)
2071 assert(false && "unexpected si_code for SIGFPE");
2074 reason = ProcessMessage::eIntegerDivideByZero;
2077 reason = ProcessMessage::eIntegerOverflow;
2080 reason = ProcessMessage::eFloatDivideByZero;
2083 reason = ProcessMessage::eFloatOverflow;
2086 reason = ProcessMessage::eFloatUnderflow;
2089 reason = ProcessMessage::eFloatInexactResult;
2092 reason = ProcessMessage::eFloatInvalidOperation;
2095 reason = ProcessMessage::eFloatSubscriptRange;
2104 ProcessMessage::CrashReason
2105 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2107 ProcessMessage::CrashReason reason;
2108 assert(info->si_signo == SIGBUS);
2110 reason = ProcessMessage::eInvalidCrashReason;
2112 switch (info->si_code)
2115 assert(false && "unexpected si_code for SIGBUS");
2118 reason = ProcessMessage::eIllegalAlignment;
2121 reason = ProcessMessage::eIllegalAddress;
2124 reason = ProcessMessage::eHardwareError;
2132 Error NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size,
2133 size_t &bytes_read) {
2134 if (ProcessVmReadvSupported()) {
2135 // The process_vm_readv path is about 50 times faster than ptrace api. We
2137 // this syscall if it is supported.
2139 const ::pid_t pid = GetID();
2141 struct iovec local_iov, remote_iov;
2142 local_iov.iov_base = buf;
2143 local_iov.iov_len = size;
2144 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2145 remote_iov.iov_len = size;
2147 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2148 const bool success = bytes_read == size;
2150 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2152 log->Printf("NativeProcessLinux::%s using process_vm_readv to read %zd "
2153 "bytes from inferior address 0x%" PRIx64 ": %s",
2154 __FUNCTION__, size, addr,
2155 success ? "Success" : strerror(errno));
2160 // the call failed for some reason, let's retry the read using ptrace
2164 unsigned char *dst = static_cast<unsigned char *>(buf);
2168 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
2170 ProcessPOSIXLog::IncNestLevel();
2171 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2172 log->GetMask().Test(POSIX_LOG_MEMORY))
2173 log->Printf("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__,
2174 (void *)addr, buf, size);
2176 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) {
2177 Error error = NativeProcessLinux::PtraceWrapper(
2178 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data);
2181 ProcessPOSIXLog::DecNestLevel();
2185 remainder = size - bytes_read;
2186 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2188 // Copy the data into our buffer
2189 memcpy(dst, &data, remainder);
2191 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2192 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2193 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2194 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) {
2195 uintptr_t print_dst = 0;
2196 // Format bytes from data by moving into print_dst for log output
2197 for (unsigned i = 0; i < remainder; ++i)
2198 print_dst |= (((data >> i * 8) & 0xFF) << i * 8);
2199 log->Printf("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64
2201 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
2203 addr += k_ptrace_word_size;
2204 dst += k_ptrace_word_size;
2208 ProcessPOSIXLog::DecNestLevel();
2212 Error NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
2214 size_t &bytes_read) {
2215 Error error = ReadMemory(addr, buf, size, bytes_read);
2218 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2221 Error NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf,
2222 size_t size, size_t &bytes_written) {
2223 const unsigned char *src = static_cast<const unsigned char *>(buf);
2227 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_ALL));
2229 ProcessPOSIXLog::IncNestLevel();
2230 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2231 log->GetMask().Test(POSIX_LOG_MEMORY))
2232 log->Printf("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__,
2235 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) {
2236 remainder = size - bytes_written;
2237 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2239 if (remainder == k_ptrace_word_size) {
2240 unsigned long data = 0;
2241 memcpy(&data, src, k_ptrace_word_size);
2243 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2244 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2245 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2246 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2247 log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2248 (void *)addr, *(const unsigned long *)src, data);
2250 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(),
2251 (void *)addr, (void *)data);
2254 ProcessPOSIXLog::DecNestLevel();
2258 unsigned char buff[8];
2260 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2263 ProcessPOSIXLog::DecNestLevel();
2267 memcpy(buff, src, remainder);
2269 size_t bytes_written_rec;
2270 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2273 ProcessPOSIXLog::DecNestLevel();
2277 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2278 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2279 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2280 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2281 log->Printf("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2282 (void *)addr, *(const unsigned long *)src,
2283 *(unsigned long *)buff);
2286 addr += k_ptrace_word_size;
2287 src += k_ptrace_word_size;
2290 ProcessPOSIXLog::DecNestLevel();
2294 Error NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) {
2295 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2298 Error NativeProcessLinux::GetEventMessage(lldb::tid_t tid,
2299 unsigned long *message) {
2300 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2303 Error NativeProcessLinux::Detach(lldb::tid_t tid) {
2304 if (tid == LLDB_INVALID_THREAD_ID)
2307 return PtraceWrapper(PTRACE_DETACH, tid);
2310 bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) {
2311 for (auto thread_sp : m_threads) {
2312 assert(thread_sp && "thread list should not contain NULL threads");
2313 if (thread_sp->GetID() == thread_id) {
2314 // We have this thread.
2319 // We don't have this thread.
2323 bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) {
2324 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2327 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2332 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
2333 if (*it && ((*it)->GetID() == thread_id)) {
2334 m_threads.erase(it);
2340 SignalIfAllThreadsStopped();
2345 NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) {
2346 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD));
2349 log->Printf("NativeProcessLinux::%s pid %" PRIu64
2350 " adding thread with tid %" PRIu64,
2351 __FUNCTION__, GetID(), thread_id);
2354 assert(!HasThreadNoLock(thread_id) &&
2355 "attempted to add a thread by id that already exists");
2357 // If this is the first thread, save it as the current thread
2358 if (m_threads.empty())
2359 SetCurrentThreadID(thread_id);
2361 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2362 m_threads.push_back(thread_sp);
2366 Error NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) {
2367 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2371 // Find out the size of a breakpoint (might depend on where we are in the
2373 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2375 error.SetErrorString("cannot get a NativeRegisterContext for the thread");
2377 log->Printf("NativeProcessLinux::%s failed: %s", __FUNCTION__,
2382 uint32_t breakpoint_size = 0;
2383 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2386 log->Printf("NativeProcessLinux::%s GetBreakpointSize() failed: %s",
2387 __FUNCTION__, error.AsCString());
2391 log->Printf("NativeProcessLinux::%s breakpoint size: %" PRIu32,
2392 __FUNCTION__, breakpoint_size);
2395 // First try probing for a breakpoint at a software breakpoint location: PC -
2397 const lldb::addr_t initial_pc_addr =
2398 context_sp->GetPCfromBreakpointLocation();
2399 lldb::addr_t breakpoint_addr = initial_pc_addr;
2400 if (breakpoint_size > 0) {
2401 // Do not allow breakpoint probe to wrap around.
2402 if (breakpoint_addr >= breakpoint_size)
2403 breakpoint_addr -= breakpoint_size;
2406 // Check if we stopped because of a breakpoint.
2407 NativeBreakpointSP breakpoint_sp;
2408 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
2409 if (!error.Success() || !breakpoint_sp) {
2410 // We didn't find one at a software probe location. Nothing to do.
2413 "NativeProcessLinux::%s pid %" PRIu64
2414 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64,
2415 __FUNCTION__, GetID(), breakpoint_addr);
2419 // If the breakpoint is not a software breakpoint, nothing to do.
2420 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
2422 log->Printf("NativeProcessLinux::%s pid %" PRIu64
2423 " breakpoint found at 0x%" PRIx64
2424 ", not software, nothing to adjust",
2425 __FUNCTION__, GetID(), breakpoint_addr);
2430 // We have a software breakpoint and need to adjust the PC.
2434 if (breakpoint_size == 0) {
2435 // Nothing to do! How did we get here?
2438 "NativeProcessLinux::%s pid %" PRIu64
2439 " breakpoint found at 0x%" PRIx64
2440 ", it is software, but the size is zero, nothing to do (unexpected)",
2441 __FUNCTION__, GetID(), breakpoint_addr);
2445 // Change the program counter.
2447 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2448 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64,
2449 __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr,
2452 error = context_sp->SetPC(breakpoint_addr);
2455 log->Printf("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64
2456 ": failed to set PC: %s",
2457 __FUNCTION__, GetID(), thread.GetID(), error.AsCString());
2464 Error NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path,
2465 FileSpec &file_spec) {
2466 FileSpec module_file_spec(module_path, true);
2470 ProcFileReader::ProcessLineByLine(
2471 GetID(), "maps", [&](const std::string &line) {
2472 SmallVector<StringRef, 16> columns;
2473 StringRef(line).split(columns, " ", -1, false);
2474 if (columns.size() < 6)
2475 return true; // continue searching
2477 FileSpec this_file_spec(columns[5].str(), false);
2478 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2479 return true; // continue searching
2481 file_spec = this_file_spec;
2483 return false; // we are done
2487 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2488 module_file_spec.GetFilename().AsCString(), GetID());
2493 Error NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name,
2494 lldb::addr_t &load_addr) {
2495 load_addr = LLDB_INVALID_ADDRESS;
2496 Error error = ProcFileReader::ProcessLineByLine(
2497 GetID(), "maps", [&](const std::string &line) -> bool {
2498 StringRef maps_row(line);
2500 SmallVector<StringRef, 16> maps_columns;
2501 maps_row.split(maps_columns, StringRef(" "), -1, false);
2503 if (maps_columns.size() < 6) {
2504 // Return true to continue reading the proc file
2508 if (maps_columns[5] == file_name) {
2509 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2510 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2512 // Return false to stop reading the proc file further
2516 // Return true to continue reading the proc file
2522 NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) {
2523 return std::static_pointer_cast<NativeThreadLinux>(
2524 NativeProcessProtocol::GetThreadByID(tid));
2527 Error NativeProcessLinux::ResumeThread(NativeThreadLinux &thread,
2528 lldb::StateType state, int signo) {
2529 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2532 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2535 // Before we do the resume below, first check if we have a pending
2536 // stop notification that is currently waiting for
2537 // all threads to stop. This is potentially a buggy situation since
2538 // we're ostensibly waiting for threads to stop before we send out the
2539 // pending notification, and here we are resuming one before we send
2540 // out the pending stop notification.
2541 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log) {
2542 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64
2543 " per explicit request but we have a pending stop notification "
2544 "(tid %" PRIu64 ") that is actively waiting for this thread to "
2545 "stop. Valid sequence of events?",
2546 __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2549 // Request a resume. We expect this to be synchronous and the system
2550 // to reflect it is running after this completes.
2552 case eStateRunning: {
2553 const auto resume_result = thread.Resume(signo);
2554 if (resume_result.Success())
2555 SetState(eStateRunning, true);
2556 return resume_result;
2558 case eStateStepping: {
2559 const auto step_result = thread.SingleStep(signo);
2560 if (step_result.Success())
2561 SetState(eStateRunning, true);
2566 log->Printf("NativeProcessLinux::%s Unhandled state %s.", __FUNCTION__,
2567 StateAsCString(state));
2568 llvm_unreachable("Unhandled state for resume");
2572 //===----------------------------------------------------------------------===//
2574 void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) {
2575 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2578 log->Printf("NativeProcessLinux::%s about to process event: "
2579 "(triggering_tid: %" PRIu64 ")",
2580 __FUNCTION__, triggering_tid);
2583 m_pending_notification_tid = triggering_tid;
2585 // Request a stop for all the thread stops that need to be stopped
2586 // and are not already known to be stopped.
2587 for (const auto &thread_sp : m_threads) {
2588 if (StateIsRunningState(thread_sp->GetState()))
2589 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2592 SignalIfAllThreadsStopped();
2595 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2599 void NativeProcessLinux::SignalIfAllThreadsStopped() {
2600 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2601 return; // No pending notification. Nothing to do.
2603 for (const auto &thread_sp : m_threads) {
2604 if (StateIsRunningState(thread_sp->GetState()))
2605 return; // Some threads are still running. Don't signal yet.
2608 // We have a pending notification and all threads have stopped.
2610 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2612 // Clear any temporary breakpoints we used to implement software single
2614 for (const auto &thread_info : m_threads_stepping_with_breakpoint) {
2615 Error error = RemoveBreakpoint(thread_info.second);
2618 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64
2619 " remove stepping breakpoint: %s",
2620 __FUNCTION__, thread_info.first, error.AsCString());
2622 m_threads_stepping_with_breakpoint.clear();
2624 // Notify the delegate about the stop
2625 SetCurrentThreadID(m_pending_notification_tid);
2626 SetState(StateType::eStateStopped, true);
2627 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2630 void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) {
2631 Log *const log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD);
2634 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__,
2637 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID &&
2638 StateIsRunningState(thread.GetState())) {
2639 // We will need to wait for this new thread to stop as well before firing
2642 thread.RequestStop();
2646 void NativeProcessLinux::SigchldHandler() {
2647 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2648 // Process all pending waitpid notifications.
2651 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2654 break; // We are done.
2656 if (wait_pid == -1) {
2660 Error error(errno, eErrorTypePOSIX);
2662 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | "
2663 "__WNOTHREAD | WNOHANG) failed: %s",
2664 __FUNCTION__, error.AsCString());
2668 bool exited = false;
2670 int exit_status = 0;
2671 const char *status_cstr = nullptr;
2672 if (WIFSTOPPED(status)) {
2673 signal = WSTOPSIG(status);
2674 status_cstr = "STOPPED";
2675 } else if (WIFEXITED(status)) {
2676 exit_status = WEXITSTATUS(status);
2677 status_cstr = "EXITED";
2679 } else if (WIFSIGNALED(status)) {
2680 signal = WTERMSIG(status);
2681 status_cstr = "SIGNALED";
2682 if (wait_pid == static_cast<::pid_t>(GetID())) {
2687 status_cstr = "(\?\?\?)";
2690 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | "
2691 "__WNOTHREAD | WNOHANG)"
2693 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2694 __FUNCTION__, wait_pid, status, status_cstr, signal,
2697 MonitorCallback(wait_pid, exited, signal, exit_status);
2701 // Wrapper for ptrace to catch errors and log calls.
2702 // Note that ptrace sets errno on error because -1 can be a valid result (i.e.
2703 // for PTRACE_PEEK*)
2704 Error NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
2705 void *data, size_t data_size,
2710 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
2712 PtraceDisplayBytes(req, data, data_size);
2715 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2716 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2717 *(unsigned int *)addr, data);
2719 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid),
2723 error.SetErrorToErrno();
2729 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr,
2730 data, data_size, ret);
2732 PtraceDisplayBytes(req, data, data_size);
2734 if (log && error.GetError() != 0) {
2736 switch (error.GetError()) {
2750 str = error.AsCString();
2752 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);