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