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