xref: /llvm-project/lldb/source/Plugins/Process/Linux/NativeProcessLinux.cpp (revision b9739d4090da7812e4a3ba2fccc357a76ee80bcb)
1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "NativeProcessLinux.h"
11 
12 // C Includes
13 #include <errno.h>
14 #include <string.h>
15 #include <stdint.h>
16 #include <unistd.h>
17 
18 // C++ Includes
19 #include <fstream>
20 #include <mutex>
21 #include <sstream>
22 #include <string>
23 #include <unordered_map>
24 
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"
44 
45 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
46 #include "NativeThreadLinux.h"
47 #include "ProcFileReader.h"
48 #include "Procfs.h"
49 
50 // System includes - They have to be included after framework includes because they define some
51 // macros which collide with variable names in other modules
52 #include <linux/unistd.h>
53 #include <sys/socket.h>
54 
55 #include <sys/syscall.h>
56 #include <sys/types.h>
57 #include <sys/user.h>
58 #include <sys/wait.h>
59 
60 #include "lldb/Host/linux/Personality.h"
61 #include "lldb/Host/linux/Ptrace.h"
62 #include "lldb/Host/linux/Uio.h"
63 
64 // Support hardware breakpoints in case it has not been defined
65 #ifndef TRAP_HWBKPT
66   #define TRAP_HWBKPT 4
67 #endif
68 
69 using namespace lldb;
70 using namespace lldb_private;
71 using namespace lldb_private::process_linux;
72 using namespace llvm;
73 
74 // Private bits we only need internally.
75 
76 static bool ProcessVmReadvSupported()
77 {
78     static bool is_supported;
79     static std::once_flag flag;
80 
81     std::call_once(flag, [] {
82         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
83 
84         uint32_t source = 0x47424742;
85         uint32_t dest = 0;
86 
87         struct iovec local, remote;
88         remote.iov_base = &source;
89         local.iov_base = &dest;
90         remote.iov_len = local.iov_len = sizeof source;
91 
92         // We shall try if cross-process-memory reads work by attempting to read a 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);
95         if (log)
96         {
97             if (is_supported)
98                 log->Printf("%s: Detected kernel support for process_vm_readv syscall. Fast memory reads enabled.",
99                         __FUNCTION__);
100             else
101                 log->Printf("%s: syscall process_vm_readv failed (error: %s). Fast memory reads disabled.",
102                         __FUNCTION__, strerror(errno));
103         }
104     });
105 
106     return is_supported;
107 }
108 
109 namespace
110 {
111 Error
112 ResolveProcessArchitecture(lldb::pid_t pid, ArchSpec &arch)
113 {
114     // Grab process info for the running process.
115     ProcessInstanceInfo process_info;
116     if (!Host::GetProcessInfo(pid, process_info))
117         return Error("failed to get process info");
118 
119     // Resolve the executable module.
120     ModuleSpecList module_specs;
121     if (!ObjectFile::GetModuleSpecifications(process_info.GetExecutableFile(), 0, 0, module_specs))
122         return Error("failed to get module specifications");
123     assert(module_specs.GetSize() == 1);
124 
125     arch = module_specs.GetModuleSpecRefAtIndex(0).GetArchitecture();
126     if (arch.IsValid())
127         return Error();
128     else
129         return Error("failed to retrieve a valid architecture from the exe module");
130 }
131 
132 void
133 MaybeLogLaunchInfo(const ProcessLaunchInfo &info)
134 {
135     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
136     if (!log)
137         return;
138 
139     if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO))
140         log->Printf("%s: setting STDIN to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
141     else
142         log->Printf("%s leaving STDIN as is", __FUNCTION__);
143 
144     if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO))
145         log->Printf("%s setting STDOUT to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
146     else
147         log->Printf("%s leaving STDOUT as is", __FUNCTION__);
148 
149     if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO))
150         log->Printf("%s setting STDERR to '%s'", __FUNCTION__, action->GetFileSpec().GetCString());
151     else
152         log->Printf("%s leaving STDERR as is", __FUNCTION__);
153 
154     int i = 0;
155     for (const char **args = info.GetArguments().GetConstArgumentVector(); *args; ++args, ++i)
156         log->Printf("%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr");
157 }
158 
159 void
160 DisplayBytes(StreamString &s, void *bytes, uint32_t count)
161 {
162     uint8_t *ptr = (uint8_t *)bytes;
163     const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count);
164     for (uint32_t i = 0; i < loop_count; i++)
165     {
166         s.Printf("[%x]", *ptr);
167         ptr++;
168     }
169 }
170 
171     void
172     PtraceDisplayBytes(int &req, void *data, size_t data_size)
173     {
174         StreamString buf;
175         Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (
176                     POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE));
177 
178         if (verbose_log)
179         {
180             switch(req)
181             {
182             case PTRACE_POKETEXT:
183             {
184                 DisplayBytes(buf, &data, 8);
185                 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData());
186                 break;
187             }
188             case PTRACE_POKEDATA:
189             {
190                 DisplayBytes(buf, &data, 8);
191                 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData());
192                 break;
193             }
194             case PTRACE_POKEUSER:
195             {
196                 DisplayBytes(buf, &data, 8);
197                 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData());
198                 break;
199             }
200             case PTRACE_SETREGS:
201             {
202                 DisplayBytes(buf, data, data_size);
203                 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData());
204                 break;
205             }
206             case PTRACE_SETFPREGS:
207             {
208                 DisplayBytes(buf, data, data_size);
209                 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData());
210                 break;
211             }
212             case PTRACE_SETSIGINFO:
213             {
214                 DisplayBytes(buf, data, sizeof(siginfo_t));
215                 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData());
216                 break;
217             }
218             case PTRACE_SETREGSET:
219             {
220                 // Extract iov_base from data, which is a pointer to the struct IOVEC
221                 DisplayBytes(buf, *(void **)data, data_size);
222                 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData());
223                 break;
224             }
225             default:
226             {
227             }
228             }
229         }
230     }
231 
232     static constexpr unsigned k_ptrace_word_size = sizeof(void*);
233     static_assert(sizeof(long) >= k_ptrace_word_size, "Size of long must be larger than ptrace word size");
234 } // end of anonymous namespace
235 
236 // Simple helper function to ensure flags are enabled on the given file
237 // descriptor.
238 static Error
239 EnsureFDFlags(int fd, int flags)
240 {
241     Error error;
242 
243     int status = fcntl(fd, F_GETFL);
244     if (status == -1)
245     {
246         error.SetErrorToErrno();
247         return error;
248     }
249 
250     if (fcntl(fd, F_SETFL, status | flags) == -1)
251     {
252         error.SetErrorToErrno();
253         return error;
254     }
255 
256     return error;
257 }
258 
259 // -----------------------------------------------------------------------------
260 // Public Static Methods
261 // -----------------------------------------------------------------------------
262 
263 Error
264 NativeProcessProtocol::Launch (
265     ProcessLaunchInfo &launch_info,
266     NativeProcessProtocol::NativeDelegate &native_delegate,
267     MainLoop &mainloop,
268     NativeProcessProtocolSP &native_process_sp)
269 {
270     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
271 
272     Error error;
273 
274     // Verify the working directory is valid if one was specified.
275     FileSpec working_dir{launch_info.GetWorkingDirectory()};
276     if (working_dir &&
277             (!working_dir.ResolvePath() ||
278              working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
279     {
280         error.SetErrorStringWithFormat ("No such file or directory: %s",
281                 working_dir.GetCString());
282         return error;
283     }
284 
285     // Create the NativeProcessLinux in launch mode.
286     native_process_sp.reset (new NativeProcessLinux ());
287 
288     if (!native_process_sp->RegisterNativeDelegate (native_delegate))
289     {
290         native_process_sp.reset ();
291         error.SetErrorStringWithFormat ("failed to register the native delegate");
292         return error;
293     }
294 
295     error = std::static_pointer_cast<NativeProcessLinux>(native_process_sp)->LaunchInferior(mainloop, launch_info);
296 
297     if (error.Fail ())
298     {
299         native_process_sp.reset ();
300         if (log)
301             log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ());
302         return error;
303     }
304 
305     launch_info.SetProcessID (native_process_sp->GetID ());
306 
307     return error;
308 }
309 
310 Error
311 NativeProcessProtocol::Attach (
312     lldb::pid_t pid,
313     NativeProcessProtocol::NativeDelegate &native_delegate,
314     MainLoop &mainloop,
315     NativeProcessProtocolSP &native_process_sp)
316 {
317     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
318     if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE))
319         log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid);
320 
321     // Retrieve the architecture for the running process.
322     ArchSpec process_arch;
323     Error error = ResolveProcessArchitecture(pid, process_arch);
324     if (!error.Success ())
325         return error;
326 
327     std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ());
328 
329     if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate))
330     {
331         error.SetErrorStringWithFormat ("failed to register the native delegate");
332         return error;
333     }
334 
335     native_process_linux_sp->AttachToInferior (mainloop, pid, error);
336     if (!error.Success ())
337         return error;
338 
339     native_process_sp = native_process_linux_sp;
340     return error;
341 }
342 
343 // -----------------------------------------------------------------------------
344 // Public Instance Methods
345 // -----------------------------------------------------------------------------
346 
347 NativeProcessLinux::NativeProcessLinux () :
348     NativeProcessProtocol (LLDB_INVALID_PROCESS_ID),
349     m_arch (),
350     m_supports_mem_region (eLazyBoolCalculate),
351     m_mem_region_cache (),
352     m_pending_notification_tid(LLDB_INVALID_THREAD_ID)
353 {
354 }
355 
356 void
357 NativeProcessLinux::AttachToInferior (MainLoop &mainloop, lldb::pid_t pid, Error &error)
358 {
359     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
360     if (log)
361         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid);
362 
363     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD,
364             [this] (MainLoopBase &) { SigchldHandler(); }, error);
365     if (! m_sigchld_handle)
366         return;
367 
368     error = ResolveProcessArchitecture(pid, m_arch);
369     if (!error.Success())
370         return;
371 
372     // Set the architecture to the exe architecture.
373     if (log)
374         log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ());
375 
376     m_pid = pid;
377     SetState(eStateAttaching);
378 
379     Attach(pid, error);
380 }
381 
382 Error
383 NativeProcessLinux::LaunchInferior(MainLoop &mainloop, ProcessLaunchInfo &launch_info)
384 {
385     Error error;
386     m_sigchld_handle = mainloop.RegisterSignal(SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, error);
387     if (!m_sigchld_handle)
388         return error;
389 
390     SetState(eStateLaunching);
391 
392     MaybeLogLaunchInfo(launch_info);
393 
394     ::pid_t pid = ProcessLauncherLinux().LaunchProcess(launch_info, error).GetProcessId();
395     if (error.Fail())
396         return error;
397 
398     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
399 
400     // Wait for the child process to trap on its call to execve.
401     ::pid_t wpid;
402     int status;
403     if ((wpid = waitpid(pid, &status, 0)) < 0)
404     {
405         error.SetErrorToErrno();
406         if (log)
407             log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s",
408                     __FUNCTION__, error.AsCString ());
409 
410         // Mark the inferior as invalid.
411         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
412         SetState (StateType::eStateInvalid);
413 
414         return error;
415     }
416     assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) &&
417            "Could not sync with inferior process.");
418 
419     if (log)
420         log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__);
421 
422     error = SetDefaultPtraceOpts(pid);
423     if (error.Fail())
424     {
425         if (log)
426             log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s",
427                     __FUNCTION__, error.AsCString ());
428 
429         // Mark the inferior as invalid.
430         // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
431         SetState (StateType::eStateInvalid);
432 
433         return error;
434     }
435 
436     // Release the master terminal descriptor and pass it off to the
437     // NativeProcessLinux instance.  Similarly stash the inferior pid.
438     m_terminal_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
439     m_pid = pid;
440     launch_info.SetProcessID(pid);
441 
442     if (m_terminal_fd != -1)
443     {
444         error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
445         if (error.Fail())
446         {
447             if (log)
448                 log->Printf(
449                     "NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s",
450                     __FUNCTION__, error.AsCString());
451 
452             // Mark the inferior as invalid.
453             // FIXME this could really use a new state - eStateLaunchFailure.  For now, using eStateInvalid.
454             SetState(StateType::eStateInvalid);
455 
456             return error;
457         }
458     }
459 
460     if (log)
461         log->Printf("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, uint64_t(pid));
462 
463     ResolveProcessArchitecture(m_pid, m_arch);
464     NativeThreadLinuxSP thread_sp = AddThread(pid);
465     assert (thread_sp && "AddThread() returned a nullptr thread");
466     thread_sp->SetStoppedBySignal(SIGSTOP);
467     ThreadWasCreated(*thread_sp);
468 
469     // Let our process instance know the thread has stopped.
470     SetCurrentThreadID (thread_sp->GetID ());
471     SetState (StateType::eStateStopped);
472 
473     if (log)
474     {
475         if (error.Success ())
476             log->Printf("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__);
477         else
478             log->Printf("NativeProcessLinux::%s inferior launching failed: %s", __FUNCTION__, error.AsCString());
479     }
480     return error;
481 }
482 
483 ::pid_t
484 NativeProcessLinux::Attach(lldb::pid_t pid, Error &error)
485 {
486     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
487 
488     // Use a map to keep track of the threads which we have attached/need to attach.
489     Host::TidMap tids_to_attach;
490     if (pid <= 1)
491     {
492         error.SetErrorToGenericError();
493         error.SetErrorString("Attaching to process 1 is not allowed.");
494         return -1;
495     }
496 
497     while (Host::FindProcessThreads(pid, tids_to_attach))
498     {
499         for (Host::TidMap::iterator it = tids_to_attach.begin();
500              it != tids_to_attach.end();)
501         {
502             if (it->second == false)
503             {
504                 lldb::tid_t tid = it->first;
505 
506                 // Attach to the requested process.
507                 // An attach will cause the thread to stop with a SIGSTOP.
508                 error = PtraceWrapper(PTRACE_ATTACH, tid);
509                 if (error.Fail())
510                 {
511                     // No such thread. The thread may have exited.
512                     // More error handling may be needed.
513                     if (error.GetError() == ESRCH)
514                     {
515                         it = tids_to_attach.erase(it);
516                         continue;
517                     }
518                     else
519                         return -1;
520                 }
521 
522                 int status;
523                 // Need to use __WALL otherwise we receive an error with errno=ECHLD
524                 // At this point we should have a thread stopped if waitpid succeeds.
525                 if ((status = waitpid(tid, NULL, __WALL)) < 0)
526                 {
527                     // No such thread. The thread may have exited.
528                     // More error handling may be needed.
529                     if (errno == ESRCH)
530                     {
531                         it = tids_to_attach.erase(it);
532                         continue;
533                     }
534                     else
535                     {
536                         error.SetErrorToErrno();
537                         return -1;
538                     }
539                 }
540 
541                 error = SetDefaultPtraceOpts(tid);
542                 if (error.Fail())
543                     return -1;
544 
545                 if (log)
546                     log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid);
547 
548                 it->second = true;
549 
550                 // Create the thread, mark it as stopped.
551                 NativeThreadLinuxSP thread_sp (AddThread(static_cast<lldb::tid_t>(tid)));
552                 assert (thread_sp && "AddThread() returned a nullptr");
553 
554                 // This will notify this is a new thread and tell the system it is stopped.
555                 thread_sp->SetStoppedBySignal(SIGSTOP);
556                 ThreadWasCreated(*thread_sp);
557                 SetCurrentThreadID (thread_sp->GetID ());
558             }
559 
560             // move the loop forward
561             ++it;
562         }
563     }
564 
565     if (tids_to_attach.size() > 0)
566     {
567         m_pid = pid;
568         // Let our process instance know the thread has stopped.
569         SetState (StateType::eStateStopped);
570     }
571     else
572     {
573         error.SetErrorToGenericError();
574         error.SetErrorString("No such process.");
575         return -1;
576     }
577 
578     return pid;
579 }
580 
581 Error
582 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid)
583 {
584     long ptrace_opts = 0;
585 
586     // Have the child raise an event on exit.  This is used to keep the child in
587     // limbo until it is destroyed.
588     ptrace_opts |= PTRACE_O_TRACEEXIT;
589 
590     // Have the tracer trace threads which spawn in the inferior process.
591     // TODO: if we want to support tracing the inferiors' child, add the
592     // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK)
593     ptrace_opts |= PTRACE_O_TRACECLONE;
594 
595     // Have the tracer notify us before execve returns
596     // (needed to disable legacy SIGTRAP generation)
597     ptrace_opts |= PTRACE_O_TRACEEXEC;
598 
599     return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts);
600 }
601 
602 static ExitType convert_pid_status_to_exit_type (int status)
603 {
604     if (WIFEXITED (status))
605         return ExitType::eExitTypeExit;
606     else if (WIFSIGNALED (status))
607         return ExitType::eExitTypeSignal;
608     else if (WIFSTOPPED (status))
609         return ExitType::eExitTypeStop;
610     else
611     {
612         // We don't know what this is.
613         return ExitType::eExitTypeInvalid;
614     }
615 }
616 
617 static int convert_pid_status_to_return_code (int status)
618 {
619     if (WIFEXITED (status))
620         return WEXITSTATUS (status);
621     else if (WIFSIGNALED (status))
622         return WTERMSIG (status);
623     else if (WIFSTOPPED (status))
624         return WSTOPSIG (status);
625     else
626     {
627         // We don't know what this is.
628         return ExitType::eExitTypeInvalid;
629     }
630 }
631 
632 // Handles all waitpid events from the inferior process.
633 void
634 NativeProcessLinux::MonitorCallback(lldb::pid_t pid,
635                                     bool exited,
636                                     int signal,
637                                     int status)
638 {
639     Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS));
640 
641     // Certain activities differ based on whether the pid is the tid of the main thread.
642     const bool is_main_thread = (pid == GetID ());
643 
644     // Handle when the thread exits.
645     if (exited)
646     {
647         if (log)
648             log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %"  PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not");
649 
650         // This is a thread that exited.  Ensure we're not tracking it anymore.
651         const bool thread_found = StopTrackingThread (pid);
652 
653         if (is_main_thread)
654         {
655             // We only set the exit status and notify the delegate if we haven't already set the process
656             // state to an exited state.  We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8)
657             // for the main thread.
658             const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed);
659             if (!already_notified)
660             {
661                 if (log)
662                     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 ()));
663                 // The main thread exited.  We're done monitoring.  Report to delegate.
664                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
665 
666                 // Notify delegate that our process has exited.
667                 SetState (StateType::eStateExited, true);
668             }
669             else
670             {
671                 if (log)
672                     log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
673             }
674         }
675         else
676         {
677             // Do we want to report to the delegate in this case?  I think not.  If this was an orderly
678             // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal,
679             // and we would have done an all-stop then.
680             if (log)
681                 log->Printf ("NativeProcessLinux::%s() tid = %"  PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found");
682         }
683         return;
684     }
685 
686     siginfo_t info;
687     const auto info_err = GetSignalInfo(pid, &info);
688     auto thread_sp = GetThreadByID(pid);
689 
690     if (! thread_sp)
691     {
692         // Normally, the only situation when we cannot find the thread is if we have just
693         // received a new thread notification. This is indicated by GetSignalInfo() returning
694         // si_code == SI_USER and si_pid == 0
695         if (log)
696             log->Printf("NativeProcessLinux::%s received notification about an unknown tid %" PRIu64 ".", __FUNCTION__, pid);
697 
698         if (info_err.Fail())
699         {
700             if (log)
701                 log->Printf("NativeProcessLinux::%s (tid %" PRIu64 ") GetSignalInfo failed (%s). Ingoring this notification.", __FUNCTION__, pid, info_err.AsCString());
702             return;
703         }
704 
705         if (log && (info.si_code != SI_USER || info.si_pid != 0))
706             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);
707 
708         auto thread_sp = AddThread(pid);
709         // Resume the newly created thread.
710         ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
711         ThreadWasCreated(*thread_sp);
712         return;
713     }
714 
715     // Get details on the signal raised.
716     if (info_err.Success())
717     {
718         // We have retrieved the signal info.  Dispatch appropriately.
719         if (info.si_signo == SIGTRAP)
720             MonitorSIGTRAP(info, *thread_sp);
721         else
722             MonitorSignal(info, *thread_sp, exited);
723     }
724     else
725     {
726         if (info_err.GetError() == EINVAL)
727         {
728             // This is a group stop reception for this tid.
729             // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the
730             // tracee, triggering the group-stop mechanism. Normally receiving these would stop
731             // the process, pending a SIGCONT. Simulating this state in a debugger is hard and is
732             // generally not needed (one use case is debugging background task being managed by a
733             // shell). For general use, it is sufficient to stop the process in a signal-delivery
734             // stop which happens before the group stop. This done by MonitorSignal and works
735             // correctly for all signals.
736             if (log)
737                 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);
738             ResumeThread(*thread_sp, thread_sp->GetState(), LLDB_INVALID_SIGNAL_NUMBER);
739         }
740         else
741         {
742             // ptrace(GETSIGINFO) failed (but not due to group-stop).
743 
744             // A return value of ESRCH means the thread/process is no longer on the system,
745             // so it was killed somehow outside of our control.  Either way, we can't do anything
746             // with it anymore.
747 
748             // Stop tracking the metadata for the thread since it's entirely off the system now.
749             const bool thread_found = StopTrackingThread (pid);
750 
751             if (log)
752                 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)",
753                              __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");
754 
755             if (is_main_thread)
756             {
757                 // Notify the delegate - our process is not available but appears to have been killed outside
758                 // our control.  Is eStateExited the right exit state in this case?
759                 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true);
760                 SetState (StateType::eStateExited, true);
761             }
762             else
763             {
764                 // This thread was pulled out from underneath us.  Anything to do here? Do we want to do an all stop?
765                 if (log)
766                     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);
767             }
768         }
769     }
770 }
771 
772 void
773 NativeProcessLinux::WaitForNewThread(::pid_t tid)
774 {
775     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
776 
777     NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid);
778 
779     if (new_thread_sp)
780     {
781         // We are already tracking the thread - we got the event on the new thread (see
782         // MonitorSignal) before this one. We are done.
783         return;
784     }
785 
786     // The thread is not tracked yet, let's wait for it to appear.
787     int status = -1;
788     ::pid_t wait_pid;
789     do
790     {
791         if (log)
792             log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid);
793         wait_pid = waitpid(tid, &status, __WALL);
794     }
795     while (wait_pid == -1 && errno == EINTR);
796     // Since we are waiting on a specific tid, this must be the creation event. But let's do
797     // some checks just in case.
798     if (wait_pid != tid) {
799         if (log)
800             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid);
801         // The only way I know of this could happen is if the whole process was
802         // SIGKILLed in the mean time. In any case, we can't do anything about that now.
803         return;
804     }
805     if (WIFEXITED(status))
806     {
807         if (log)
808             log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid);
809         // Also a very improbable event.
810         return;
811     }
812 
813     siginfo_t info;
814     Error error = GetSignalInfo(tid, &info);
815     if (error.Fail())
816     {
817         if (log)
818             log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid);
819         return;
820     }
821 
822     if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log)
823     {
824         // We should be getting a thread creation signal here, but we received something
825         // else. There isn't much we can do about it now, so we will just log that. Since the
826         // thread is alive and we are receiving events from it, we shall pretend that it was
827         // created properly.
828         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);
829     }
830 
831     if (log)
832         log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32,
833                  __FUNCTION__, GetID (), tid);
834 
835     new_thread_sp = AddThread(tid);
836     ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER);
837     ThreadWasCreated(*new_thread_sp);
838 }
839 
840 void
841 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, NativeThreadLinux &thread)
842 {
843     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
844     const bool is_main_thread = (thread.GetID() == GetID ());
845 
846     assert(info.si_signo == SIGTRAP && "Unexpected child signal!");
847 
848     switch (info.si_code)
849     {
850     // TODO: these two cases are required if we want to support tracing of the inferiors' children.  We'd need this to debug a monitor.
851     // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)):
852     // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)):
853 
854     case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)):
855     {
856         // This is the notification on the parent thread which informs us of new thread
857         // creation.
858         // We don't want to do anything with the parent thread so we just resume it. In case we
859         // want to implement "break on thread creation" functionality, we would need to stop
860         // here.
861 
862         unsigned long event_message = 0;
863         if (GetEventMessage(thread.GetID(), &event_message).Fail())
864         {
865             if (log)
866                 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, thread.GetID());
867         } else
868             WaitForNewThread(event_message);
869 
870         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
871         break;
872     }
873 
874     case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)):
875     {
876         NativeThreadLinuxSP main_thread_sp;
877         if (log)
878             log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info.si_code ^ SIGTRAP);
879 
880         // Exec clears any pending notifications.
881         m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
882 
883         // Remove all but the main thread here.  Linux fork creates a new process which only copies the main thread.
884         if (log)
885             log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__);
886 
887         for (auto thread_sp : m_threads)
888         {
889             const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID ();
890             if (is_main_thread)
891             {
892                 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp);
893                 if (log)
894                     log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ());
895             }
896             else
897             {
898                 if (log)
899                     log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ());
900             }
901         }
902 
903         m_threads.clear ();
904 
905         if (main_thread_sp)
906         {
907             m_threads.push_back (main_thread_sp);
908             SetCurrentThreadID (main_thread_sp->GetID ());
909             main_thread_sp->SetStoppedByExec();
910         }
911         else
912         {
913             SetCurrentThreadID (LLDB_INVALID_THREAD_ID);
914             if (log)
915                 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ());
916         }
917 
918         // Tell coordinator about about the "new" (since exec) stopped main thread.
919         ThreadWasCreated(*main_thread_sp);
920 
921         // Let our delegate know we have just exec'd.
922         NotifyDidExec ();
923 
924         // If we have a main thread, indicate we are stopped.
925         assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked");
926 
927         // Let the process know we're stopped.
928         StopRunningThreads(main_thread_sp->GetID());
929 
930         break;
931     }
932 
933     case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)):
934     {
935         // The inferior process or one of its threads is about to exit.
936         // We don't want to do anything with the thread so we just resume it. In case we
937         // want to implement "break on thread exit" functionality, we would need to stop
938         // here.
939 
940         unsigned long data = 0;
941         if (GetEventMessage(thread.GetID(), &data).Fail())
942             data = -1;
943 
944         if (log)
945         {
946             log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)",
947                          __FUNCTION__,
948                          data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false",
949                          thread.GetID(),
950                     is_main_thread ? "is main thread" : "not main thread");
951         }
952 
953         if (is_main_thread)
954         {
955             SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true);
956         }
957 
958         StateType state = thread.GetState();
959         if (! StateIsRunningState(state))
960         {
961             // Due to a kernel bug, we may sometimes get this stop after the inferior gets a
962             // SIGKILL. This confuses our state tracking logic in ResumeThread(), since normally,
963             // we should not be receiving any ptrace events while the inferior is stopped. This
964             // makes sure that the inferior is resumed and exits normally.
965             state = eStateRunning;
966         }
967         ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER);
968 
969         break;
970     }
971 
972     case 0:
973     case TRAP_TRACE:  // We receive this on single stepping.
974     case TRAP_HWBKPT: // We receive this on watchpoint hit
975     {
976         // If a watchpoint was hit, report it
977         uint32_t wp_index;
978         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, (uintptr_t)info.si_addr);
979         if (error.Fail() && log)
980             log->Printf("NativeProcessLinux::%s() "
981                         "received error while checking for watchpoint hits, "
982                         "pid = %" PRIu64 " error = %s",
983                         __FUNCTION__, thread.GetID(), error.AsCString());
984         if (wp_index != LLDB_INVALID_INDEX32)
985         {
986             MonitorWatchpoint(thread, wp_index);
987             break;
988         }
989 
990         // Otherwise, report step over
991         MonitorTrace(thread);
992         break;
993     }
994 
995     case SI_KERNEL:
996 #if defined __mips__
997         // For mips there is no special signal for watchpoint
998         // So we check for watchpoint in kernel trap
999     {
1000         // If a watchpoint was hit, report it
1001         uint32_t wp_index;
1002         Error error = thread.GetRegisterContext()->GetWatchpointHitIndex(wp_index, LLDB_INVALID_ADDRESS);
1003         if (error.Fail() && log)
1004             log->Printf("NativeProcessLinux::%s() "
1005                         "received error while checking for watchpoint hits, "
1006                         "pid = %" PRIu64 " error = %s",
1007                         __FUNCTION__, thread.GetID(), error.AsCString());
1008         if (wp_index != LLDB_INVALID_INDEX32)
1009         {
1010             MonitorWatchpoint(thread, wp_index);
1011             break;
1012         }
1013     }
1014         // NO BREAK
1015 #endif
1016     case TRAP_BRKPT:
1017         MonitorBreakpoint(thread);
1018         break;
1019 
1020     case SIGTRAP:
1021     case (SIGTRAP | 0x80):
1022         if (log)
1023             log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), thread.GetID());
1024 
1025         // Ignore these signals until we know more about them.
1026         ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER);
1027         break;
1028 
1029     default:
1030         assert(false && "Unexpected SIGTRAP code!");
1031         if (log)
1032             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 "tid %" PRIu64 " received unhandled SIGTRAP code: 0x%d",
1033                     __FUNCTION__, GetID(), thread.GetID(), info.si_code);
1034         break;
1035 
1036     }
1037 }
1038 
1039 void
1040 NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread)
1041 {
1042     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1043     if (log)
1044         log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)",
1045                 __FUNCTION__, thread.GetID());
1046 
1047     // This thread is currently stopped.
1048     thread.SetStoppedByTrace();
1049 
1050     StopRunningThreads(thread.GetID());
1051 }
1052 
1053 void
1054 NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread)
1055 {
1056     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
1057     if (log)
1058         log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64,
1059                 __FUNCTION__, thread.GetID());
1060 
1061     // Mark the thread as stopped at breakpoint.
1062     thread.SetStoppedByBreakpoint();
1063     Error error = FixupBreakpointPCAsNeeded(thread);
1064     if (error.Fail())
1065         if (log)
1066             log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s",
1067                     __FUNCTION__, thread.GetID(), error.AsCString());
1068 
1069     if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != m_threads_stepping_with_breakpoint.end())
1070         thread.SetStoppedByTrace();
1071 
1072     StopRunningThreads(thread.GetID());
1073 }
1074 
1075 void
1076 NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, uint32_t wp_index)
1077 {
1078     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS));
1079     if (log)
1080         log->Printf("NativeProcessLinux::%s() received watchpoint event, "
1081                     "pid = %" PRIu64 ", wp_index = %" PRIu32,
1082                     __FUNCTION__, thread.GetID(), wp_index);
1083 
1084     // Mark the thread as stopped at watchpoint.
1085     // The address is at (lldb::addr_t)info->si_addr if we need it.
1086     thread.SetStoppedByWatchpoint(wp_index);
1087 
1088     // We need to tell all other running threads before we notify the delegate about this stop.
1089     StopRunningThreads(thread.GetID());
1090 }
1091 
1092 void
1093 NativeProcessLinux::MonitorSignal(const siginfo_t &info, NativeThreadLinux &thread, bool exited)
1094 {
1095     const int signo = info.si_signo;
1096     const bool is_from_llgs = info.si_pid == getpid ();
1097 
1098     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1099 
1100     // POSIX says that process behaviour is undefined after it ignores a SIGFPE,
1101     // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a
1102     // kill(2) or raise(3).  Similarly for tgkill(2) on Linux.
1103     //
1104     // IOW, user generated signals never generate what we consider to be a
1105     // "crash".
1106     //
1107     // Similarly, ACK signals generated by this monitor.
1108 
1109     // Handle the signal.
1110     if (info.si_code == SI_TKILL || info.si_code == SI_USER)
1111     {
1112         if (log)
1113             log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")",
1114                             __FUNCTION__,
1115                             Host::GetSignalAsCString(signo),
1116                             signo,
1117                             (info.si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"),
1118                             info.si_pid,
1119                             is_from_llgs ? "from llgs" : "not from llgs",
1120                             thread.GetID());
1121     }
1122 
1123     // Check for thread stop notification.
1124     if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP))
1125     {
1126         // This is a tgkill()-based stop.
1127         if (log)
1128             log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped",
1129                          __FUNCTION__,
1130                          GetID (),
1131                          thread.GetID());
1132 
1133         // Check that we're not already marked with a stop reason.
1134         // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that
1135         // the kernel signaled us with the thread stopping which we handled and marked as stopped,
1136         // and that, without an intervening resume, we received another stop.  It is more likely
1137         // that we are missing the marking of a run state somewhere if we find that the thread was
1138         // marked as stopped.
1139         const StateType thread_state = thread.GetState();
1140         if (!StateIsStoppedState (thread_state, false))
1141         {
1142             // An inferior thread has stopped because of a SIGSTOP we have sent it.
1143             // Generally, these are not important stops and we don't want to report them as
1144             // they are just used to stop other threads when one thread (the one with the
1145             // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the
1146             // case of an asynchronous Interrupt(), this *is* the real stop reason, so we
1147             // leave the signal intact if this is the thread that was chosen as the
1148             // triggering thread.
1149             if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID)
1150             {
1151                 if (m_pending_notification_tid == thread.GetID())
1152                     thread.SetStoppedBySignal(SIGSTOP, &info);
1153                 else
1154                     thread.SetStoppedWithNoReason();
1155 
1156                 SetCurrentThreadID (thread.GetID ());
1157                 SignalIfAllThreadsStopped();
1158             }
1159             else
1160             {
1161                 // We can end up here if stop was initiated by LLGS but by this time a
1162                 // thread stop has occurred - maybe initiated by another event.
1163                 Error error = ResumeThread(thread, thread.GetState(), 0);
1164                 if (error.Fail() && log)
1165                 {
1166                     log->Printf("NativeProcessLinux::%s failed to resume thread tid  %" PRIu64 ": %s",
1167                             __FUNCTION__, thread.GetID(), error.AsCString());
1168                 }
1169             }
1170         }
1171         else
1172         {
1173             if (log)
1174             {
1175                 // Retrieve the signal name if the thread was stopped by a signal.
1176                 int stop_signo = 0;
1177                 const bool stopped_by_signal = thread.IsStopped(&stop_signo);
1178                 const char *signal_name = stopped_by_signal ? Host::GetSignalAsCString(stop_signo) : "<not stopped by signal>";
1179                 if (!signal_name)
1180                     signal_name = "<no-signal-name>";
1181 
1182                 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",
1183                              __FUNCTION__,
1184                              GetID (),
1185                              thread.GetID(),
1186                              StateAsCString (thread_state),
1187                              stop_signo,
1188                              signal_name);
1189             }
1190             SignalIfAllThreadsStopped();
1191         }
1192 
1193         // Done handling.
1194         return;
1195     }
1196 
1197     if (log)
1198         log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, Host::GetSignalAsCString(signo));
1199 
1200     // This thread is stopped.
1201     thread.SetStoppedBySignal(signo, &info);
1202 
1203     // Send a stop to the debugger after we get all other threads to stop.
1204     StopRunningThreads(thread.GetID());
1205 }
1206 
1207 namespace {
1208 
1209 struct EmulatorBaton
1210 {
1211     NativeProcessLinux* m_process;
1212     NativeRegisterContext* m_reg_context;
1213 
1214     // eRegisterKindDWARF -> RegsiterValue
1215     std::unordered_map<uint32_t, RegisterValue> m_register_values;
1216 
1217     EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) :
1218             m_process(process), m_reg_context(reg_context) {}
1219 };
1220 
1221 } // anonymous namespace
1222 
1223 static size_t
1224 ReadMemoryCallback (EmulateInstruction *instruction,
1225                     void *baton,
1226                     const EmulateInstruction::Context &context,
1227                     lldb::addr_t addr,
1228                     void *dst,
1229                     size_t length)
1230 {
1231     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1232 
1233     size_t bytes_read;
1234     emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read);
1235     return bytes_read;
1236 }
1237 
1238 static bool
1239 ReadRegisterCallback (EmulateInstruction *instruction,
1240                       void *baton,
1241                       const RegisterInfo *reg_info,
1242                       RegisterValue &reg_value)
1243 {
1244     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1245 
1246     auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]);
1247     if (it != emulator_baton->m_register_values.end())
1248     {
1249         reg_value = it->second;
1250         return true;
1251     }
1252 
1253     // The emulator only fill in the dwarf regsiter numbers (and in some case
1254     // the generic register numbers). Get the full register info from the
1255     // register context based on the dwarf register numbers.
1256     const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo(
1257             eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
1258 
1259     Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
1260     if (error.Success())
1261         return true;
1262 
1263     return false;
1264 }
1265 
1266 static bool
1267 WriteRegisterCallback (EmulateInstruction *instruction,
1268                        void *baton,
1269                        const EmulateInstruction::Context &context,
1270                        const RegisterInfo *reg_info,
1271                        const RegisterValue &reg_value)
1272 {
1273     EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton);
1274     emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value;
1275     return true;
1276 }
1277 
1278 static size_t
1279 WriteMemoryCallback (EmulateInstruction *instruction,
1280                      void *baton,
1281                      const EmulateInstruction::Context &context,
1282                      lldb::addr_t addr,
1283                      const void *dst,
1284                      size_t length)
1285 {
1286     return length;
1287 }
1288 
1289 static lldb::addr_t
1290 ReadFlags (NativeRegisterContext* regsiter_context)
1291 {
1292     const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo(
1293             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1294     return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS);
1295 }
1296 
1297 Error
1298 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread)
1299 {
1300     Error error;
1301     NativeRegisterContextSP register_context_sp = thread.GetRegisterContext();
1302 
1303     std::unique_ptr<EmulateInstruction> emulator_ap(
1304         EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr));
1305 
1306     if (emulator_ap == nullptr)
1307         return Error("Instruction emulator not found!");
1308 
1309     EmulatorBaton baton(this, register_context_sp.get());
1310     emulator_ap->SetBaton(&baton);
1311     emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1312     emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1313     emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1314     emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1315 
1316     if (!emulator_ap->ReadInstruction())
1317         return Error("Read instruction failed!");
1318 
1319     bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1320 
1321     const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1322     const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS);
1323 
1324     auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1325     auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]);
1326 
1327     lldb::addr_t next_pc;
1328     lldb::addr_t next_flags;
1329     if (emulation_result)
1330     {
1331         assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated");
1332         next_pc = pc_it->second.GetAsUInt64();
1333 
1334         if (flags_it != baton.m_register_values.end())
1335             next_flags = flags_it->second.GetAsUInt64();
1336         else
1337             next_flags = ReadFlags (register_context_sp.get());
1338     }
1339     else if (pc_it == baton.m_register_values.end())
1340     {
1341         // Emulate instruction failed and it haven't changed PC. Advance PC
1342         // with the size of the current opcode because the emulation of all
1343         // PC modifying instruction should be successful. The failure most
1344         // likely caused by a not supported instruction which don't modify PC.
1345         next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1346         next_flags = ReadFlags (register_context_sp.get());
1347     }
1348     else
1349     {
1350         // The instruction emulation failed after it modified the PC. It is an
1351         // unknown error where we can't continue because the next instruction is
1352         // modifying the PC but we don't  know how.
1353         return Error ("Instruction emulation failed unexpectedly.");
1354     }
1355 
1356     if (m_arch.GetMachine() == llvm::Triple::arm)
1357     {
1358         if (next_flags & 0x20)
1359         {
1360             // Thumb mode
1361             error = SetSoftwareBreakpoint(next_pc, 2);
1362         }
1363         else
1364         {
1365             // Arm mode
1366             error = SetSoftwareBreakpoint(next_pc, 4);
1367         }
1368     }
1369     else if (m_arch.GetMachine() == llvm::Triple::mips64
1370             || m_arch.GetMachine() == llvm::Triple::mips64el
1371             || m_arch.GetMachine() == llvm::Triple::mips
1372             || m_arch.GetMachine() == llvm::Triple::mipsel)
1373         error = SetSoftwareBreakpoint(next_pc, 4);
1374     else
1375     {
1376         // No size hint is given for the next breakpoint
1377         error = SetSoftwareBreakpoint(next_pc, 0);
1378     }
1379 
1380     if (error.Fail())
1381         return error;
1382 
1383     m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc});
1384 
1385     return Error();
1386 }
1387 
1388 bool
1389 NativeProcessLinux::SupportHardwareSingleStepping() const
1390 {
1391     if (m_arch.GetMachine() == llvm::Triple::arm
1392         || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el
1393         || m_arch.GetMachine() == llvm::Triple::mips || m_arch.GetMachine() == llvm::Triple::mipsel)
1394         return false;
1395     return true;
1396 }
1397 
1398 Error
1399 NativeProcessLinux::Resume (const ResumeActionList &resume_actions)
1400 {
1401     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
1402     if (log)
1403         log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ());
1404 
1405     bool software_single_step = !SupportHardwareSingleStepping();
1406 
1407     if (software_single_step)
1408     {
1409         for (auto thread_sp : m_threads)
1410         {
1411             assert (thread_sp && "thread list should not contain NULL threads");
1412 
1413             const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1414             if (action == nullptr)
1415                 continue;
1416 
1417             if (action->state == eStateStepping)
1418             {
1419                 Error error = SetupSoftwareSingleStepping(static_cast<NativeThreadLinux &>(*thread_sp));
1420                 if (error.Fail())
1421                     return error;
1422             }
1423         }
1424     }
1425 
1426     for (auto thread_sp : m_threads)
1427     {
1428         assert (thread_sp && "thread list should not contain NULL threads");
1429 
1430         const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true);
1431 
1432         if (action == nullptr)
1433         {
1434             if (log)
1435                 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64,
1436                     __FUNCTION__, GetID (), thread_sp->GetID ());
1437             continue;
1438         }
1439 
1440         if (log)
1441         {
1442             log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64,
1443                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1444         }
1445 
1446         switch (action->state)
1447         {
1448         case eStateRunning:
1449         case eStateStepping:
1450         {
1451             // Run the thread, possibly feeding it the signal.
1452             const int signo = action->signal;
1453             ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, signo);
1454             break;
1455         }
1456 
1457         case eStateSuspended:
1458         case eStateStopped:
1459             lldbassert(0 && "Unexpected state");
1460 
1461         default:
1462             return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64,
1463                     __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ());
1464         }
1465     }
1466 
1467     return Error();
1468 }
1469 
1470 Error
1471 NativeProcessLinux::Halt ()
1472 {
1473     Error error;
1474 
1475     if (kill (GetID (), SIGSTOP) != 0)
1476         error.SetErrorToErrno ();
1477 
1478     return error;
1479 }
1480 
1481 Error
1482 NativeProcessLinux::Detach ()
1483 {
1484     Error error;
1485 
1486     // Stop monitoring the inferior.
1487     m_sigchld_handle.reset();
1488 
1489     // Tell ptrace to detach from the process.
1490     if (GetID () == LLDB_INVALID_PROCESS_ID)
1491         return error;
1492 
1493     for (auto thread_sp : m_threads)
1494     {
1495         Error e = Detach(thread_sp->GetID());
1496         if (e.Fail())
1497             error = e; // Save the error, but still attempt to detach from other threads.
1498     }
1499 
1500     return error;
1501 }
1502 
1503 Error
1504 NativeProcessLinux::Signal (int signo)
1505 {
1506     Error error;
1507 
1508     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1509     if (log)
1510         log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64,
1511                 __FUNCTION__, signo, Host::GetSignalAsCString(signo), GetID());
1512 
1513     if (kill(GetID(), signo))
1514         error.SetErrorToErrno();
1515 
1516     return error;
1517 }
1518 
1519 Error
1520 NativeProcessLinux::Interrupt ()
1521 {
1522     // Pick a running thread (or if none, a not-dead stopped thread) as
1523     // the chosen thread that will be the stop-reason thread.
1524     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1525 
1526     NativeThreadProtocolSP running_thread_sp;
1527     NativeThreadProtocolSP stopped_thread_sp;
1528 
1529     if (log)
1530         log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__);
1531 
1532     for (auto thread_sp : m_threads)
1533     {
1534         // The thread shouldn't be null but lets just cover that here.
1535         if (!thread_sp)
1536             continue;
1537 
1538         // If we have a running or stepping thread, we'll call that the
1539         // target of the interrupt.
1540         const auto thread_state = thread_sp->GetState ();
1541         if (thread_state == eStateRunning ||
1542             thread_state == eStateStepping)
1543         {
1544             running_thread_sp = thread_sp;
1545             break;
1546         }
1547         else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true))
1548         {
1549             // Remember the first non-dead stopped thread.  We'll use that as a backup if there are no running threads.
1550             stopped_thread_sp = thread_sp;
1551         }
1552     }
1553 
1554     if (!running_thread_sp && !stopped_thread_sp)
1555     {
1556         Error error("found no running/stepping or live stopped threads as target for interrupt");
1557         if (log)
1558             log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ());
1559 
1560         return error;
1561     }
1562 
1563     NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp;
1564 
1565     if (log)
1566         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target",
1567                      __FUNCTION__,
1568                      GetID (),
1569                      running_thread_sp ? "running" : "stopped",
1570                      deferred_signal_thread_sp->GetID ());
1571 
1572     StopRunningThreads(deferred_signal_thread_sp->GetID());
1573 
1574     return Error();
1575 }
1576 
1577 Error
1578 NativeProcessLinux::Kill ()
1579 {
1580     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1581     if (log)
1582         log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ());
1583 
1584     Error error;
1585 
1586     switch (m_state)
1587     {
1588         case StateType::eStateInvalid:
1589         case StateType::eStateExited:
1590         case StateType::eStateCrashed:
1591         case StateType::eStateDetached:
1592         case StateType::eStateUnloaded:
1593             // Nothing to do - the process is already dead.
1594             if (log)
1595                 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state));
1596             return error;
1597 
1598         case StateType::eStateConnected:
1599         case StateType::eStateAttaching:
1600         case StateType::eStateLaunching:
1601         case StateType::eStateStopped:
1602         case StateType::eStateRunning:
1603         case StateType::eStateStepping:
1604         case StateType::eStateSuspended:
1605             // We can try to kill a process in these states.
1606             break;
1607     }
1608 
1609     if (kill (GetID (), SIGKILL) != 0)
1610     {
1611         error.SetErrorToErrno ();
1612         return error;
1613     }
1614 
1615     return error;
1616 }
1617 
1618 static Error
1619 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info)
1620 {
1621     memory_region_info.Clear();
1622 
1623     StringExtractor line_extractor (maps_line.c_str ());
1624 
1625     // Format: {address_start_hex}-{address_end_hex} perms offset  dev   inode   pathname
1626     // perms: rwxp   (letter is present if set, '-' if not, final character is p=private, s=shared).
1627 
1628     // Parse out the starting address
1629     lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0);
1630 
1631     // Parse out hyphen separating start and end address from range.
1632     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-'))
1633         return Error ("malformed /proc/{pid}/maps entry, missing dash between address range");
1634 
1635     // Parse out the ending address
1636     lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address);
1637 
1638     // Parse out the space after the address.
1639     if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' '))
1640         return Error ("malformed /proc/{pid}/maps entry, missing space after range");
1641 
1642     // Save the range.
1643     memory_region_info.GetRange ().SetRangeBase (start_address);
1644     memory_region_info.GetRange ().SetRangeEnd (end_address);
1645 
1646     // Any memory region in /proc/{pid}/maps is by definition mapped into the process.
1647     memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
1648 
1649     // Parse out each permission entry.
1650     if (line_extractor.GetBytesLeft () < 4)
1651         return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions");
1652 
1653     // Handle read permission.
1654     const char read_perm_char = line_extractor.GetChar ();
1655     if (read_perm_char == 'r')
1656         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes);
1657     else if (read_perm_char == '-')
1658         memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1659     else
1660         return Error ("unexpected /proc/{pid}/maps read permission char");
1661 
1662     // Handle write permission.
1663     const char write_perm_char = line_extractor.GetChar ();
1664     if (write_perm_char == 'w')
1665         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes);
1666     else if (write_perm_char == '-')
1667         memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1668     else
1669         return Error ("unexpected /proc/{pid}/maps write permission char");
1670 
1671     // Handle execute permission.
1672     const char exec_perm_char = line_extractor.GetChar ();
1673     if (exec_perm_char == 'x')
1674         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes);
1675     else if (exec_perm_char == '-')
1676         memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1677     else
1678         return Error ("unexpected /proc/{pid}/maps exec permission char");
1679 
1680     line_extractor.GetChar();              // Read the private bit
1681     line_extractor.SkipSpaces();           // Skip the separator
1682     line_extractor.GetHexMaxU64(false, 0); // Read the offset
1683     line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1684     line_extractor.GetChar();              // Read the device id separator
1685     line_extractor.GetHexMaxU64(false, 0); // Read the major device number
1686     line_extractor.SkipSpaces();           // Skip the separator
1687     line_extractor.GetU64(0, 10);          // Read the inode number
1688 
1689     line_extractor.SkipSpaces();
1690     const char* name = line_extractor.Peek();
1691     if (name)
1692         memory_region_info.SetName(name);
1693 
1694     return Error ();
1695 }
1696 
1697 Error
1698 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info)
1699 {
1700     // FIXME review that the final memory region returned extends to the end of the virtual address space,
1701     // with no perms if it is not mapped.
1702 
1703     // Use an approach that reads memory regions from /proc/{pid}/maps.
1704     // Assume proc maps entries are in ascending order.
1705     // FIXME assert if we find differently.
1706 
1707     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1708     Error error;
1709 
1710     if (m_supports_mem_region == LazyBool::eLazyBoolNo)
1711     {
1712         // We're done.
1713         error.SetErrorString ("unsupported");
1714         return error;
1715     }
1716 
1717     // If our cache is empty, pull the latest.  There should always be at least one memory region
1718     // if memory region handling is supported.
1719     if (m_mem_region_cache.empty ())
1720     {
1721         error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
1722              [&] (const std::string &line) -> bool
1723              {
1724                  MemoryRegionInfo info;
1725                  const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info);
1726                  if (parse_error.Success ())
1727                  {
1728                      m_mem_region_cache.push_back (info);
1729                      return true;
1730                  }
1731                  else
1732                  {
1733                      if (log)
1734                          log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ());
1735                      return false;
1736                  }
1737              });
1738 
1739         // If we had an error, we'll mark unsupported.
1740         if (error.Fail ())
1741         {
1742             m_supports_mem_region = LazyBool::eLazyBoolNo;
1743             return error;
1744         }
1745         else if (m_mem_region_cache.empty ())
1746         {
1747             // No entries after attempting to read them.  This shouldn't happen if /proc/{pid}/maps
1748             // is supported.  Assume we don't support map entries via procfs.
1749             if (log)
1750                 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__);
1751             m_supports_mem_region = LazyBool::eLazyBoolNo;
1752             error.SetErrorString ("not supported");
1753             return error;
1754         }
1755 
1756         if (log)
1757             log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ());
1758 
1759         // We support memory retrieval, remember that.
1760         m_supports_mem_region = LazyBool::eLazyBoolYes;
1761     }
1762     else
1763     {
1764         if (log)
1765             log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
1766     }
1767 
1768     lldb::addr_t prev_base_address = 0;
1769 
1770     // FIXME start by finding the last region that is <= target address using binary search.  Data is sorted.
1771     // There can be a ton of regions on pthreads apps with lots of threads.
1772     for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it)
1773     {
1774         MemoryRegionInfo &proc_entry_info = *it;
1775 
1776         // Sanity check assumption that /proc/{pid}/maps entries are ascending.
1777         assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected");
1778         prev_base_address = proc_entry_info.GetRange ().GetRangeBase ();
1779 
1780         // If the target address comes before this entry, indicate distance to next region.
1781         if (load_addr < proc_entry_info.GetRange ().GetRangeBase ())
1782         {
1783             range_info.GetRange ().SetRangeBase (load_addr);
1784             range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr);
1785             range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1786             range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1787             range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1788             range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1789 
1790             return error;
1791         }
1792         else if (proc_entry_info.GetRange ().Contains (load_addr))
1793         {
1794             // The target address is within the memory region we're processing here.
1795             range_info = proc_entry_info;
1796             return error;
1797         }
1798 
1799         // The target memory address comes somewhere after the region we just parsed.
1800     }
1801 
1802     // If we made it here, we didn't find an entry that contained the given address. Return the
1803     // load_addr as start and the amount of bytes betwwen load address and the end of the memory as
1804     // size.
1805     range_info.GetRange ().SetRangeBase (load_addr);
1806     range_info.GetRange ().SetRangeEnd(LLDB_INVALID_ADDRESS);
1807     range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo);
1808     range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo);
1809     range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo);
1810     range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
1811     return error;
1812 }
1813 
1814 void
1815 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId)
1816 {
1817     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1818     if (log)
1819         log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId);
1820 
1821         if (log)
1822             log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()));
1823         m_mem_region_cache.clear ();
1824 }
1825 
1826 Error
1827 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr)
1828 {
1829     // FIXME implementing this requires the equivalent of
1830     // InferiorCallPOSIX::InferiorCallMmap, which depends on
1831     // functional ThreadPlans working with Native*Protocol.
1832 #if 1
1833     return Error ("not implemented yet");
1834 #else
1835     addr = LLDB_INVALID_ADDRESS;
1836 
1837     unsigned prot = 0;
1838     if (permissions & lldb::ePermissionsReadable)
1839         prot |= eMmapProtRead;
1840     if (permissions & lldb::ePermissionsWritable)
1841         prot |= eMmapProtWrite;
1842     if (permissions & lldb::ePermissionsExecutable)
1843         prot |= eMmapProtExec;
1844 
1845     // TODO implement this directly in NativeProcessLinux
1846     // (and lift to NativeProcessPOSIX if/when that class is
1847     // refactored out).
1848     if (InferiorCallMmap(this, addr, 0, size, prot,
1849                          eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
1850         m_addr_to_mmap_size[addr] = size;
1851         return Error ();
1852     } else {
1853         addr = LLDB_INVALID_ADDRESS;
1854         return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
1855     }
1856 #endif
1857 }
1858 
1859 Error
1860 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr)
1861 {
1862     // FIXME see comments in AllocateMemory - required lower-level
1863     // bits not in place yet (ThreadPlans)
1864     return Error ("not implemented");
1865 }
1866 
1867 lldb::addr_t
1868 NativeProcessLinux::GetSharedLibraryInfoAddress ()
1869 {
1870     // punt on this for now
1871     return LLDB_INVALID_ADDRESS;
1872 }
1873 
1874 size_t
1875 NativeProcessLinux::UpdateThreads ()
1876 {
1877     // The NativeProcessLinux monitoring threads are always up to date
1878     // with respect to thread state and they keep the thread list
1879     // populated properly. All this method needs to do is return the
1880     // thread count.
1881     return m_threads.size ();
1882 }
1883 
1884 bool
1885 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const
1886 {
1887     arch = m_arch;
1888     return true;
1889 }
1890 
1891 Error
1892 NativeProcessLinux::GetSoftwareBreakpointPCOffset(uint32_t &actual_opcode_size)
1893 {
1894     // FIXME put this behind a breakpoint protocol class that can be
1895     // set per architecture.  Need ARM, MIPS support here.
1896     static const uint8_t g_i386_opcode [] = { 0xCC };
1897     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
1898 
1899     switch (m_arch.GetMachine ())
1900     {
1901         case llvm::Triple::x86:
1902         case llvm::Triple::x86_64:
1903             actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode));
1904             return Error ();
1905 
1906         case llvm::Triple::systemz:
1907             actual_opcode_size = static_cast<uint32_t> (sizeof(g_s390x_opcode));
1908             return Error ();
1909 
1910         case llvm::Triple::arm:
1911         case llvm::Triple::aarch64:
1912         case llvm::Triple::mips64:
1913         case llvm::Triple::mips64el:
1914         case llvm::Triple::mips:
1915         case llvm::Triple::mipsel:
1916             // On these architectures the PC don't get updated for breakpoint hits
1917             actual_opcode_size = 0;
1918             return Error ();
1919 
1920         default:
1921             assert(false && "CPU type not supported!");
1922             return Error ("CPU type not supported");
1923     }
1924 }
1925 
1926 Error
1927 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware)
1928 {
1929     if (hardware)
1930         return Error ("NativeProcessLinux does not support hardware breakpoints");
1931     else
1932         return SetSoftwareBreakpoint (addr, size);
1933 }
1934 
1935 Error
1936 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint,
1937                                                      size_t &actual_opcode_size,
1938                                                      const uint8_t *&trap_opcode_bytes)
1939 {
1940     // FIXME put this behind a breakpoint protocol class that can be set per
1941     // architecture.  Need MIPS support here.
1942     static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 };
1943     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1944     // linux kernel does otherwise.
1945     static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
1946     static const uint8_t g_i386_opcode [] = { 0xCC };
1947     static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d };
1948     static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 };
1949     static const uint8_t g_s390x_opcode[] = { 0x00, 0x01 };
1950     static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
1951 
1952     switch (m_arch.GetMachine ())
1953     {
1954     case llvm::Triple::aarch64:
1955         trap_opcode_bytes = g_aarch64_opcode;
1956         actual_opcode_size = sizeof(g_aarch64_opcode);
1957         return Error ();
1958 
1959     case llvm::Triple::arm:
1960         switch (trap_opcode_size_hint)
1961         {
1962         case 2:
1963             trap_opcode_bytes = g_thumb_breakpoint_opcode;
1964             actual_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1965             return Error ();
1966         case 4:
1967             trap_opcode_bytes = g_arm_breakpoint_opcode;
1968             actual_opcode_size = sizeof(g_arm_breakpoint_opcode);
1969             return Error ();
1970         default:
1971             assert(false && "Unrecognised trap opcode size hint!");
1972             return Error ("Unrecognised trap opcode size hint!");
1973         }
1974 
1975     case llvm::Triple::x86:
1976     case llvm::Triple::x86_64:
1977         trap_opcode_bytes = g_i386_opcode;
1978         actual_opcode_size = sizeof(g_i386_opcode);
1979         return Error ();
1980 
1981     case llvm::Triple::mips:
1982     case llvm::Triple::mips64:
1983         trap_opcode_bytes = g_mips64_opcode;
1984         actual_opcode_size = sizeof(g_mips64_opcode);
1985         return Error ();
1986 
1987     case llvm::Triple::mipsel:
1988     case llvm::Triple::mips64el:
1989         trap_opcode_bytes = g_mips64el_opcode;
1990         actual_opcode_size = sizeof(g_mips64el_opcode);
1991         return Error ();
1992 
1993     case llvm::Triple::systemz:
1994         trap_opcode_bytes = g_s390x_opcode;
1995         actual_opcode_size = sizeof(g_s390x_opcode);
1996         return Error ();
1997 
1998     default:
1999         assert(false && "CPU type not supported!");
2000         return Error ("CPU type not supported");
2001     }
2002 }
2003 
2004 #if 0
2005 ProcessMessage::CrashReason
2006 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info)
2007 {
2008     ProcessMessage::CrashReason reason;
2009     assert(info->si_signo == SIGSEGV);
2010 
2011     reason = ProcessMessage::eInvalidCrashReason;
2012 
2013     switch (info->si_code)
2014     {
2015     default:
2016         assert(false && "unexpected si_code for SIGSEGV");
2017         break;
2018     case SI_KERNEL:
2019         // Linux will occasionally send spurious SI_KERNEL codes.
2020         // (this is poorly documented in sigaction)
2021         // One way to get this is via unaligned SIMD loads.
2022         reason = ProcessMessage::eInvalidAddress; // for lack of anything better
2023         break;
2024     case SEGV_MAPERR:
2025         reason = ProcessMessage::eInvalidAddress;
2026         break;
2027     case SEGV_ACCERR:
2028         reason = ProcessMessage::ePrivilegedAddress;
2029         break;
2030     }
2031 
2032     return reason;
2033 }
2034 #endif
2035 
2036 
2037 #if 0
2038 ProcessMessage::CrashReason
2039 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info)
2040 {
2041     ProcessMessage::CrashReason reason;
2042     assert(info->si_signo == SIGILL);
2043 
2044     reason = ProcessMessage::eInvalidCrashReason;
2045 
2046     switch (info->si_code)
2047     {
2048     default:
2049         assert(false && "unexpected si_code for SIGILL");
2050         break;
2051     case ILL_ILLOPC:
2052         reason = ProcessMessage::eIllegalOpcode;
2053         break;
2054     case ILL_ILLOPN:
2055         reason = ProcessMessage::eIllegalOperand;
2056         break;
2057     case ILL_ILLADR:
2058         reason = ProcessMessage::eIllegalAddressingMode;
2059         break;
2060     case ILL_ILLTRP:
2061         reason = ProcessMessage::eIllegalTrap;
2062         break;
2063     case ILL_PRVOPC:
2064         reason = ProcessMessage::ePrivilegedOpcode;
2065         break;
2066     case ILL_PRVREG:
2067         reason = ProcessMessage::ePrivilegedRegister;
2068         break;
2069     case ILL_COPROC:
2070         reason = ProcessMessage::eCoprocessorError;
2071         break;
2072     case ILL_BADSTK:
2073         reason = ProcessMessage::eInternalStackError;
2074         break;
2075     }
2076 
2077     return reason;
2078 }
2079 #endif
2080 
2081 #if 0
2082 ProcessMessage::CrashReason
2083 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info)
2084 {
2085     ProcessMessage::CrashReason reason;
2086     assert(info->si_signo == SIGFPE);
2087 
2088     reason = ProcessMessage::eInvalidCrashReason;
2089 
2090     switch (info->si_code)
2091     {
2092     default:
2093         assert(false && "unexpected si_code for SIGFPE");
2094         break;
2095     case FPE_INTDIV:
2096         reason = ProcessMessage::eIntegerDivideByZero;
2097         break;
2098     case FPE_INTOVF:
2099         reason = ProcessMessage::eIntegerOverflow;
2100         break;
2101     case FPE_FLTDIV:
2102         reason = ProcessMessage::eFloatDivideByZero;
2103         break;
2104     case FPE_FLTOVF:
2105         reason = ProcessMessage::eFloatOverflow;
2106         break;
2107     case FPE_FLTUND:
2108         reason = ProcessMessage::eFloatUnderflow;
2109         break;
2110     case FPE_FLTRES:
2111         reason = ProcessMessage::eFloatInexactResult;
2112         break;
2113     case FPE_FLTINV:
2114         reason = ProcessMessage::eFloatInvalidOperation;
2115         break;
2116     case FPE_FLTSUB:
2117         reason = ProcessMessage::eFloatSubscriptRange;
2118         break;
2119     }
2120 
2121     return reason;
2122 }
2123 #endif
2124 
2125 #if 0
2126 ProcessMessage::CrashReason
2127 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info)
2128 {
2129     ProcessMessage::CrashReason reason;
2130     assert(info->si_signo == SIGBUS);
2131 
2132     reason = ProcessMessage::eInvalidCrashReason;
2133 
2134     switch (info->si_code)
2135     {
2136     default:
2137         assert(false && "unexpected si_code for SIGBUS");
2138         break;
2139     case BUS_ADRALN:
2140         reason = ProcessMessage::eIllegalAlignment;
2141         break;
2142     case BUS_ADRERR:
2143         reason = ProcessMessage::eIllegalAddress;
2144         break;
2145     case BUS_OBJERR:
2146         reason = ProcessMessage::eHardwareError;
2147         break;
2148     }
2149 
2150     return reason;
2151 }
2152 #endif
2153 
2154 Error
2155 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2156 {
2157     if (ProcessVmReadvSupported()) {
2158         // The process_vm_readv path is about 50 times faster than ptrace api. We want to use
2159         // this syscall if it is supported.
2160 
2161         const ::pid_t pid = GetID();
2162 
2163         struct iovec local_iov, remote_iov;
2164         local_iov.iov_base = buf;
2165         local_iov.iov_len = size;
2166         remote_iov.iov_base = reinterpret_cast<void *>(addr);
2167         remote_iov.iov_len = size;
2168 
2169         bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0);
2170         const bool success = bytes_read == size;
2171 
2172         Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2173         if (log)
2174             log->Printf ("NativeProcessLinux::%s using process_vm_readv to read %zd bytes from inferior address 0x%" PRIx64": %s",
2175                     __FUNCTION__, size, addr, success ? "Success" : strerror(errno));
2176 
2177         if (success)
2178             return Error();
2179         // else
2180         //     the call failed for some reason, let's retry the read using ptrace api.
2181     }
2182 
2183     unsigned char *dst = static_cast<unsigned char*>(buf);
2184     size_t remainder;
2185     long data;
2186 
2187     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2188     if (log)
2189         ProcessPOSIXLog::IncNestLevel();
2190     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2191         log->Printf ("NativeProcessLinux::%s(%p, %p, %zd, _)", __FUNCTION__, (void*)addr, buf, size);
2192 
2193     for (bytes_read = 0; bytes_read < size; bytes_read += remainder)
2194     {
2195         Error error = NativeProcessLinux::PtraceWrapper(PTRACE_PEEKDATA, GetID(), (void*)addr, nullptr, 0, &data);
2196         if (error.Fail())
2197         {
2198             if (log)
2199                 ProcessPOSIXLog::DecNestLevel();
2200             return error;
2201         }
2202 
2203         remainder = size - bytes_read;
2204         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2205 
2206         // Copy the data into our buffer
2207         memcpy(dst, &data, remainder);
2208 
2209         if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2210                 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2211                         (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2212                                 size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2213         {
2214             uintptr_t print_dst = 0;
2215             // Format bytes from data by moving into print_dst for log output
2216             for (unsigned i = 0; i < remainder; ++i)
2217                 print_dst |= (((data >> i*8) & 0xFF) << i*8);
2218             log->Printf ("NativeProcessLinux::%s() [0x%" PRIx64 "]:0x%" PRIx64 " (0x%" PRIx64 ")",
2219                     __FUNCTION__, addr, uint64_t(print_dst), uint64_t(data));
2220         }
2221         addr += k_ptrace_word_size;
2222         dst += k_ptrace_word_size;
2223     }
2224 
2225     if (log)
2226         ProcessPOSIXLog::DecNestLevel();
2227     return Error();
2228 }
2229 
2230 Error
2231 NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read)
2232 {
2233     Error error = ReadMemory(addr, buf, size, bytes_read);
2234     if (error.Fail()) return error;
2235     return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
2236 }
2237 
2238 Error
2239 NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written)
2240 {
2241     const unsigned char *src = static_cast<const unsigned char*>(buf);
2242     size_t remainder;
2243     Error error;
2244 
2245     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL));
2246     if (log)
2247         ProcessPOSIXLog::IncNestLevel();
2248     if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY))
2249         log->Printf ("NativeProcessLinux::%s(0x%" PRIx64 ", %p, %zu)", __FUNCTION__, addr, buf, size);
2250 
2251     for (bytes_written = 0; bytes_written < size; bytes_written += remainder)
2252     {
2253         remainder = size - bytes_written;
2254         remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder;
2255 
2256         if (remainder == k_ptrace_word_size)
2257         {
2258             unsigned long data = 0;
2259             memcpy(&data, src, k_ptrace_word_size);
2260 
2261             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2262                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2263                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2264                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2265                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2266                         (void*)addr, *(const unsigned long*)src, data);
2267 
2268             error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), (void*)addr, (void*)data);
2269             if (error.Fail())
2270             {
2271                 if (log)
2272                     ProcessPOSIXLog::DecNestLevel();
2273                 return error;
2274             }
2275         }
2276         else
2277         {
2278             unsigned char buff[8];
2279             size_t bytes_read;
2280             error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read);
2281             if (error.Fail())
2282             {
2283                 if (log)
2284                     ProcessPOSIXLog::DecNestLevel();
2285                 return error;
2286             }
2287 
2288             memcpy(buff, src, remainder);
2289 
2290             size_t bytes_written_rec;
2291             error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec);
2292             if (error.Fail())
2293             {
2294                 if (log)
2295                     ProcessPOSIXLog::DecNestLevel();
2296                 return error;
2297             }
2298 
2299             if (log && ProcessPOSIXLog::AtTopNestLevel() &&
2300                     (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) ||
2301                             (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) &&
2302                                     size <= POSIX_LOG_MEMORY_SHORT_BYTES)))
2303                 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__,
2304                         (void*)addr, *(const unsigned long*)src, *(unsigned long*)buff);
2305         }
2306 
2307         addr += k_ptrace_word_size;
2308         src += k_ptrace_word_size;
2309     }
2310     if (log)
2311         ProcessPOSIXLog::DecNestLevel();
2312     return error;
2313 }
2314 
2315 Error
2316 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo)
2317 {
2318     return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo);
2319 }
2320 
2321 Error
2322 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message)
2323 {
2324     return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message);
2325 }
2326 
2327 Error
2328 NativeProcessLinux::Detach(lldb::tid_t tid)
2329 {
2330     if (tid == LLDB_INVALID_THREAD_ID)
2331         return Error();
2332 
2333     return PtraceWrapper(PTRACE_DETACH, tid);
2334 }
2335 
2336 bool
2337 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id)
2338 {
2339     for (auto thread_sp : m_threads)
2340     {
2341         assert (thread_sp && "thread list should not contain NULL threads");
2342         if (thread_sp->GetID () == thread_id)
2343         {
2344             // We have this thread.
2345             return true;
2346         }
2347     }
2348 
2349     // We don't have this thread.
2350     return false;
2351 }
2352 
2353 bool
2354 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id)
2355 {
2356     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2357 
2358     if (log)
2359         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id);
2360 
2361     bool found = false;
2362 
2363     for (auto it = m_threads.begin (); it != m_threads.end (); ++it)
2364     {
2365         if (*it && ((*it)->GetID () == thread_id))
2366         {
2367             m_threads.erase (it);
2368             found = true;
2369             break;
2370         }
2371     }
2372 
2373     SignalIfAllThreadsStopped();
2374 
2375     return found;
2376 }
2377 
2378 NativeThreadLinuxSP
2379 NativeProcessLinux::AddThread (lldb::tid_t thread_id)
2380 {
2381     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
2382 
2383     if (log)
2384     {
2385         log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64,
2386                 __FUNCTION__,
2387                 GetID (),
2388                 thread_id);
2389     }
2390 
2391     assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists");
2392 
2393     // If this is the first thread, save it as the current thread
2394     if (m_threads.empty ())
2395         SetCurrentThreadID (thread_id);
2396 
2397     auto thread_sp = std::make_shared<NativeThreadLinux>(this, thread_id);
2398     m_threads.push_back (thread_sp);
2399     return thread_sp;
2400 }
2401 
2402 Error
2403 NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread)
2404 {
2405     Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2406 
2407     Error error;
2408 
2409     // Find out the size of a breakpoint (might depend on where we are in the code).
2410     NativeRegisterContextSP context_sp = thread.GetRegisterContext();
2411     if (!context_sp)
2412     {
2413         error.SetErrorString ("cannot get a NativeRegisterContext for the thread");
2414         if (log)
2415             log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ());
2416         return error;
2417     }
2418 
2419     uint32_t breakpoint_size = 0;
2420     error = GetSoftwareBreakpointPCOffset(breakpoint_size);
2421     if (error.Fail ())
2422     {
2423         if (log)
2424             log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ());
2425         return error;
2426     }
2427     else
2428     {
2429         if (log)
2430             log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size);
2431     }
2432 
2433     // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size.
2434     const lldb::addr_t initial_pc_addr = context_sp->GetPCfromBreakpointLocation ();
2435     lldb::addr_t breakpoint_addr = initial_pc_addr;
2436     if (breakpoint_size > 0)
2437     {
2438         // Do not allow breakpoint probe to wrap around.
2439         if (breakpoint_addr >= breakpoint_size)
2440             breakpoint_addr -= breakpoint_size;
2441     }
2442 
2443     // Check if we stopped because of a breakpoint.
2444     NativeBreakpointSP breakpoint_sp;
2445     error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp);
2446     if (!error.Success () || !breakpoint_sp)
2447     {
2448         // We didn't find one at a software probe location.  Nothing to do.
2449         if (log)
2450             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr);
2451         return Error ();
2452     }
2453 
2454     // If the breakpoint is not a software breakpoint, nothing to do.
2455     if (!breakpoint_sp->IsSoftwareBreakpoint ())
2456     {
2457         if (log)
2458             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr);
2459         return Error ();
2460     }
2461 
2462     //
2463     // We have a software breakpoint and need to adjust the PC.
2464     //
2465 
2466     // Sanity check.
2467     if (breakpoint_size == 0)
2468     {
2469         // Nothing to do!  How did we get here?
2470         if (log)
2471             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);
2472         return Error ();
2473     }
2474 
2475     // Change the program counter.
2476     if (log)
2477         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);
2478 
2479     error = context_sp->SetPC (breakpoint_addr);
2480     if (error.Fail ())
2481     {
2482         if (log)
2483             log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID(), thread.GetID(), error.AsCString ());
2484         return error;
2485     }
2486 
2487     return error;
2488 }
2489 
2490 Error
2491 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec)
2492 {
2493     FileSpec module_file_spec(module_path, true);
2494 
2495     bool found = false;
2496     file_spec.Clear();
2497     ProcFileReader::ProcessLineByLine(GetID(), "maps",
2498         [&] (const std::string &line)
2499         {
2500             SmallVector<StringRef, 16> columns;
2501             StringRef(line).split(columns, " ", -1, false);
2502             if (columns.size() < 6)
2503                 return true; // continue searching
2504 
2505             FileSpec this_file_spec(columns[5].str().c_str(), false);
2506             if (this_file_spec.GetFilename() != module_file_spec.GetFilename())
2507                 return true; // continue searching
2508 
2509             file_spec = this_file_spec;
2510             found = true;
2511             return false; // we are done
2512         });
2513 
2514     if (! found)
2515         return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!",
2516                 module_file_spec.GetFilename().AsCString(), GetID());
2517 
2518     return Error();
2519 }
2520 
2521 Error
2522 NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef& file_name, lldb::addr_t& load_addr)
2523 {
2524     load_addr = LLDB_INVALID_ADDRESS;
2525     Error error = ProcFileReader::ProcessLineByLine (GetID (), "maps",
2526         [&] (const std::string &line) -> bool
2527         {
2528             StringRef maps_row(line);
2529 
2530             SmallVector<StringRef, 16> maps_columns;
2531             maps_row.split(maps_columns, StringRef(" "), -1, false);
2532 
2533             if (maps_columns.size() < 6)
2534             {
2535                 // Return true to continue reading the proc file
2536                 return true;
2537             }
2538 
2539             if (maps_columns[5] == file_name)
2540             {
2541                 StringExtractor addr_extractor(maps_columns[0].str().c_str());
2542                 load_addr = addr_extractor.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
2543 
2544                 // Return false to stop reading the proc file further
2545                 return false;
2546             }
2547 
2548             // Return true to continue reading the proc file
2549             return true;
2550         });
2551     return error;
2552 }
2553 
2554 NativeThreadLinuxSP
2555 NativeProcessLinux::GetThreadByID(lldb::tid_t tid)
2556 {
2557     return std::static_pointer_cast<NativeThreadLinux>(NativeProcessProtocol::GetThreadByID(tid));
2558 }
2559 
2560 Error
2561 NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, lldb::StateType state, int signo)
2562 {
2563     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2564 
2565     if (log)
2566         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")",
2567                 __FUNCTION__, thread.GetID());
2568 
2569     // Before we do the resume below, first check if we have a pending
2570     // stop notification that is currently waiting for
2571     // all threads to stop.  This is potentially a buggy situation since
2572     // we're ostensibly waiting for threads to stop before we send out the
2573     // pending notification, and here we are resuming one before we send
2574     // out the pending stop notification.
2575     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && log)
2576     {
2577         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);
2578     }
2579 
2580     // Request a resume.  We expect this to be synchronous and the system
2581     // to reflect it is running after this completes.
2582     switch (state)
2583     {
2584     case eStateRunning:
2585     {
2586         const auto resume_result = thread.Resume(signo);
2587         if (resume_result.Success())
2588             SetState(eStateRunning, true);
2589         return resume_result;
2590     }
2591     case eStateStepping:
2592     {
2593         const auto step_result = thread.SingleStep(signo);
2594         if (step_result.Success())
2595             SetState(eStateRunning, true);
2596         return step_result;
2597     }
2598     default:
2599         if (log)
2600             log->Printf("NativeProcessLinux::%s Unhandled state %s.",
2601                     __FUNCTION__, StateAsCString(state));
2602         llvm_unreachable("Unhandled state for resume");
2603     }
2604 }
2605 
2606 //===----------------------------------------------------------------------===//
2607 
2608 void
2609 NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid)
2610 {
2611     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2612 
2613     if (log)
2614     {
2615         log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")",
2616                 __FUNCTION__, triggering_tid);
2617     }
2618 
2619     m_pending_notification_tid = triggering_tid;
2620 
2621     // Request a stop for all the thread stops that need to be stopped
2622     // and are not already known to be stopped.
2623     for (const auto &thread_sp: m_threads)
2624     {
2625         if (StateIsRunningState(thread_sp->GetState()))
2626             static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop();
2627     }
2628 
2629     SignalIfAllThreadsStopped();
2630 
2631     if (log)
2632     {
2633         log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__);
2634     }
2635 }
2636 
2637 void
2638 NativeProcessLinux::SignalIfAllThreadsStopped()
2639 {
2640     if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID)
2641         return; // No pending notification. Nothing to do.
2642 
2643     for (const auto &thread_sp: m_threads)
2644     {
2645         if (StateIsRunningState(thread_sp->GetState()))
2646             return; // Some threads are still running. Don't signal yet.
2647     }
2648 
2649     // We have a pending notification and all threads have stopped.
2650     Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS));
2651 
2652     // Clear any temporary breakpoints we used to implement software single stepping.
2653     for (const auto &thread_info: m_threads_stepping_with_breakpoint)
2654     {
2655         Error error = RemoveBreakpoint (thread_info.second);
2656         if (error.Fail())
2657             if (log)
2658                 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s",
2659                         __FUNCTION__, thread_info.first, error.AsCString());
2660     }
2661     m_threads_stepping_with_breakpoint.clear();
2662 
2663     // Notify the delegate about the stop
2664     SetCurrentThreadID(m_pending_notification_tid);
2665     SetState(StateType::eStateStopped, true);
2666     m_pending_notification_tid = LLDB_INVALID_THREAD_ID;
2667 }
2668 
2669 void
2670 NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread)
2671 {
2672     Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD);
2673 
2674     if (log)
2675         log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread.GetID());
2676 
2677     if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && StateIsRunningState(thread.GetState()))
2678     {
2679         // We will need to wait for this new thread to stop as well before firing the
2680         // notification.
2681         thread.RequestStop();
2682     }
2683 }
2684 
2685 void
2686 NativeProcessLinux::SigchldHandler()
2687 {
2688     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2689     // Process all pending waitpid notifications.
2690     while (true)
2691     {
2692         int status = -1;
2693         ::pid_t wait_pid = waitpid(-1, &status, __WALL | __WNOTHREAD | WNOHANG);
2694 
2695         if (wait_pid == 0)
2696             break; // We are done.
2697 
2698         if (wait_pid == -1)
2699         {
2700             if (errno == EINTR)
2701                 continue;
2702 
2703             Error error(errno, eErrorTypePOSIX);
2704             if (log)
2705                 log->Printf("NativeProcessLinux::%s waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG) failed: %s",
2706                         __FUNCTION__, error.AsCString());
2707             break;
2708         }
2709 
2710         bool exited = false;
2711         int signal = 0;
2712         int exit_status = 0;
2713         const char *status_cstr = nullptr;
2714         if (WIFSTOPPED(status))
2715         {
2716             signal = WSTOPSIG(status);
2717             status_cstr = "STOPPED";
2718         }
2719         else if (WIFEXITED(status))
2720         {
2721             exit_status = WEXITSTATUS(status);
2722             status_cstr = "EXITED";
2723             exited = true;
2724         }
2725         else if (WIFSIGNALED(status))
2726         {
2727             signal = WTERMSIG(status);
2728             status_cstr = "SIGNALED";
2729             if (wait_pid == static_cast< ::pid_t>(GetID())) {
2730                 exited = true;
2731                 exit_status = -1;
2732             }
2733         }
2734         else
2735             status_cstr = "(\?\?\?)";
2736 
2737         if (log)
2738             log->Printf("NativeProcessLinux::%s: waitpid (-1, &status, __WALL | __WNOTHREAD | WNOHANG)"
2739                 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
2740                 __FUNCTION__, wait_pid, status, status_cstr, signal, exit_status);
2741 
2742         MonitorCallback (wait_pid, exited, signal, exit_status);
2743     }
2744 }
2745 
2746 // Wrapper for ptrace to catch errors and log calls.
2747 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*)
2748 Error
2749 NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, long *result)
2750 {
2751     Error error;
2752     long int ret;
2753 
2754     Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE));
2755 
2756     PtraceDisplayBytes(req, data, data_size);
2757 
2758     errno = 0;
2759     if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET)
2760         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data);
2761     else
2762         ret = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data);
2763 
2764     if (ret == -1)
2765         error.SetErrorToErrno();
2766 
2767     if (result)
2768         *result = ret;
2769 
2770     if (log)
2771         log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, ret);
2772 
2773     PtraceDisplayBytes(req, data, data_size);
2774 
2775     if (log && error.GetError() != 0)
2776     {
2777         const char* str;
2778         switch (error.GetError())
2779         {
2780         case ESRCH:  str = "ESRCH"; break;
2781         case EINVAL: str = "EINVAL"; break;
2782         case EBUSY:  str = "EBUSY"; break;
2783         case EPERM:  str = "EPERM"; break;
2784         default:     str = error.AsCString();
2785         }
2786         log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str);
2787     }
2788 
2789     return error;
2790 }
2791