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/ThreadLauncher.h"
33 #include "lldb/Host/common/NativeBreakpoint.h"
34 #include "lldb/Host/common/NativeRegisterContext.h"
35 #include "lldb/Symbol/ObjectFile.h"
36 #include "lldb/Target/Process.h"
37 #include "lldb/Target/ProcessLaunchInfo.h"
38 #include "lldb/Target/Target.h"
39 #include "lldb/Utility/LLDBAssert.h"
40 #include "lldb/Utility/PseudoTerminal.h"
41 #include "lldb/Utility/StringExtractor.h"
43 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
44 #include "NativeThreadLinux.h"
45 #include "ProcFileReader.h"
48 // System includes - They have to be included after framework includes because they define some
49 // macros which collide with variable names in other modules
50 #include <linux/unistd.h>
51 #include <sys/socket.h>
53 #include <sys/syscall.h>
54 #include <sys/types.h>
58 #include "lldb/Host/linux/Personality.h"
59 #include "lldb/Host/linux/Ptrace.h"
60 #include "lldb/Host/linux/Uio.h"
61 #include "lldb/Host/android/Android.h"
63 #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff
65 // Support hardware breakpoints in case it has not been defined
71 using namespace lldb_private;
72 using namespace lldb_private::process_linux;
75 // Private bits we only need internally.
77 static bool ProcessVmReadvSupported()
79 static bool is_supported;
80 static std::once_flag flag;
82 std::call_once(flag, [] {
83 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
85 uint32_t source = 0x47424742;
88 struct iovec local, remote;
89 remote.iov_base = &source;
90 local.iov_base = &dest;
91 remote.iov_len = local.iov_len = sizeof source;
93 // We shall try if cross-process-memory reads work by attempting to read a value from our own process.
94 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0);
95 is_supported = (res == sizeof(source) && source == dest);
99 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
102 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
103 __FUNCTION__, strerror(errno));
113 ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch)
115 // Grab process info for the running process.
116 ProcessInstanceInfo process_info;
117 if (!Host::GetProcessInfo(pid, process_info))
118 return Error("failed to get process info");
120 // Resolve the executable module.
121 ModuleSpecList module_specs;
122 if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs))
123 return Error("failed to get module specifications");
124 assert(module_specs.GetSize() == 1);
126 arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
130 return Error("failed to retrieve a valid architecture from the exe module");
133 // Used to notify the parent about which part of the launch sequence failed.
134 enum LaunchCallSpecifier
144 eLaunchCallMax = eSetSigMaskFailed
147 static uint8_t LLVM_ATTRIBUTE_NORETURN
148 ExitChildAbnormally(LaunchCallSpecifier spec)
150 static_assert(eLaunchCallMax < 0x8, "Have more launch calls than we are able to represent");
151 // This may truncate the topmost bits of the errno because the exit code is only 8 bits wide.
152 // However, it should still give us a pretty good indication of what went wrong. (And the
153 // most common errors have small numbers anyway).
154 _exit(unsigned(spec) | (errno << 3));
157 // The second member is the errno (or its 5 lowermost bits anyway).
158 inline std::pair<LaunchCallSpecifier, uint8_t>
159 DecodeChildExitCode(int exit_code)
161 return std::make_pair(LaunchCallSpecifier(exit_code & 0x7), exit_code >> 3);
165 MaybeLogLaunchInfo(const ProcessLaunchInfo &info)
167 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
171 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
172 log->Printf("%s: setting STDIN to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
174 log->Printf("%s leaving STDIN as is", __FUNCTION__);
176 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
177 log->Printf("%s setting STDOUT to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
179 log->Printf("%s leaving STDOUT as is", __FUNCTION__);
181 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
182 log->Printf("%s setting STDERR to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
184 log->Printf("%s leaving STDERR as is", __FUNCTION__);
187 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args; ++args, ++i)
188 log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
192 DisplayBytes(StreamString &s, void *bytes, uint32_t count)
194 uint8_t *ptr = (uint8_t *)bytes;
195 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
196 for (uint32_t i = 0; i < loop_count; i++)
198 s.Printf("[%x]", *ptr);
204 PtraceDisplayBytes(int &req, void *data, size_t data_size)
207 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
208 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
214 case PTRACE_POKETEXT:
216 DisplayBytes(buf, &data, 8);
217 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
220 case PTRACE_POKEDATA:
222 DisplayBytes(buf, &data, 8);
223 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
226 case PTRACE_POKEUSER:
228 DisplayBytes(buf, &data, 8);
229 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
234 DisplayBytes(buf, data, data_size);
235 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
238 case PTRACE_SETFPREGS:
240 DisplayBytes(buf, data, data_size);
241 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
244 case PTRACE_SETSIGINFO:
246 DisplayBytes(buf, data, sizeof(siginfo_t));
247 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
250 case PTRACE_SETREGSET:
252 // Extract iov_base from data, which is a pointer to the struct IOVEC
253 DisplayBytes(buf, *(void **)data, data_size);
254 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
264 static constexpr unsigned k_ptrace_word_size = sizeof(void*);
265 static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
266 } // end of anonymous namespace
268 // Simple helper function to ensure flags are enabled on the given file
271 EnsureFDFlags(int fd, int flags)
275 int status = fcntl(fd, F_GETFL);
278 error.SetErrorToErrno();
282 if (fcntl(fd, F_SETFL, status | flags) == -1)
284 error.SetErrorToErrno();
291 // -----------------------------------------------------------------------------
292 // Public Static Methods
293 // -----------------------------------------------------------------------------
296 NativeProcessProtocol::Launch (
297 ProcessLaunchInfo &launch_info,
298 NativeProcessProtocol::NativeDelegate &native_delegate,
300 NativeProcessProtocolSP &native_process_sp)
302 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
306 // Verify the working directory is valid if one was specified.
307 FileSpec working_dir{launch_info.GetWorkingDirectory()};
309 (!working_dir.ResolvePath() ||
310 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
312 error.SetErrorStringWithFormat ("No such file or directory: %s",
313 working_dir.GetCString());
317 // Create the NativeProcessLinux in launch mode.
318 native_process_sp.reset (new NativeProcessLinux ());
320 if (!native_process_sp->RegisterNativeDelegate (native_delegate))
322 native_process_sp.reset ();
323 error.SetErrorStringWithFormat ("failed to register the native delegate");
327 error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)->LaunchInferior(mainloop, launch_info);
331 native_process_sp.reset ();
333 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
337 launch_info.SetProcessID (native_process_sp->GetID ());
343 NativeProcessProtocol::Attach (
345 NativeProcessProtocol::NativeDelegate &native_delegate,
347 NativeProcessProtocolSP &native_process_sp)
349 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
350 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
351 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
353 // Retrieve the architecture for the running process.
354 ArchSpec process_arch;
355 Error error = ResolveProcessArchitecture(pid, process_arch);
356 if (!error.Success ())
359 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
361 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
363 error.SetErrorStringWithFormat ("failed to register the native delegate");
367 native_process_linux_sp->AttachToInferior (mainloop, pid, error);
368 if (!error.Success ())
371 native_process_sp = native_process_linux_sp;
375 // -----------------------------------------------------------------------------
376 // Public Instance Methods
377 // -----------------------------------------------------------------------------
379 NativeProcessLinux::NativeProcessLinux () :
380 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
382 m_supports_mem_region (eLazyBoolCalculate),
383 m_mem_region_cache (),
384 m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
389 NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
391 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
393 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
395 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
396 [this] (MainLoopBase &) { SigchldHandler(); }, error);
397 if (! m_sigchld_handle)
400 error = ResolveProcessArchitecture(pid, m_arch);
401 if (!error.Success())
404 // Set the architecture to the exe architecture.
406 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
409 SetState(eStateAttaching);
415 NativeProcessLinux::ChildFunc(const ProcessLaunchInfo &info)
417 // Start tracing this child that is about to exec.
418 if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1)
419 ExitChildAbnormally(ePtraceFailed);
421 // Do not inherit setgid powers.
422 if (setgid(getgid()) != 0)
423 ExitChildAbnormally(eSetGidFailed);
425 // Attempt to have our own process group.
426 if (setpgid(0, 0) != 0)
428 // FIXME log that this failed. This is common.
429 // Don't allow this to prevent an inferior exec.
432 // Dup file descriptors if needed.
433 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
434 if (!DupDescriptor(action->GetFileSpec(), STDIN_FILENO, O_RDONLY))
435 ExitChildAbnormally(eDupStdinFailed);
437 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
438 if (!DupDescriptor(action->GetFileSpec(), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
439 ExitChildAbnormally(eDupStdoutFailed);
441 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
442 if (!DupDescriptor(action->GetFileSpec(), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC))
443 ExitChildAbnormally(eDupStderrFailed);
445 // Close everything besides stdin, stdout, and stderr that has no file
446 // action to avoid leaking
447 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd)
448 if (!info.GetFileActionForFD(fd))
451 // Change working directory
452 if (info.GetWorkingDirectory() && 0 != ::chdir(info.GetWorkingDirectory().GetCString()))
453 ExitChildAbnormally(eChdirFailed);
455 // Disable ASLR if requested.
456 if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR))
458 const int old_personality = personality(LLDB_PERSONALITY_GET_CURRENT_SETTINGS);
459 if (old_personality == -1)
461 // Can't retrieve Linux personality. Cannot disable ASLR.
465 const int new_personality = personality(ADDR_NO_RANDOMIZE | old_personality);
466 if (new_personality == -1)
468 // Disabling ASLR failed.
472 // Disabling ASLR succeeded.
477 // Clear the signal mask to prevent the child from being affected by
478 // any masking done by the parent.
480 if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0)
481 ExitChildAbnormally(eSetSigMaskFailed);
483 const char **argv = info.GetArguments().GetConstArgumentVector();
485 // Propagate the environment if one is not supplied.
486 const char **envp = info.GetEnvironmentEntries().GetConstArgumentVector();
487 if (envp == NULL || envp[0] == NULL)
488 envp = const_cast<const char **>(environ);
490 // Execute. We should never return...
491 execve(argv[0], const_cast<char *const *>(argv), const_cast<char *const *>(envp));
493 if (errno == ETXTBSY)
495 // On android M and earlier we can get this error because the adb deamon can hold a write
496 // handle on the executable even after it has finished uploading it. This state lasts
497 // only a short time and happens only when there are many concurrent adb commands being
498 // issued, such as when running the test suite. (The file remains open when someone does
499 // an "adb shell" command in the fork() child before it has had a chance to exec.) Since
500 // this state should clear up quickly, wait a while and then give it one more go.
502 execve(argv[0], const_cast<char *const *>(argv), const_cast<char *const *>(envp));
505 // ...unless exec fails. In which case we definitely need to end the child here.
506 ExitChildAbnormally(eExecFailed);
510 NativeProcessLinux::LaunchInferior(MainLoop &mainloop, ProcessLaunchInfo &launch_info)
513 m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
514 if (!m_sigchld_handle)
517 SetState(eStateLaunching);
519 lldb_utility::PseudoTerminal terminal;
520 const size_t err_len = 1024;
521 char err_str[err_len];
524 MaybeLogLaunchInfo(launch_info);
526 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1))
528 error.SetErrorToGenericError();
529 error.SetErrorStringWithFormat("Process fork failed: %s", err_str);
536 // First, make sure we disable all logging. If we are logging to stdout, our logs can be
537 // mistaken for inferior output.
538 Log::DisableAllLogChannels(nullptr);
540 // terminal has already dupped the tty descriptors to stdin/out/err.
541 // This closes original fd from which they were copied (and avoids
542 // leaking descriptors to the debugged process.
543 terminal.CloseSlaveFileDescriptor();
545 ChildFunc(launch_info);
548 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
550 // Wait for the child process to trap on its call to execve.
553 if ((wpid = waitpid(pid, &status, 0)) < 0)
555 error.SetErrorToErrno();
557 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
558 __FUNCTION__, error.AsCString ());
560 // Mark the inferior as invalid.
561 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
562 SetState (StateType::eStateInvalid);
566 else if (WIFEXITED(status))
568 auto p = DecodeChildExitCode(WEXITSTATUS(status));
569 Error child_error(p.second, eErrorTypePOSIX);
570 const char *failure_reason;
574 failure_reason = "Child ptrace failed";
576 case eDupStdinFailed:
577 failure_reason = "Child open stdin failed";
579 case eDupStdoutFailed:
580 failure_reason = "Child open stdout failed";
582 case eDupStderrFailed:
583 failure_reason = "Child open stderr failed";
586 failure_reason = "Child failed to set working directory";
589 failure_reason = "Child exec failed";
592 failure_reason = "Child setgid failed";
594 case eSetSigMaskFailed:
595 failure_reason = "Child failed to set signal mask";
598 error.SetErrorStringWithFormat("%s: %d - %s (error code truncated)", failure_reason, child_error.GetError(), child_error.AsCString());
602 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP",
604 WEXITSTATUS(status));
607 // Mark the inferior as invalid.
608 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
609 SetState (StateType::eStateInvalid);
613 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
614 "Could not sync with inferior process.");
617 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
619 error = SetDefaultPtraceOpts(pid);
623 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
624 __FUNCTION__, error.AsCString ());
626 // Mark the inferior as invalid.
627 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
628 SetState (StateType::eStateInvalid);
633 // Release the master terminal descriptor and pass it off to the
634 // NativeProcessLinux instance. Similarly stash the inferior pid.
635 m_terminal_fd = terminal.ReleaseMasterFileDescriptor();
637 launch_info.SetProcessID(pid);
639 // Set the terminal fd to be in non blocking mode (it simplifies the
640 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking
641 // descriptor to read from).
642 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
646 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
647 __FUNCTION__, error.AsCString ());
649 // Mark the inferior as invalid.
650 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid.
651 SetState (StateType::eStateInvalid);
657 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid);
659 ResolveProcessArchitecture(m_pid, m_arch);
660 NativeThreadLinuxSP thread_sp = AddThread(pid);
661 assert (thread_sp && "AddThread() returned a nullptr thread");
662 thread_sp->SetStoppedBySignal(SIGSTOP);
663 ThreadWasCreated(*thread_sp);
665 // Let our process instance know the thread has stopped.
666 SetCurrentThreadID (thread_sp->GetID ());
667 SetState (StateType::eStateStopped);
671 if (error.Success ())
672 log->Printf("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
674 log->Printf("NativeProcessLinux::%s inferior launching failed: %s", __FUNCTION__, error.AsCString());
680 NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
682 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
684 // Use a map to keep track of the threads which we have attached/need to attach.
685 Host::TidMap tids_to_attach;
688 error.SetErrorToGenericError();
689 error.SetErrorString("Attaching to process 1 is not allowed.");
693 while (Host::FindProcessThreads(pid, tids_to_attach))
695 for (Host::TidMap::iterator it = tids_to_attach.begin();
696 it != tids_to_attach.end();)
698 if (it->second == false)
700 lldb::tid_t tid = it->first;
702 // Attach to the requested process.
703 // An attach will cause the thread to stop with a SIGSTOP.
704 error = PtraceWrapper(PTRACE_ATTACH, tid);
707 // No such thread. The thread may have exited.
708 // More error handling may be needed.
709 if (error.GetError() == ESRCH)
711 it = tids_to_attach.erase(it);
719 // Need to use __WALL otherwise we receive an error with errno=ECHLD
720 // At this point we should have a thread stopped if waitpid succeeds.
721 if ((status = waitpid(tid, NULL, __WALL)) < 0)
723 // No such thread. The thread may have exited.
724 // More error handling may be needed.
727 it = tids_to_attach.erase(it);
732 error.SetErrorToErrno();
737 error = SetDefaultPtraceOpts(tid);
742 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
746 // Create the thread, mark it as stopped.
747 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
748 assert (thread_sp && "AddThread() returned a nullptr");
750 // This will notify this is a new thread and tell the system it is stopped.
751 thread_sp->SetStoppedBySignal(SIGSTOP);
752 ThreadWasCreated(*thread_sp);
753 SetCurrentThreadID (thread_sp->GetID ());
756 // move the loop forward
761 if (tids_to_attach.size() > 0)
764 // Let our process instance know the thread has stopped.
765 SetState (StateType::eStateStopped);
769 error.SetErrorToGenericError();
770 error.SetErrorString("No such process.");
778 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
780 long ptrace_opts = 0;
782 // Have the child raise an event on exit. This is used to keep the child in
783 // limbo until it is destroyed.
784 ptrace_opts |= PTRACE_O_TRACEEXIT;
786 // Have the tracer trace threads which spawn in the inferior process.
787 // TODO: if we want to support tracing the inferiors' child, add the
788 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
789 ptrace_opts |= PTRACE_O_TRACECLONE;
791 // Have the tracer notify us before execve returns
792 // (needed to disable legacy SIGTRAP generation)
793 ptrace_opts |= PTRACE_O_TRACEEXEC;
795 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
798 static ExitType convert_pid_status_to_exit_type (int status)
800 if (WIFEXITED (status))
801 return ExitType::eExitTypeExit;
802 else if (WIFSIGNALED (status))
803 return ExitType::eExitTypeSignal;
804 else if (WIFSTOPPED (status))
805 return ExitType::eExitTypeStop;
808 // We don't know what this is.
809 return ExitType::eExitTypeInvalid;
813 static int convert_pid_status_to_return_code (int status)
815 if (WIFEXITED (status))
816 return WEXITSTATUS (status);
817 else if (WIFSIGNALED (status))
818 return WTERMSIG (status);
819 else if (WIFSTOPPED (status))
820 return WSTOPSIG (status);
823 // We don't know what this is.
824 return ExitType::eExitTypeInvalid;
828 // Handles all waitpid events from the inferior process.
830 NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
835 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
837 // Certain activities differ based on whether the pid is the tid of the main thread.
838 const bool is_main_thread = (pid == GetID ());
840 // Handle when the thread exits.
844 log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
846 // This is a thread that exited. Ensure we're not tracking it anymore.
847 const bool thread_found = StopTrackingThread (pid);
851 // We only set the exit status and notify the delegate if we haven't already set the process
852 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
853 // for the main thread.
854 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
855 if (!already_notified)
858 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ()));
859 // The main thread exited. We're done monitoring. Report to delegate.
860 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
862 // Notify delegate that our process has exited.
863 SetState (StateType::eStateExited, true);
868 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
873 // Do we want to report to the delegate in this case? I think not. If this was an orderly
874 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
875 // and we would have done an all-stop then.
877 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
883 const auto info_err = GetSignalInfo(pid, &info);
884 auto thread_sp = GetThreadByID(pid);
888 // Normally, the only situation when we cannot find the thread is if we have just
889 // received a new thread notification. This is indicated by GetSignalInfo() returning
890 // si_code == SI_USER and si_pid == 0
892 log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
897 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
901 if (log && (info.si_code != SI_USER || info.si_pid != 0))
902 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") unexpected signal info (si_code: %d, si_pid: %d). Treating as a new thread notification anyway.", __FUNCTION__, pid, info.si_code, info.si_pid);
904 auto thread_sp = AddThread(pid);
905 // Resume the newly created thread.
906 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
907 ThreadWasCreated(*thread_sp);
911 // Get details on the signal raised.
912 if (info_err.Success())
914 // We have retrieved the signal info. Dispatch appropriately.
915 if (info.si_signo == SIGTRAP)
916 MonitorSIGTRAP(info, *thread_sp);
918 MonitorSignal(info, *thread_sp, exited);
922 if (info_err.GetError() == EINVAL)
924 // This is a group stop reception for this tid.
925 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
926 // tracee, triggering the group-stop mechanism. Normally receiving these would stop
927 // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
928 // generally not needed (one use case is debugging background task being managed by a
929 // shell). For general use, it is sufficient to stop the process in a signal-delivery
930 // stop which happens before the group stop. This done by MonitorSignal and works
931 // correctly for all signals.
933 log->Printf("NativeProcessLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64 ". Transparent handling of group stops not supported, resuming the thread.", __FUNCTION__, GetID (), pid);
934 ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
938 // ptrace(GETSIGINFO) failed (but not due to group-stop).
940 // A return value of ESRCH means the thread/process is no longer on the system,
941 // so it was killed somehow outside of our control. Either way, we can't do anything
944 // Stop tracking the metadata for the thread since it's entirely off the system now.
945 const bool thread_found = StopTrackingThread (pid);
948 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
949 __FUNCTION__, info_err.AsCString(), pid, signal, status, info_err.GetError() == ESRCH ? "thread/process killed" : "unknown reason", is_main_thread ? "is main thread" : "is not main thread", thread_found ? "thread metadata removed" : "thread metadata not found");
953 // Notify the delegate - our process is not available but appears to have been killed outside
954 // our control. Is eStateExited the right exit state in this case?
955 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
956 SetState (StateType::eStateExited, true);
960 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop?
962 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid);
969 NativeProcessLinux::WaitForNewThread(::pid_t tid)
971 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
973 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
977 // We are already tracking the thread - we got the event on the new thread (see
978 // MonitorSignal) before this one. We are done.
982 // The thread is not tracked yet, let's wait for it to appear.
988 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
989 wait_pid = waitpid(tid, &status, __WALL);
991 while (wait_pid == -1 && errno == EINTR);
992 // Since we are waiting on a specific tid, this must be the creation event. But let's do
993 // some checks just in case.
994 if (wait_pid != tid) {
996 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
997 // The only way I know of this could happen is if the whole process was
998 // SIGKILLed in the mean time. In any case, we can't do anything about that now.
1001 if (WIFEXITED(status))
1004 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
1005 // Also a very improbable event.
1010 Error error = GetSignalInfo(tid, &info);
1014 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
1018 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
1020 // We should be getting a thread creation signal here, but we received something
1021 // else. There isn't much we can do about it now, so we will just log that. Since the
1022 // thread is alive and we are receiving events from it, we shall pretend that it was
1023 // created properly.
1024 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid);
1028 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
1029 __FUNCTION__, GetID (), tid);
1031 new_thread_sp = AddThread(tid);
1032 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
1033 ThreadWasCreated(*new_thread_sp);
1037 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
1039 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1040 const bool is_main_thread = (thread.GetID() == GetID ());
1042 assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
1044 switch (info.si_code)
1046 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor.
1047 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
1048 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
1050 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
1052 // This is the notification on the parent thread which informs us of new thread
1054 // We don't want to do anything with the parent thread so we just resume it. In case we
1055 // want to implement "break on thread creation" functionality, we would need to stop
1058 unsigned long event_message = 0;
1059 if (GetEventMessage(thread.GetID(), &event_message).Fail())
1062 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, thread.GetID());
1064 WaitForNewThread(event_message);
1066 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1070 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
1072 NativeThreadLinuxSP main_thread_sp;
1074 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
1076 // Exec clears any pending notifications.
1077 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
1079 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread.
1081 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
1083 for (auto thread_sp : m_threads)
1085 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
1088 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
1090 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
1095 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
1103 m_threads.push_back (main_thread_sp);
1104 SetCurrentThreadID (main_thread_sp->GetID ());
1105 main_thread_sp->SetStoppedByExec();
1109 SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
1111 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
1114 // Tell coordinator about about the "new" (since exec) stopped main thread.
1115 ThreadWasCreated(*main_thread_sp);
1117 // Let our delegate know we have just exec'd.
1120 // If we have a main thread, indicate we are stopped.
1121 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
1123 // Let the process know we're stopped.
1124 StopRunningThreads(main_thread_sp->GetID());
1129 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
1131 // The inferior process or one of its threads is about to exit.
1132 // We don't want to do anything with the thread so we just resume it. In case we
1133 // want to implement "break on thread exit" functionality, we would need to stop
1136 unsigned long data = 0;
1137 if (GetEventMessage(thread.GetID(), &data).Fail())
1142 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
1144 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
1146 is_main_thread ? "is main thread" : "not main thread");
1151 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
1154 StateType state = thread.GetState();
1155 if (! StateIsRunningState(state))
1157 // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
1158 // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
1159 // we should not be receiving any ptrace events while the inferior is stopped. This
1160 // makes sure that the inferior is resumed and exits normally.
1161 state = eStateRunning;
1163 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
1169 case TRAP_TRACE: // We receive this on single stepping.
1170 case TRAP_HWBKPT: // We receive this on watchpoint hit
1172 // If a watchpoint was hit, report it
1174 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
1175 if (error.Fail() && log)
1176 log->Printf("NativeProcessLinux::%s() "
1177 "received error while checking for watchpoint hits, "
1178 "pid = %" PRIu64 " error = %s",
1179 __FUNCTION__, thread.GetID(), error.AsCString());
1180 if (wp_index != LLDB_INVALID_INDEX32)
1182 MonitorWatchpoint(thread, wp_index);
1186 // Otherwise, report step over
1187 MonitorTrace(thread);
1192 #if defined __mips__
1193 // For mips there is no special signal for watchpoint
1194 // So we check for watchpoint in kernel trap
1196 // If a watchpoint was hit, report it
1198 Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1199 if (error.Fail() && log)
1200 log->Printf("NativeProcessLinux::%s() "
1201 "received error while checking for watchpoint hits, "
1202 "pid = %" PRIu64 " error = %s",
1203 __FUNCTION__, thread.GetID(), error.AsCString());
1204 if (wp_index != LLDB_INVALID_INDEX32)
1206 MonitorWatchpoint(thread, wp_index);
1213 MonitorBreakpoint(thread);
1217 case (SIGTRAP | 0x80):
1219 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
1221 // Ignore these signals until we know more about them.
1222 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1226 assert(false && "Unexpected SIGTRAP code!");
1228 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1229 __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1236 NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
1238 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1240 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1241 __FUNCTION__, thread.GetID());
1243 // This thread is currently stopped.
1244 thread.SetStoppedByTrace();
1246 StopRunningThreads(thread.GetID());
1250 NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
1252 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1254 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1255 __FUNCTION__, thread.GetID());
1257 // Mark the thread as stopped at breakpoint.
1258 thread.SetStoppedByBreakpoint();
1259 Error error = FixupBreakpointPCAsNeeded(thread);
1262 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1263 __FUNCTION__, thread.GetID(), error.AsCString());
1265 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1266 thread.SetStoppedByTrace();
1268 StopRunningThreads(thread.GetID());
1272 NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
1274 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1276 log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1277 "pid = %" PRIu64 ", wp_index = %" PRIu32,
1278 __FUNCTION__, thread.GetID(), wp_index);
1280 // Mark the thread as stopped at watchpoint.
1281 // The address is at (lldb::addr_t)info->si_addr if we need it.
1282 thread.SetStoppedByWatchpoint(wp_index);
1284 // We need to tell all other running threads before we notify the delegate about this stop.
1285 StopRunningThreads(thread.GetID());
1289 NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
1291 const int signo = info.si_signo;
1292 const bool is_from_llgs = info.si_pid == getpid ();
1294 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1296 // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1297 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1298 // kill(2) or raise(3). Similarly for tgkill(2) on Linux.
1300 // IOW, user generated signals never generate what we consider to be a
1303 // Similarly, ACK signals generated by this monitor.
1305 // Handle the signal.
1306 if (info.si_code == SI_TKILL || info.si_code == SI_USER)
1309 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1311 Host::GetSignalAsCString(signo),
1313 (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1315 is_from_llgs ? "from llgs" : "not from llgs",
1319 // Check for thread stop notification.
1320 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
1322 // This is a tgkill()-based stop.
1324 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1329 // Check that we're not already marked with a stop reason.
1330 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1331 // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1332 // and that, without an intervening resume, we received another stop. It is more likely
1333 // that we are missing the marking of a run state somewhere if we find that the thread was
1334 // marked as stopped.
1335 const StateType thread_state = thread.GetState();
1336 if (!StateIsStoppedState (thread_state, false))
1338 // An inferior thread has stopped because of a SIGSTOP we have sent it.
1339 // Generally, these are not important stops and we don't want to report them as
1340 // they are just used to stop other threads when one thread (the one with the
1341 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1342 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1343 // leave the signal intact if this is the thread that was chosen as the
1344 // triggering thread.
1345 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
1347 if (m_pending_notification_tid == thread.GetID())
1348 thread.SetStoppedBySignal(SIGSTOP, &info);
1350 thread.SetStoppedWithNoReason();
1352 SetCurrentThreadID (thread.GetID ());
1353 SignalIfAllThreadsStopped();
1357 // We can end up here if stop was initiated by LLGS but by this time a
1358 // thread stop has occurred - maybe initiated by another event.
1359 Error error = ResumeThread(thread, thread.GetState(), 0);
1360 if (error.Fail() && log)
1362 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s",
1363 __FUNCTION__, thread.GetID(), error.AsCString());
1371 // Retrieve the signal name if the thread was stopped by a signal.
1373 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1374 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1376 signal_name = "<no-signal-name>";
1378 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is",
1382 StateAsCString (thread_state),
1386 SignalIfAllThreadsStopped();
1394 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
1396 // This thread is stopped.
1397 thread.SetStoppedBySignal(signo, &info);
1399 // Send a stop to the debugger after we get all other threads to stop.
1400 StopRunningThreads(thread.GetID());
1405 struct EmulatorBaton
1407 NativeProcessLinux* m_process;
1408 NativeRegisterContext* m_reg_context;
1410 // eRegisterKindDWARF -> RegsiterValue
1411 std::unordered_map<uint32_t, RegisterValue> m_register_values;
1413 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
1414 m_process(process), m_reg_context(reg_context) {}
1417 } // anonymous namespace
1420 ReadMemoryCallback (EmulateInstruction *instruction,
1422 const EmulateInstruction::Context &context,
1427 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1430 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1435 ReadRegisterCallback (EmulateInstruction *instruction,
1437 const RegisterInfo *reg_info,
1438 RegisterValue ®_value)
1440 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1442 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1443 if (it != emulator_baton->m_register_values.end())
1445 reg_value = it->second;
1449 // The emulator only fill in the dwarf regsiter numbers (and in some case
1450 // the generic register numbers). Get the full register info from the
1451 // register context based on the dwarf register numbers.
1452 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1453 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1455 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1456 if (error.Success())
1463 WriteRegisterCallback (EmulateInstruction *instruction,
1465 const EmulateInstruction::Context &context,
1466 const RegisterInfo *reg_info,
1467 const RegisterValue ®_value)
1469 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1470 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
1475 WriteMemoryCallback (EmulateInstruction *instruction,
1477 const EmulateInstruction::Context &context,
1486 ReadFlags (NativeRegisterContext* regsiter_context)
1488 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1489 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1490 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1494 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
1497 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1499 std::unique_ptr<EmulateInstruction> emulator_ap(
1500 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1502 if (emulator_ap == nullptr)
1503 return Error("Instruction emulator not found!");
1505 EmulatorBaton baton(this, register_context_sp.get());
1506 emulator_ap->SetBaton(&baton);
1507 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1508 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1509 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1510 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1512 if (!emulator_ap->ReadInstruction())
1513 return Error("Read instruction failed!");
1515 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1517 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1518 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1520 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1521 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1523 lldb::addr_t next_pc;
1524 lldb::addr_t next_flags;
1525 if (emulation_result)
1527 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1528 next_pc = pc_it->second.GetAsUInt64();
1530 if (flags_it != baton.m_register_values.end())
1531 next_flags = flags_it->second.GetAsUInt64();
1533 next_flags = ReadFlags (register_context_sp.get());
1535 else if (pc_it == baton.m_register_values.end())
1537 // Emulate instruction failed and it haven't changed PC. Advance PC
1538 // with the size of the current opcode because the emulation of all
1539 // PC modifying instruction should be successful. The failure most
1540 // likely caused by a not supported instruction which don't modify PC.
1541 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1542 next_flags = ReadFlags (register_context_sp.get());
1546 // The instruction emulation failed after it modified the PC. It is an
1547 // unknown error where we can't continue because the next instruction is
1548 // modifying the PC but we don't know how.
1549 return Error ("Instruction emulation failed unexpectedly.");
1552 if (m_arch.GetMachine() == llvm::Triple::arm)
1554 if (next_flags & 0x20)
1557 error = SetSoftwareBreakpoint(next_pc, 2);
1562 error = SetSoftwareBreakpoint(next_pc, 4);
1565 else if (m_arch.GetMachine() == llvm::Triple::mips64
1566 || m_arch.GetMachine() == llvm::Triple::mips64el
1567 || m_arch.GetMachine() == llvm::Triple::mips
1568 || m_arch.GetMachine() == llvm::Triple::mipsel)
1569 error = SetSoftwareBreakpoint(next_pc, 4);
1572 // No size hint is given for the next breakpoint
1573 error = SetSoftwareBreakpoint(next_pc, 0);
1579 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1585 NativeProcessLinux::SupportHardwareSingleStepping() const
1587 if (m_arch.GetMachine() == llvm::Triple::arm
1588 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1589 || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
1595 NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1597 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1599 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1601 bool software_single_step = !SupportHardwareSingleStepping();
1603 if (software_single_step)
1605 for (auto thread_sp : m_threads)
1607 assert (thread_sp && "thread list should not contain NULL threads");
1609 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1610 if (action == nullptr)
1613 if (action->state == eStateStepping)
1615 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
1622 for (auto thread_sp : m_threads)
1624 assert (thread_sp && "thread list should not contain NULL threads");
1626 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1628 if (action == nullptr)
1631 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1632 __FUNCTION__, GetID (), thread_sp->GetID ());
1638 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1639 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1642 switch (action->state)
1645 case eStateStepping:
1647 // Run the thread, possibly feeding it the signal.
1648 const int signo = action->signal;
1649 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
1653 case eStateSuspended:
1655 lldbassert(0 && "Unexpected state");
1658 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1659 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1667 NativeProcessLinux::Halt ()
1671 if (kill (GetID (), SIGSTOP) != 0)
1672 error.SetErrorToErrno ();
1678 NativeProcessLinux::Detach ()
1682 // Stop monitoring the inferior.
1683 m_sigchld_handle.reset();
1685 // Tell ptrace to detach from the process.
1686 if (GetID () == LLDB_INVALID_PROCESS_ID)
1689 for (auto thread_sp : m_threads)
1691 Error e = Detach(thread_sp->GetID());
1693 error = e; // Save the error, but still attempt to detach from other threads.
1700 NativeProcessLinux::Signal (int signo)
1704 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1706 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1707 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1709 if (kill(GetID(), signo))
1710 error.SetErrorToErrno();
1716 NativeProcessLinux::Interrupt ()
1718 // Pick a running thread (or if none, a not-dead stopped thread) as
1719 // the chosen thread that will be the stop-reason thread.
1720 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1722 NativeThreadProtocolSP running_thread_sp;
1723 NativeThreadProtocolSP stopped_thread_sp;
1726 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1728 for (auto thread_sp : m_threads)
1730 // The thread shouldn't be null but lets just cover that here.
1734 // If we have a running or stepping thread, we'll call that the
1735 // target of the interrupt.
1736 const auto thread_state = thread_sp->GetState ();
1737 if (thread_state == eStateRunning ||
1738 thread_state == eStateStepping)
1740 running_thread_sp = thread_sp;
1743 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1745 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads.
1746 stopped_thread_sp = thread_sp;
1750 if (!running_thread_sp && !stopped_thread_sp)
1752 Error error("found no running/stepping or live stopped threads as target for interrupt");
1754 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
1759 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1762 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1765 running_thread_sp ? "running" : "stopped",
1766 deferred_signal_thread_sp->GetID ());
1768 StopRunningThreads(deferred_signal_thread_sp->GetID());
1774 NativeProcessLinux::Kill ()
1776 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1778 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1784 case StateType::eStateInvalid:
1785 case StateType::eStateExited:
1786 case StateType::eStateCrashed:
1787 case StateType::eStateDetached:
1788 case StateType::eStateUnloaded:
1789 // Nothing to do - the process is already dead.
1791 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1794 case StateType::eStateConnected:
1795 case StateType::eStateAttaching:
1796 case StateType::eStateLaunching:
1797 case StateType::eStateStopped:
1798 case StateType::eStateRunning:
1799 case StateType::eStateStepping:
1800 case StateType::eStateSuspended:
1801 // We can try to kill a process in these states.
1805 if (kill (GetID (), SIGKILL) != 0)
1807 error.SetErrorToErrno ();
1815 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1817 memory_region_info.Clear();
1819 StringExtractor line_extractor (maps_line.c_str ());
1821 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname
1822 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared).
1824 // Parse out the starting address
1825 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1827 // Parse out hyphen separating start and end address from range.
1828 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1829 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1831 // Parse out the ending address
1832 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1834 // Parse out the space after the address.
1835 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1836 return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1839 memory_region_info.GetRange ().SetRangeBase (start_address);
1840 memory_region_info.GetRange ().SetRangeEnd (end_address);
1842 // Any memory region in /proc/{pid}/maps is by definition mapped into the process.
1843 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1845 // Parse out each permission entry.
1846 if (line_extractor.GetBytesLeft () < 4)
1847 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1849 // Handle read permission.
1850 const char read_perm_char = line_extractor.GetChar ();
1851 if (read_perm_char == 'r')
1852 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1853 else if (read_perm_char == '-')
1854 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1856 return Error ("unexpected /proc/{pid}/maps read permission char");
1858 // Handle write permission.
1859 const char write_perm_char = line_extractor.GetChar ();
1860 if (write_perm_char == 'w')
1861 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1862 else if (write_perm_char == '-')
1863 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1865 return Error ("unexpected /proc/{pid}/maps write permission char");
1867 // Handle execute permission.
1868 const char exec_perm_char = line_extractor.GetChar ();
1869 if (exec_perm_char == 'x')
1870 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1871 else if (exec_perm_char == '-')
1872 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1874 return Error ("unexpected /proc/{pid}/maps exec permission char");
1880 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1882 // FIXME review that the final memory region returned extends to the end of the virtual address space,
1883 // with no perms if it is not mapped.
1885 // Use an approach that reads memory regions from /proc/{pid}/maps.
1886 // Assume proc maps entries are in ascending order.
1887 // FIXME assert if we find differently.
1889 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1892 if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1895 error.SetErrorString ("unsupported");
1899 // If our cache is empty, pull the latest. There should always be at least one memory region
1900 // if memory region handling is supported.
1901 if (m_mem_region_cache.empty ())
1903 error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1904 [&] (const std::string &line) -> bool
1906 MemoryRegionInfo info;
1907 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1908 if (parse_error.Success ())
1910 m_mem_region_cache.push_back (info);
1916 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1921 // If we had an error, we'll mark unsupported.
1924 m_supports_mem_region = LazyBool::eLazyBoolNo;
1927 else if (m_mem_region_cache.empty ())
1929 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps
1930 // is supported. Assume we don't support map entries via procfs.
1932 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
1933 m_supports_mem_region = LazyBool::eLazyBoolNo;
1934 error.SetErrorString ("not supported");
1939 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
1941 // We support memory retrieval, remember that.
1942 m_supports_mem_region = LazyBool::eLazyBoolYes;
1947 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
1950 lldb::addr_t prev_base_address = 0;
1952 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted.
1953 // There can be a ton of regions on pthreads apps with lots of threads.
1954 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
1956 MemoryRegionInfo &proc_entry_info = *it;
1958 // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1959 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
1960 prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
1962 // If the target address comes before this entry, indicate distance to next region.
1963 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
1965 range_info.GetRange ().SetRangeBase (load_addr);
1966 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
1967 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1968 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1969 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1970 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1974 else if (proc_entry_info.GetRange ().Contains (load_addr))
1976 // The target address is within the memory region we're processing here.
1977 range_info = proc_entry_info;
1981 // The target memory address comes somewhere after the region we just parsed.
1984 // If we made it here, we didn't find an entry that contained the given address. Return the
1985 // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
1987 range_info.GetRange ().SetRangeBase (load_addr);
1988 range_info.GetRange ().SetRangeEnd(LLDB_INVALID_ADDRESS);
1989 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1990 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1991 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1992 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1997 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
1999 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2001 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
2004 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
2005 m_mem_region_cache.clear ();
2009 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
2011 // FIXME implementing this requires the equivalent of
2012 // InferiorCallPOSIX::InferiorCallMmap, which depends on
2013 // functional ThreadPlans working with Native*Protocol.
2015 return Error ("not implemented yet");
2017 addr = LLDB_INVALID_ADDRESS;
2020 if (permissions & lldb::ePermissionsReadable)
2021 prot |= eMmapProtRead;
2022 if (permissions & lldb::ePermissionsWritable)
2023 prot |= eMmapProtWrite;
2024 if (permissions & lldb::ePermissionsExecutable)
2025 prot |= eMmapProtExec;
2027 // TODO implement this directly in NativeProcessLinux
2028 // (and lift to NativeProcessPOSIX if/when that class is
2030 if (InferiorCallMmap(this, addr, 0, size, prot,
2031 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
2032 m_addr_to_mmap_size[addr] = size;
2035 addr = LLDB_INVALID_ADDRESS;
2036 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
2042 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
2044 // FIXME see comments in AllocateMemory - required lower-level
2045 // bits not in place yet (ThreadPlans)
2046 return Error ("not implemented");
2050 NativeProcessLinux::GetSharedLibraryInfoAddress ()
2052 // punt on this for now
2053 return LLDB_INVALID_ADDRESS;
2057 NativeProcessLinux::UpdateThreads ()
2059 // The NativeProcessLinux monitoring threads are always up to date
2060 // with respect to thread state and they keep the thread list
2061 // populated properly. All this method needs to do is return the
2063 return m_threads.size ();
2067 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
2074 NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
2076 // FIXME put this behind a breakpoint protocol class that can be
2077 // set per architecture. Need ARM, MIPS support here.
2078 static const uint8_t g_i386_opcode [] = { 0xCC };
2079 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2081 switch (m_arch.GetMachine ())
2083 case llvm::Triple::x86:
2084 case llvm::Triple::x86_64:
2085 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
2088 case llvm::Triple::systemz:
2089 actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
2092 case llvm::Triple::arm:
2093 case llvm::Triple::aarch64:
2094 case llvm::Triple::mips64:
2095 case llvm::Triple::mips64el:
2096 case llvm::Triple::mips:
2097 case llvm::Triple::mipsel:
2098 // On these architectures the PC don't get updated for breakpoint hits
2099 actual_opcode_size = 0;
2103 assert(false && "CPU type not supported!");
2104 return Error ("CPU type not supported");
2109 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
2112 return Error ("NativeProcessLinux does not support hardware breakpoints");
2114 return SetSoftwareBreakpoint (addr, size);
2118 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
2119 size_t &actual_opcode_size,
2120 const uint8_t *&trap_opcode_bytes)
2122 // FIXME put this behind a breakpoint protocol class that can be set per
2123 // architecture. Need MIPS support here.
2124 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
2125 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
2126 // linux kernel does otherwise.
2127 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
2128 static const uint8_t g_i386_opcode [] = { 0xCC };
2129 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
2130 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
2131 static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
2132 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
2134 switch (m_arch.GetMachine ())
2136 case llvm::Triple::aarch64:
2137 trap_opcode_bytes = g_aarch64_opcode;
2138 actual_opcode_size = sizeof(g_aarch64_opcode);
2141 case llvm::Triple::arm:
2142 switch (trap_opcode_size_hint)
2145 trap_opcode_bytes = g_thumb_breakpoint_opcode;
2146 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2149 trap_opcode_bytes = g_arm_breakpoint_opcode;
2150 actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
2153 assert(false && "Unrecognised trap opcode size hint!");
2154 return Error ("Unrecognised trap opcode size hint!");
2157 case llvm::Triple::x86:
2158 case llvm::Triple::x86_64:
2159 trap_opcode_bytes = g_i386_opcode;
2160 actual_opcode_size = sizeof(g_i386_opcode);
2163 case llvm::Triple::mips:
2164 case llvm::Triple::mips64:
2165 trap_opcode_bytes = g_mips64_opcode;
2166 actual_opcode_size = sizeof(g_mips64_opcode);
2169 case llvm::Triple::mipsel:
2170 case llvm::Triple::mips64el:
2171 trap_opcode_bytes = g_mips64el_opcode;
2172 actual_opcode_size = sizeof(g_mips64el_opcode);
2175 case llvm::Triple::systemz:
2176 trap_opcode_bytes = g_s390x_opcode;
2177 actual_opcode_size = sizeof(g_s390x_opcode);
2181 assert(false && "CPU type not supported!");
2182 return Error ("CPU type not supported");
2187 ProcessMessage::CrashReason
2188 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2190 ProcessMessage::CrashReason reason;
2191 assert(info->si_signo == SIGSEGV);
2193 reason = ProcessMessage::eInvalidCrashReason;
2195 switch (info->si_code)
2198 assert(false && "unexpected si_code for SIGSEGV");
2201 // Linux will occasionally send spurious SI_KERNEL codes.
2202 // (this is poorly documented in sigaction)
2203 // One way to get this is via unaligned SIMD loads.
2204 reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2207 reason = ProcessMessage::eInvalidAddress;
2210 reason = ProcessMessage::ePrivilegedAddress;
2220 ProcessMessage::CrashReason
2221 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2223 ProcessMessage::CrashReason reason;
2224 assert(info->si_signo == SIGILL);
2226 reason = ProcessMessage::eInvalidCrashReason;
2228 switch (info->si_code)
2231 assert(false && "unexpected si_code for SIGILL");
2234 reason = ProcessMessage::eIllegalOpcode;
2237 reason = ProcessMessage::eIllegalOperand;
2240 reason = ProcessMessage::eIllegalAddressingMode;
2243 reason = ProcessMessage::eIllegalTrap;
2246 reason = ProcessMessage::ePrivilegedOpcode;
2249 reason = ProcessMessage::ePrivilegedRegister;
2252 reason = ProcessMessage::eCoprocessorError;
2255 reason = ProcessMessage::eInternalStackError;
2264 ProcessMessage::CrashReason
2265 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2267 ProcessMessage::CrashReason reason;
2268 assert(info->si_signo == SIGFPE);
2270 reason = ProcessMessage::eInvalidCrashReason;
2272 switch (info->si_code)
2275 assert(false && "unexpected si_code for SIGFPE");
2278 reason = ProcessMessage::eIntegerDivideByZero;
2281 reason = ProcessMessage::eIntegerOverflow;
2284 reason = ProcessMessage::eFloatDivideByZero;
2287 reason = ProcessMessage::eFloatOverflow;
2290 reason = ProcessMessage::eFloatUnderflow;
2293 reason = ProcessMessage::eFloatInexactResult;
2296 reason = ProcessMessage::eFloatInvalidOperation;
2299 reason = ProcessMessage::eFloatSubscriptRange;
2308 ProcessMessage::CrashReason
2309 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2311 ProcessMessage::CrashReason reason;
2312 assert(info->si_signo == SIGBUS);
2314 reason = ProcessMessage::eInvalidCrashReason;
2316 switch (info->si_code)
2319 assert(false && "unexpected si_code for SIGBUS");
2322 reason = ProcessMessage::eIllegalAlignment;
2325 reason = ProcessMessage::eIllegalAddress;
2328 reason = ProcessMessage::eHardwareError;
2337 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2339 if (ProcessVmReadvSupported()) {
2340 // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2341 // this syscall if it is supported.
2343 const ::pid_t pid = GetID();
2345 struct iovec local_iov, remote_iov;
2346 local_iov.iov_base = buf;
2347 local_iov.iov_len = size;
2348 remote_iov.iov_base = reinterpret_cast<void *>(addr);
2349 remote_iov.iov_len = size;
2351 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2352 const bool success = bytes_read == size;
2354 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2356 log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2357 __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2362 // the call failed for some reason, let's retry the read using ptrace api.
2365 unsigned char *dst = static_cast<unsigned char*>(buf);
2369 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2371 ProcessPOSIXLog::IncNestLevel();
2372 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2373 log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2375 for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2377 Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2381 ProcessPOSIXLog::DecNestLevel();
2385 remainder = size - bytes_read;
2386 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2388 // Copy the data into our buffer
2389 memcpy(dst, &data, remainder);
2391 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2392 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2393 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2394 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2396 uintptr_t print_dst = 0;
2397 // Format bytes from data by moving into print_dst for log output
2398 for (unsigned i = 0; i < remainder; ++i)
2399 print_dst |= (((data >> i*8) & 0xFF) << i*8);
2400 log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2401 __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
2403 addr += k_ptrace_word_size;
2404 dst += k_ptrace_word_size;
2408 ProcessPOSIXLog::DecNestLevel();
2413 NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2415 Error error = ReadMemory(addr, buf, size, bytes_read);
2416 if (error.Fail()) return error;
2417 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2421 NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
2423 const unsigned char *src = static_cast<const unsigned char*>(buf);
2427 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2429 ProcessPOSIXLog::IncNestLevel();
2430 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2431 log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
2433 for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2435 remainder = size - bytes_written;
2436 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2438 if (remainder == k_ptrace_word_size)
2440 unsigned long data = 0;
2441 memcpy(&data, src, k_ptrace_word_size);
2443 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2444 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2445 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2446 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2447 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2448 (void*)addr, *(const unsigned long*)src, data);
2450 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2454 ProcessPOSIXLog::DecNestLevel();
2460 unsigned char buff[8];
2462 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2466 ProcessPOSIXLog::DecNestLevel();
2470 memcpy(buff, src, remainder);
2472 size_t bytes_written_rec;
2473 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2477 ProcessPOSIXLog::DecNestLevel();
2481 if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2482 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2483 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2484 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2485 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2486 (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2489 addr += k_ptrace_word_size;
2490 src += k_ptrace_word_size;
2493 ProcessPOSIXLog::DecNestLevel();
2498 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
2500 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2504 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2506 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2510 NativeProcessLinux::Detach(lldb::tid_t tid)
2512 if (tid == LLDB_INVALID_THREAD_ID)
2515 return PtraceWrapper(PTRACE_DETACH, tid);
2519 NativeProcessLinux::DupDescriptor(const FileSpec &file_spec, int fd, int flags)
2521 int target_fd = open(file_spec.GetCString(), flags, 0666);
2523 if (target_fd == -1)
2526 if (dup2(target_fd, fd) == -1)
2529 return (close(target_fd) == -1) ? false : true;
2533 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2535 for (auto thread_sp : m_threads)
2537 assert (thread_sp && "thread list should not contain NULL threads");
2538 if (thread_sp->GetID () == thread_id)
2540 // We have this thread.
2545 // We don't have this thread.
2550 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2552 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2555 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2559 for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2561 if (*it && ((*it)->GetID () == thread_id))
2563 m_threads.erase (it);
2569 SignalIfAllThreadsStopped();
2575 NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2577 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2581 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2587 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2589 // If this is the first thread, save it as the current thread
2590 if (m_threads.empty ())
2591 SetCurrentThreadID (thread_id);
2593 auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2594 m_threads.push_back (thread_sp);
2599 NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
2601 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2605 // Find out the size of a breakpoint (might depend on where we are in the code).
2606 NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2609 error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2611 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2615 uint32_t breakpoint_size = 0;
2616 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2620 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2626 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2629 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
2630 const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
2631 lldb::addr_t breakpoint_addr = initial_pc_addr;
2632 if (breakpoint_size > 0)
2634 // Do not allow breakpoint probe to wrap around.
2635 if (breakpoint_addr >= breakpoint_size)
2636 breakpoint_addr -= breakpoint_size;
2639 // Check if we stopped because of a breakpoint.
2640 NativeBreakpointSP breakpoint_sp;
2641 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2642 if (!error.Success () || !breakpoint_sp)
2644 // We didn't find one at a software probe location. Nothing to do.
2646 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2650 // If the breakpoint is not a software breakpoint, nothing to do.
2651 if (!breakpoint_sp->IsSoftwareBreakpoint ())
2654 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2659 // We have a software breakpoint and need to adjust the PC.
2663 if (breakpoint_size == 0)
2665 // Nothing to do! How did we get here?
2667 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", it is software, but the size is zero, nothing to do (unexpected)", __FUNCTION__, GetID (), breakpoint_addr);
2671 // Change the program counter.
2673 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID(), thread.GetID(), initial_pc_addr, breakpoint_addr);
2675 error = context_sp->SetPC (breakpoint_addr);
2679 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
2687 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2689 FileSpec module_file_spec(module_path, true);
2693 ProcFileReader::ProcessLineByLine(GetID(), "maps",
2694 [&] (const std::string &line)
2696 SmallVector<StringRef, 16> columns;
2697 StringRef(line).split(columns, " ", -1, false);
2698 if (columns.size() < 6)
2699 return true; // continue searching
2701 FileSpec this_file_spec(columns[5].str().c_str(), false);
2702 if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2703 return true; // continue searching
2705 file_spec = this_file_spec;
2707 return false; // we are done
2711 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2712 module_file_spec.GetFilename().AsCString(), GetID());
2718 NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2720 load_addr = LLDB_INVALID_ADDRESS;
2721 Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2722 [&] (const std::string &line) -> bool
2724 StringRef maps_row(line);
2726 SmallVector<StringRef, 16> maps_columns;
2727 maps_row.split(maps_columns, StringRef(" "), -1, false);
2729 if (maps_columns.size() < 6)
2731 // Return true to continue reading the proc file
2735 if (maps_columns[5] == file_name)
2737 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2738 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2740 // Return false to stop reading the proc file further
2744 // Return true to continue reading the proc file
2751 NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2753 return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2757 NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
2759 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2762 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
2763 __FUNCTION__, thread.GetID());
2765 // Before we do the resume below, first check if we have a pending
2766 // stop notification that is currently waiting for
2767 // all threads to stop. This is potentially a buggy situation since
2768 // we're ostensibly waiting for threads to stop before we send out the
2769 // pending notification, and here we are resuming one before we send
2770 // out the pending stop notification.
2771 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
2773 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, thread.GetID(), m_pending_notification_tid);
2776 // Request a resume. We expect this to be synchronous and the system
2777 // to reflect it is running after this completes.
2782 const auto resume_result = thread.Resume(signo);
2783 if (resume_result.Success())
2784 SetState(eStateRunning, true);
2785 return resume_result;
2787 case eStateStepping:
2789 const auto step_result = thread.SingleStep(signo);
2790 if (step_result.Success())
2791 SetState(eStateRunning, true);
2796 log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2797 __FUNCTION__, StateAsCString(state));
2798 llvm_unreachable("Unhandled state for resume");
2802 //===----------------------------------------------------------------------===//
2805 NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
2807 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2811 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
2812 __FUNCTION__, triggering_tid);
2815 m_pending_notification_tid = triggering_tid;
2817 // Request a stop for all the thread stops that need to be stopped
2818 // and are not already known to be stopped.
2819 for (const auto &thread_sp: m_threads)
2821 if (StateIsRunningState(thread_sp->GetState()))
2822 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2825 SignalIfAllThreadsStopped();
2829 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2834 NativeProcessLinux::SignalIfAllThreadsStopped()
2836 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2837 return; // No pending notification. Nothing to do.
2839 for (const auto &thread_sp: m_threads)
2841 if (StateIsRunningState(thread_sp->GetState()))
2842 return; // Some threads are still running. Don't signal yet.
2845 // We have a pending notification and all threads have stopped.
2846 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2848 // Clear any temporary breakpoints we used to implement software single stepping.
2849 for (const auto &thread_info: m_threads_stepping_with_breakpoint)
2851 Error error = RemoveBreakpoint (thread_info.second);
2854 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2855 __FUNCTION__, thread_info.first, error.AsCString());
2857 m_threads_stepping_with_breakpoint.clear();
2859 // Notify the delegate about the stop
2860 SetCurrentThreadID(m_pending_notification_tid);
2861 SetState(StateType::eStateStopped, true);
2862 m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2866 NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
2868 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2871 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
2873 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
2875 // We will need to wait for this new thread to stop as well before firing the
2877 thread.RequestStop();
2882 NativeProcessLinux::SigchldHandler()
2884 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2885 // Process all pending waitpid notifications.
2889 ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2892 break; // We are done.
2899 Error error(errno, eErrorTypePOSIX);
2901 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
2902 __FUNCTION__, error.AsCString());
2906 bool exited = false;
2908 int exit_status = 0;
2909 const char *status_cstr = nullptr;
2910 if (WIFSTOPPED(status))
2912 signal = WSTOPSIG(status);
2913 status_cstr = "STOPPED";
2915 else if (WIFEXITED(status))
2917 exit_status = WEXITSTATUS(status);
2918 status_cstr = "EXITED";
2921 else if (WIFSIGNALED(status))
2923 signal = WTERMSIG(status);
2924 status_cstr = "SIGNALED";
2925 if (wait_pid == static_cast< ::pid_t>(GetID())) {
2931 status_cstr = "(\?\?\?)";
2934 log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
2935 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2936 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
2938 MonitorCallback (wait_pid, exited, signal, exit_status);
2942 // Wrapper for ptrace to catch errors and log calls.
2943 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
2945 NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
2950 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
2952 PtraceDisplayBytes(req, data, data_size);
2955 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2956 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
2958 ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
2961 error.SetErrorToErrno();
2967 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
2969 PtraceDisplayBytes(req, data, data_size);
2971 if (log && error.GetError() != 0)
2974 switch (error.GetError())
2976 case ESRCH: str = "ESRCH"; break;
2977 case EINVAL: str = "EINVAL"; break;
2978 case EBUSY: str = "EBUSY"; break;
2979 case EPERM: str = "EPERM"; break;
2980 default: str = error.AsCString();
2982 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);