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