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