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