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