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