1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "NativeProcessLinux.h" 11 12 #include <errno.h> 13 #include <stdint.h> 14 #include <string.h> 15 #include <unistd.h> 16 17 #include <fstream> 18 #include <mutex> 19 #include <sstream> 20 #include <string> 21 #include <unordered_map> 22 23 #include "lldb/Core/EmulateInstruction.h" 24 #include "lldb/Core/ModuleSpec.h" 25 #include "lldb/Host/Host.h" 26 #include "lldb/Host/HostProcess.h" 27 #include "lldb/Host/PseudoTerminal.h" 28 #include "lldb/Host/ThreadLauncher.h" 29 #include "lldb/Host/common/NativeRegisterContext.h" 30 #include "lldb/Host/linux/Ptrace.h" 31 #include "lldb/Host/linux/Uio.h" 32 #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 33 #include "lldb/Symbol/ObjectFile.h" 34 #include "lldb/Target/Process.h" 35 #include "lldb/Target/ProcessLaunchInfo.h" 36 #include "lldb/Target/Target.h" 37 #include "lldb/Utility/LLDBAssert.h" 38 #include "lldb/Utility/RegisterValue.h" 39 #include "lldb/Utility/State.h" 40 #include "lldb/Utility/Status.h" 41 #include "lldb/Utility/StringExtractor.h" 42 #include "llvm/Support/Errno.h" 43 #include "llvm/Support/FileSystem.h" 44 #include "llvm/Support/Threading.h" 45 46 #include "NativeThreadLinux.h" 47 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 48 #include "Procfs.h" 49 50 #include <linux/unistd.h> 51 #include <sys/socket.h> 52 #include <sys/syscall.h> 53 #include <sys/types.h> 54 #include <sys/user.h> 55 #include <sys/wait.h> 56 57 // Support hardware breakpoints in case it has not been defined 58 #ifndef TRAP_HWBKPT 59 #define TRAP_HWBKPT 4 60 #endif 61 62 using namespace lldb; 63 using namespace lldb_private; 64 using namespace lldb_private::process_linux; 65 using namespace llvm; 66 67 // Private bits we only need internally. 68 69 static bool ProcessVmReadvSupported() { 70 static bool is_supported; 71 static llvm::once_flag flag; 72 73 llvm::call_once(flag, [] { 74 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 75 76 uint32_t source = 0x47424742; 77 uint32_t dest = 0; 78 79 struct iovec local, remote; 80 remote.iov_base = &source; 81 local.iov_base = &dest; 82 remote.iov_len = local.iov_len = sizeof source; 83 84 // We shall try if cross-process-memory reads work by attempting to read a 85 // value from our own process. 86 ssize_t res = process_vm_readv(getpid(), &local, 1, &remote, 1, 0); 87 is_supported = (res == sizeof(source) && source == dest); 88 if (is_supported) 89 LLDB_LOG(log, 90 "Detected kernel support for process_vm_readv syscall. " 91 "Fast memory reads enabled."); 92 else 93 LLDB_LOG(log, 94 "syscall process_vm_readv failed (error: {0}). Fast memory " 95 "reads disabled.", 96 llvm::sys::StrError()); 97 }); 98 99 return is_supported; 100 } 101 102 namespace { 103 void MaybeLogLaunchInfo(const ProcessLaunchInfo &info) { 104 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 105 if (!log) 106 return; 107 108 if (const FileAction *action = info.GetFileActionForFD(STDIN_FILENO)) 109 LLDB_LOG(log, "setting STDIN to '{0}'", action->GetFileSpec()); 110 else 111 LLDB_LOG(log, "leaving STDIN as is"); 112 113 if (const FileAction *action = info.GetFileActionForFD(STDOUT_FILENO)) 114 LLDB_LOG(log, "setting STDOUT to '{0}'", action->GetFileSpec()); 115 else 116 LLDB_LOG(log, "leaving STDOUT as is"); 117 118 if (const FileAction *action = info.GetFileActionForFD(STDERR_FILENO)) 119 LLDB_LOG(log, "setting STDERR to '{0}'", action->GetFileSpec()); 120 else 121 LLDB_LOG(log, "leaving STDERR as is"); 122 123 int i = 0; 124 for (const char **args = info.GetArguments().GetConstArgumentVector(); *args; 125 ++args, ++i) 126 LLDB_LOG(log, "arg {0}: '{1}'", i, *args); 127 } 128 129 void DisplayBytes(StreamString &s, void *bytes, uint32_t count) { 130 uint8_t *ptr = (uint8_t *)bytes; 131 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 132 for (uint32_t i = 0; i < loop_count; i++) { 133 s.Printf("[%x]", *ptr); 134 ptr++; 135 } 136 } 137 138 void PtraceDisplayBytes(int &req, void *data, size_t data_size) { 139 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 140 if (!log) 141 return; 142 StreamString buf; 143 144 switch (req) { 145 case PTRACE_POKETEXT: { 146 DisplayBytes(buf, &data, 8); 147 LLDB_LOGV(log, "PTRACE_POKETEXT {0}", buf.GetData()); 148 break; 149 } 150 case PTRACE_POKEDATA: { 151 DisplayBytes(buf, &data, 8); 152 LLDB_LOGV(log, "PTRACE_POKEDATA {0}", buf.GetData()); 153 break; 154 } 155 case PTRACE_POKEUSER: { 156 DisplayBytes(buf, &data, 8); 157 LLDB_LOGV(log, "PTRACE_POKEUSER {0}", buf.GetData()); 158 break; 159 } 160 case PTRACE_SETREGS: { 161 DisplayBytes(buf, data, data_size); 162 LLDB_LOGV(log, "PTRACE_SETREGS {0}", buf.GetData()); 163 break; 164 } 165 case PTRACE_SETFPREGS: { 166 DisplayBytes(buf, data, data_size); 167 LLDB_LOGV(log, "PTRACE_SETFPREGS {0}", buf.GetData()); 168 break; 169 } 170 case PTRACE_SETSIGINFO: { 171 DisplayBytes(buf, data, sizeof(siginfo_t)); 172 LLDB_LOGV(log, "PTRACE_SETSIGINFO {0}", buf.GetData()); 173 break; 174 } 175 case PTRACE_SETREGSET: { 176 // Extract iov_base from data, which is a pointer to the struct iovec 177 DisplayBytes(buf, *(void **)data, data_size); 178 LLDB_LOGV(log, "PTRACE_SETREGSET {0}", buf.GetData()); 179 break; 180 } 181 default: {} 182 } 183 } 184 185 static constexpr unsigned k_ptrace_word_size = sizeof(void *); 186 static_assert(sizeof(long) >= k_ptrace_word_size, 187 "Size of long must be larger than ptrace word size"); 188 } // end of anonymous namespace 189 190 // Simple helper function to ensure flags are enabled on the given file 191 // descriptor. 192 static Status EnsureFDFlags(int fd, int flags) { 193 Status error; 194 195 int status = fcntl(fd, F_GETFL); 196 if (status == -1) { 197 error.SetErrorToErrno(); 198 return error; 199 } 200 201 if (fcntl(fd, F_SETFL, status | flags) == -1) { 202 error.SetErrorToErrno(); 203 return error; 204 } 205 206 return error; 207 } 208 209 // ----------------------------------------------------------------------------- 210 // Public Static Methods 211 // ----------------------------------------------------------------------------- 212 213 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 214 NativeProcessLinux::Factory::Launch(ProcessLaunchInfo &launch_info, 215 NativeDelegate &native_delegate, 216 MainLoop &mainloop) const { 217 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 218 219 MaybeLogLaunchInfo(launch_info); 220 221 Status status; 222 ::pid_t pid = ProcessLauncherPosixFork() 223 .LaunchProcess(launch_info, status) 224 .GetProcessId(); 225 LLDB_LOG(log, "pid = {0:x}", pid); 226 if (status.Fail()) { 227 LLDB_LOG(log, "failed to launch process: {0}", status); 228 return status.ToError(); 229 } 230 231 // Wait for the child process to trap on its call to execve. 232 int wstatus; 233 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 234 assert(wpid == pid); 235 (void)wpid; 236 if (!WIFSTOPPED(wstatus)) { 237 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 238 WaitStatus::Decode(wstatus)); 239 return llvm::make_error<StringError>("Could not sync with inferior process", 240 llvm::inconvertibleErrorCode()); 241 } 242 LLDB_LOG(log, "inferior started, now in stopped state"); 243 244 ProcessInstanceInfo Info; 245 if (!Host::GetProcessInfo(pid, Info)) { 246 return llvm::make_error<StringError>("Cannot get process architecture", 247 llvm::inconvertibleErrorCode()); 248 } 249 250 // Set the architecture to the exe architecture. 251 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 252 Info.GetArchitecture().GetArchitectureName()); 253 254 status = SetDefaultPtraceOpts(pid); 255 if (status.Fail()) { 256 LLDB_LOG(log, "failed to set default ptrace options: {0}", status); 257 return status.ToError(); 258 } 259 260 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 261 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate, 262 Info.GetArchitecture(), mainloop, {pid})); 263 } 264 265 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 266 NativeProcessLinux::Factory::Attach( 267 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 268 MainLoop &mainloop) const { 269 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 270 LLDB_LOG(log, "pid = {0:x}", pid); 271 272 // Retrieve the architecture for the running process. 273 ProcessInstanceInfo Info; 274 if (!Host::GetProcessInfo(pid, Info)) { 275 return llvm::make_error<StringError>("Cannot get process architecture", 276 llvm::inconvertibleErrorCode()); 277 } 278 279 auto tids_or = NativeProcessLinux::Attach(pid); 280 if (!tids_or) 281 return tids_or.takeError(); 282 283 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 284 pid, -1, native_delegate, Info.GetArchitecture(), mainloop, *tids_or)); 285 } 286 287 // ----------------------------------------------------------------------------- 288 // Public Instance Methods 289 // ----------------------------------------------------------------------------- 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 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { 296 if (m_terminal_fd != -1) { 297 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 298 assert(status.Success()); 299 } 300 301 Status status; 302 m_sigchld_handle = mainloop.RegisterSignal( 303 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 304 assert(m_sigchld_handle && status.Success()); 305 306 for (const auto &tid : tids) { 307 NativeThreadLinux &thread = AddThread(tid); 308 thread.SetStoppedBySignal(SIGSTOP); 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 // TODO: if we want to support tracing the inferiors' child, add the 393 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 394 ptrace_opts |= PTRACE_O_TRACECLONE; 395 396 // Have the tracer notify us before execve returns (needed to disable legacy 397 // SIGTRAP generation) 398 ptrace_opts |= PTRACE_O_TRACEEXEC; 399 400 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts); 401 } 402 403 // Handles all waitpid events from the inferior process. 404 void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 405 WaitStatus status) { 406 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 407 408 // Certain activities differ based on whether the pid is the tid of the main 409 // thread. 410 const bool is_main_thread = (pid == GetID()); 411 412 // Handle when the thread exits. 413 if (exited) { 414 LLDB_LOG(log, 415 "got exit signal({0}) , tid = {1} ({2} main thread), process " 416 "state = {3}", 417 signal, pid, is_main_thread ? "is" : "is not", GetState()); 418 419 // This is a thread that exited. Ensure we're not tracking it anymore. 420 StopTrackingThread(pid); 421 422 if (is_main_thread) { 423 // The main thread exited. We're done monitoring. Report to delegate. 424 SetExitStatus(status, true); 425 426 // Notify delegate that our process has exited. 427 SetState(StateType::eStateExited, true); 428 } 429 return; 430 } 431 432 siginfo_t info; 433 const auto info_err = GetSignalInfo(pid, &info); 434 auto thread_sp = GetThreadByID(pid); 435 436 if (!thread_sp) { 437 // Normally, the only situation when we cannot find the thread is if we 438 // have just received a new thread notification. This is indicated by 439 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 440 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 441 442 if (info_err.Fail()) { 443 LLDB_LOG(log, 444 "(tid {0}) GetSignalInfo failed ({1}). " 445 "Ingoring this notification.", 446 pid, info_err); 447 return; 448 } 449 450 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 451 info.si_pid); 452 453 NativeThreadLinux &thread = AddThread(pid); 454 455 // Resume the newly created thread. 456 ResumeThread(thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 457 ThreadWasCreated(thread); 458 return; 459 } 460 461 // Get details on the signal raised. 462 if (info_err.Success()) { 463 // We have retrieved the signal info. Dispatch appropriately. 464 if (info.si_signo == SIGTRAP) 465 MonitorSIGTRAP(info, *thread_sp); 466 else 467 MonitorSignal(info, *thread_sp, exited); 468 } else { 469 if (info_err.GetError() == EINVAL) { 470 // This is a group stop reception for this tid. We can reach here if we 471 // reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU into the tracee, 472 // triggering the group-stop mechanism. Normally receiving these would 473 // stop the process, pending a SIGCONT. Simulating this state in a 474 // debugger is hard and is generally not needed (one use case is 475 // debugging background task being managed by a shell). For general use, 476 // it is sufficient to stop the process in a signal-delivery stop which 477 // happens before the group stop. This done by MonitorSignal and works 478 // correctly for all signals. 479 LLDB_LOG(log, 480 "received a group stop for pid {0} tid {1}. Transparent " 481 "handling of group stops not supported, resuming the " 482 "thread.", 483 GetID(), pid); 484 ResumeThread(*thread_sp, thread_sp->GetState(), 485 LLDB_INVALID_SIGNAL_NUMBER); 486 } else { 487 // ptrace(GETSIGINFO) failed (but not due to group-stop). 488 489 // A return value of ESRCH means the thread/process is no longer on the 490 // system, so it was killed somehow outside of our control. Either way, 491 // we can't do anything with it anymore. 492 493 // Stop tracking the metadata for the thread since it's entirely off the 494 // system now. 495 const bool thread_found = StopTrackingThread(pid); 496 497 LLDB_LOG(log, 498 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, " 499 "status = {3}, main_thread = {4}, thread_found: {5}", 500 info_err, pid, signal, status, is_main_thread, thread_found); 501 502 if (is_main_thread) { 503 // Notify the delegate - our process is not available but appears to 504 // have been killed outside our control. Is eStateExited the right 505 // exit state in this case? 506 SetExitStatus(status, true); 507 SetState(StateType::eStateExited, true); 508 } else { 509 // This thread was pulled out from underneath us. Anything to do here? 510 // Do we want to do an all stop? 511 LLDB_LOG(log, 512 "pid {0} tid {1} non-main thread exit occurred, didn't " 513 "tell delegate anything since thread disappeared out " 514 "from underneath us", 515 GetID(), pid); 516 } 517 } 518 } 519 } 520 521 void NativeProcessLinux::WaitForNewThread(::pid_t tid) { 522 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 523 524 if (GetThreadByID(tid)) { 525 // We are already tracking the thread - we got the event on the new thread 526 // (see MonitorSignal) before this one. We are done. 527 return; 528 } 529 530 // The thread is not tracked yet, let's wait for it to appear. 531 int status = -1; 532 LLDB_LOG(log, 533 "received thread creation event for tid {0}. tid not tracked " 534 "yet, waiting for thread to appear...", 535 tid); 536 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL); 537 // Since we are waiting on a specific tid, this must be the creation event. 538 // But let's do some checks just in case. 539 if (wait_pid != tid) { 540 LLDB_LOG(log, 541 "waiting for tid {0} failed. Assuming the thread has " 542 "disappeared in the meantime", 543 tid); 544 // The only way I know of this could happen is if the whole process was 545 // SIGKILLed in the mean time. In any case, we can't do anything about that 546 // now. 547 return; 548 } 549 if (WIFEXITED(status)) { 550 LLDB_LOG(log, 551 "waiting for tid {0} returned an 'exited' event. Not " 552 "tracking the thread.", 553 tid); 554 // Also a very improbable event. 555 return; 556 } 557 558 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid); 559 NativeThreadLinux &new_thread = AddThread(tid); 560 561 ResumeThread(new_thread, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 562 ThreadWasCreated(new_thread); 563 } 564 565 void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 566 NativeThreadLinux &thread) { 567 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 568 const bool is_main_thread = (thread.GetID() == GetID()); 569 570 assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 571 572 switch (info.si_code) { 573 // TODO: these two cases are required if we want to support tracing of the 574 // inferiors' children. We'd need this to debug a monitor. case (SIGTRAP | 575 // (PTRACE_EVENT_FORK << 8)): case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 576 577 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 578 // This is the notification on the parent thread which informs us of new 579 // thread creation. We don't want to do anything with the parent thread so 580 // we just resume it. In case we want to implement "break on thread 581 // creation" functionality, we would need to stop here. 582 583 unsigned long event_message = 0; 584 if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 585 LLDB_LOG(log, 586 "pid {0} received thread creation event but " 587 "GetEventMessage failed so we don't know the new tid", 588 thread.GetID()); 589 } else 590 WaitForNewThread(event_message); 591 592 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 593 break; 594 } 595 596 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 597 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 598 599 // Exec clears any pending notifications. 600 m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 601 602 // Remove all but the main thread here. Linux fork creates a new process 603 // which only copies the main thread. 604 LLDB_LOG(log, "exec received, stop tracking all but main thread"); 605 606 for (auto i = m_threads.begin(); i != m_threads.end();) { 607 if ((*i)->GetID() == GetID()) 608 i = m_threads.erase(i); 609 else 610 ++i; 611 } 612 assert(m_threads.size() == 1); 613 auto *main_thread = static_cast<NativeThreadLinux *>(m_threads[0].get()); 614 615 SetCurrentThreadID(main_thread->GetID()); 616 main_thread->SetStoppedByExec(); 617 618 // Tell coordinator about about the "new" (since exec) stopped main thread. 619 ThreadWasCreated(*main_thread); 620 621 // Let our delegate know we have just exec'd. 622 NotifyDidExec(); 623 624 // Let the process know we're stopped. 625 StopRunningThreads(main_thread->GetID()); 626 627 break; 628 } 629 630 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 631 // The inferior process or one of its threads is about to exit. We don't 632 // want to do anything with the thread so we just resume it. In case we 633 // want to implement "break on thread exit" functionality, we would need to 634 // stop here. 635 636 unsigned long data = 0; 637 if (GetEventMessage(thread.GetID(), &data).Fail()) 638 data = -1; 639 640 LLDB_LOG(log, 641 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 642 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 643 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 644 is_main_thread); 645 646 647 StateType state = thread.GetState(); 648 if (!StateIsRunningState(state)) { 649 // Due to a kernel bug, we may sometimes get this stop after the inferior 650 // gets a SIGKILL. This confuses our state tracking logic in 651 // ResumeThread(), since normally, we should not be receiving any ptrace 652 // events while the inferior is stopped. This makes sure that the 653 // inferior is resumed and exits normally. 654 state = eStateRunning; 655 } 656 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 657 658 break; 659 } 660 661 case 0: 662 case TRAP_TRACE: // We receive this on single stepping. 663 case TRAP_HWBKPT: // We receive this on watchpoint hit 664 { 665 // If a watchpoint was hit, report it 666 uint32_t wp_index; 667 Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 668 wp_index, (uintptr_t)info.si_addr); 669 if (error.Fail()) 670 LLDB_LOG(log, 671 "received error while checking for watchpoint hits, pid = " 672 "{0}, error = {1}", 673 thread.GetID(), error); 674 if (wp_index != LLDB_INVALID_INDEX32) { 675 MonitorWatchpoint(thread, wp_index); 676 break; 677 } 678 679 // If a breakpoint was hit, report it 680 uint32_t bp_index; 681 error = thread.GetRegisterContext().GetHardwareBreakHitIndex( 682 bp_index, (uintptr_t)info.si_addr); 683 if (error.Fail()) 684 LLDB_LOG(log, "received error while checking for hardware " 685 "breakpoint hits, pid = {0}, error = {1}", 686 thread.GetID(), error); 687 if (bp_index != LLDB_INVALID_INDEX32) { 688 MonitorBreakpoint(thread); 689 break; 690 } 691 692 // Otherwise, report step over 693 MonitorTrace(thread); 694 break; 695 } 696 697 case SI_KERNEL: 698 #if defined __mips__ 699 // For mips there is no special signal for watchpoint So we check for 700 // watchpoint in kernel trap 701 { 702 // If a watchpoint was hit, report it 703 uint32_t wp_index; 704 Status error = thread.GetRegisterContext().GetWatchpointHitIndex( 705 wp_index, LLDB_INVALID_ADDRESS); 706 if (error.Fail()) 707 LLDB_LOG(log, 708 "received error while checking for watchpoint hits, pid = " 709 "{0}, error = {1}", 710 thread.GetID(), error); 711 if (wp_index != LLDB_INVALID_INDEX32) { 712 MonitorWatchpoint(thread, wp_index); 713 break; 714 } 715 } 716 // NO BREAK 717 #endif 718 case TRAP_BRKPT: 719 MonitorBreakpoint(thread); 720 break; 721 722 case SIGTRAP: 723 case (SIGTRAP | 0x80): 724 LLDB_LOG( 725 log, 726 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 727 info.si_code, GetID(), thread.GetID()); 728 729 // Ignore these signals until we know more about them. 730 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 731 break; 732 733 default: 734 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 735 info.si_code, GetID(), thread.GetID()); 736 MonitorSignal(info, thread, false); 737 break; 738 } 739 } 740 741 void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 742 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 743 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 744 745 // This thread is currently stopped. 746 thread.SetStoppedByTrace(); 747 748 StopRunningThreads(thread.GetID()); 749 } 750 751 void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 752 Log *log( 753 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 754 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 755 756 // Mark the thread as stopped at breakpoint. 757 thread.SetStoppedByBreakpoint(); 758 FixupBreakpointPCAsNeeded(thread); 759 760 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 761 m_threads_stepping_with_breakpoint.end()) 762 thread.SetStoppedByTrace(); 763 764 StopRunningThreads(thread.GetID()); 765 } 766 767 void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 768 uint32_t wp_index) { 769 Log *log( 770 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 771 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 772 thread.GetID(), wp_index); 773 774 // Mark the thread as stopped at watchpoint. The address is at 775 // (lldb::addr_t)info->si_addr if we need it. 776 thread.SetStoppedByWatchpoint(wp_index); 777 778 // We need to tell all other running threads before we notify the delegate 779 // about this stop. 780 StopRunningThreads(thread.GetID()); 781 } 782 783 void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 784 NativeThreadLinux &thread, bool exited) { 785 const int signo = info.si_signo; 786 const bool is_from_llgs = info.si_pid == getpid(); 787 788 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 789 790 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 791 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a kill(2) 792 // or raise(3). Similarly for tgkill(2) on Linux. 793 // 794 // IOW, user generated signals never generate what we consider to be a 795 // "crash". 796 // 797 // Similarly, ACK signals generated by this monitor. 798 799 // Handle the signal. 800 LLDB_LOG(log, 801 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 802 "waitpid pid = {4})", 803 Host::GetSignalAsCString(signo), signo, info.si_code, 804 thread.GetID()); 805 806 // Check for thread stop notification. 807 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 808 // This is a tgkill()-based stop. 809 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 810 811 // Check that we're not already marked with a stop reason. Note this thread 812 // really shouldn't already be marked as stopped - if we were, that would 813 // imply that the kernel signaled us with the thread stopping which we 814 // handled and marked as stopped, and that, without an intervening resume, 815 // we received another stop. It is more likely that we are missing the 816 // marking of a run state somewhere if we find that the thread was marked 817 // as stopped. 818 const StateType thread_state = thread.GetState(); 819 if (!StateIsStoppedState(thread_state, false)) { 820 // An inferior thread has stopped because of a SIGSTOP we have sent it. 821 // Generally, these are not important stops and we don't want to report 822 // them as they are just used to stop other threads when one thread (the 823 // one with the *real* stop reason) hits a breakpoint (watchpoint, 824 // etc...). However, in the case of an asynchronous Interrupt(), this 825 // *is* the real stop reason, so we leave the signal intact if this is 826 // the thread that was chosen as the triggering thread. 827 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 828 if (m_pending_notification_tid == thread.GetID()) 829 thread.SetStoppedBySignal(SIGSTOP, &info); 830 else 831 thread.SetStoppedWithNoReason(); 832 833 SetCurrentThreadID(thread.GetID()); 834 SignalIfAllThreadsStopped(); 835 } else { 836 // We can end up here if stop was initiated by LLGS but by this time a 837 // thread stop has occurred - maybe initiated by another event. 838 Status error = ResumeThread(thread, thread.GetState(), 0); 839 if (error.Fail()) 840 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 841 error); 842 } 843 } else { 844 LLDB_LOG(log, 845 "pid {0} tid {1}, thread was already marked as a stopped " 846 "state (state={2}), leaving stop signal as is", 847 GetID(), thread.GetID(), thread_state); 848 SignalIfAllThreadsStopped(); 849 } 850 851 // Done handling. 852 return; 853 } 854 855 // Check if debugger should stop at this signal or just ignore it and resume 856 // the inferior. 857 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 858 ResumeThread(thread, thread.GetState(), signo); 859 return; 860 } 861 862 // This thread is stopped. 863 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 864 thread.SetStoppedBySignal(signo, &info); 865 866 // Send a stop to the debugger after we get all other threads to stop. 867 StopRunningThreads(thread.GetID()); 868 } 869 870 namespace { 871 872 struct EmulatorBaton { 873 NativeProcessLinux &m_process; 874 NativeRegisterContext &m_reg_context; 875 876 // eRegisterKindDWARF -> RegsiterValue 877 std::unordered_map<uint32_t, RegisterValue> m_register_values; 878 879 EmulatorBaton(NativeProcessLinux &process, NativeRegisterContext ®_context) 880 : m_process(process), m_reg_context(reg_context) {} 881 }; 882 883 } // anonymous namespace 884 885 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 886 const EmulateInstruction::Context &context, 887 lldb::addr_t addr, void *dst, size_t length) { 888 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 889 890 size_t bytes_read; 891 emulator_baton->m_process.ReadMemory(addr, dst, length, bytes_read); 892 return bytes_read; 893 } 894 895 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 896 const RegisterInfo *reg_info, 897 RegisterValue ®_value) { 898 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 899 900 auto it = emulator_baton->m_register_values.find( 901 reg_info->kinds[eRegisterKindDWARF]); 902 if (it != emulator_baton->m_register_values.end()) { 903 reg_value = it->second; 904 return true; 905 } 906 907 // The emulator only fill in the dwarf regsiter numbers (and in some case the 908 // generic register numbers). Get the full register info from the register 909 // context based on the dwarf register numbers. 910 const RegisterInfo *full_reg_info = 911 emulator_baton->m_reg_context.GetRegisterInfo( 912 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 913 914 Status error = 915 emulator_baton->m_reg_context.ReadRegister(full_reg_info, reg_value); 916 if (error.Success()) 917 return true; 918 919 return false; 920 } 921 922 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 923 const EmulateInstruction::Context &context, 924 const RegisterInfo *reg_info, 925 const RegisterValue ®_value) { 926 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 927 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 928 reg_value; 929 return true; 930 } 931 932 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 933 const EmulateInstruction::Context &context, 934 lldb::addr_t addr, const void *dst, 935 size_t length) { 936 return length; 937 } 938 939 static lldb::addr_t ReadFlags(NativeRegisterContext ®siter_context) { 940 const RegisterInfo *flags_info = regsiter_context.GetRegisterInfo( 941 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 942 return regsiter_context.ReadRegisterAsUnsigned(flags_info, 943 LLDB_INVALID_ADDRESS); 944 } 945 946 Status 947 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 948 Status error; 949 NativeRegisterContext& register_context = thread.GetRegisterContext(); 950 951 std::unique_ptr<EmulateInstruction> emulator_ap( 952 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 953 nullptr)); 954 955 if (emulator_ap == nullptr) 956 return Status("Instruction emulator not found!"); 957 958 EmulatorBaton baton(*this, register_context); 959 emulator_ap->SetBaton(&baton); 960 emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 961 emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 962 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 963 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 964 965 if (!emulator_ap->ReadInstruction()) 966 return Status("Read instruction failed!"); 967 968 bool emulation_result = 969 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 970 971 const RegisterInfo *reg_info_pc = register_context.GetRegisterInfo( 972 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 973 const RegisterInfo *reg_info_flags = register_context.GetRegisterInfo( 974 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 975 976 auto pc_it = 977 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 978 auto flags_it = 979 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 980 981 lldb::addr_t next_pc; 982 lldb::addr_t next_flags; 983 if (emulation_result) { 984 assert(pc_it != baton.m_register_values.end() && 985 "Emulation was successfull but PC wasn't updated"); 986 next_pc = pc_it->second.GetAsUInt64(); 987 988 if (flags_it != baton.m_register_values.end()) 989 next_flags = flags_it->second.GetAsUInt64(); 990 else 991 next_flags = ReadFlags(register_context); 992 } else if (pc_it == baton.m_register_values.end()) { 993 // Emulate instruction failed and it haven't changed PC. Advance PC with 994 // the size of the current opcode because the emulation of all 995 // PC modifying instruction should be successful. The failure most 996 // likely caused by a not supported instruction which don't modify PC. 997 next_pc = register_context.GetPC() + emulator_ap->GetOpcode().GetByteSize(); 998 next_flags = ReadFlags(register_context); 999 } else { 1000 // The instruction emulation failed after it modified the PC. It is an 1001 // unknown error where we can't continue because the next instruction is 1002 // modifying the PC but we don't know how. 1003 return Status("Instruction emulation failed unexpectedly."); 1004 } 1005 1006 if (m_arch.GetMachine() == llvm::Triple::arm) { 1007 if (next_flags & 0x20) { 1008 // Thumb mode 1009 error = SetSoftwareBreakpoint(next_pc, 2); 1010 } else { 1011 // Arm mode 1012 error = SetSoftwareBreakpoint(next_pc, 4); 1013 } 1014 } else if (m_arch.GetMachine() == llvm::Triple::mips64 || 1015 m_arch.GetMachine() == llvm::Triple::mips64el || 1016 m_arch.GetMachine() == llvm::Triple::mips || 1017 m_arch.GetMachine() == llvm::Triple::mipsel || 1018 m_arch.GetMachine() == llvm::Triple::ppc64le) 1019 error = SetSoftwareBreakpoint(next_pc, 4); 1020 else { 1021 // No size hint is given for the next breakpoint 1022 error = SetSoftwareBreakpoint(next_pc, 0); 1023 } 1024 1025 // If setting the breakpoint fails because next_pc is out of the address 1026 // space, ignore it and let the debugee segfault. 1027 if (error.GetError() == EIO || error.GetError() == EFAULT) { 1028 return Status(); 1029 } else if (error.Fail()) 1030 return error; 1031 1032 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1033 1034 return Status(); 1035 } 1036 1037 bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1038 if (m_arch.GetMachine() == llvm::Triple::arm || 1039 m_arch.GetMachine() == llvm::Triple::mips64 || 1040 m_arch.GetMachine() == llvm::Triple::mips64el || 1041 m_arch.GetMachine() == llvm::Triple::mips || 1042 m_arch.GetMachine() == llvm::Triple::mipsel) 1043 return false; 1044 return true; 1045 } 1046 1047 Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1048 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1049 LLDB_LOG(log, "pid {0}", GetID()); 1050 1051 bool software_single_step = !SupportHardwareSingleStepping(); 1052 1053 if (software_single_step) { 1054 for (const auto &thread : m_threads) { 1055 assert(thread && "thread list should not contain NULL threads"); 1056 1057 const ResumeAction *const action = 1058 resume_actions.GetActionForThread(thread->GetID(), true); 1059 if (action == nullptr) 1060 continue; 1061 1062 if (action->state == eStateStepping) { 1063 Status error = SetupSoftwareSingleStepping( 1064 static_cast<NativeThreadLinux &>(*thread)); 1065 if (error.Fail()) 1066 return error; 1067 } 1068 } 1069 } 1070 1071 for (const auto &thread : m_threads) { 1072 assert(thread && "thread list should not contain NULL threads"); 1073 1074 const ResumeAction *const action = 1075 resume_actions.GetActionForThread(thread->GetID(), true); 1076 1077 if (action == nullptr) { 1078 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1079 thread->GetID()); 1080 continue; 1081 } 1082 1083 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1084 action->state, GetID(), thread->GetID()); 1085 1086 switch (action->state) { 1087 case eStateRunning: 1088 case eStateStepping: { 1089 // Run the thread, possibly feeding it the signal. 1090 const int signo = action->signal; 1091 ResumeThread(static_cast<NativeThreadLinux &>(*thread), action->state, 1092 signo); 1093 break; 1094 } 1095 1096 case eStateSuspended: 1097 case eStateStopped: 1098 llvm_unreachable("Unexpected state"); 1099 1100 default: 1101 return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1102 "for pid %" PRIu64 ", tid %" PRIu64, 1103 __FUNCTION__, StateAsCString(action->state), GetID(), 1104 thread->GetID()); 1105 } 1106 } 1107 1108 return Status(); 1109 } 1110 1111 Status NativeProcessLinux::Halt() { 1112 Status error; 1113 1114 if (kill(GetID(), SIGSTOP) != 0) 1115 error.SetErrorToErrno(); 1116 1117 return error; 1118 } 1119 1120 Status NativeProcessLinux::Detach() { 1121 Status error; 1122 1123 // Stop monitoring the inferior. 1124 m_sigchld_handle.reset(); 1125 1126 // Tell ptrace to detach from the process. 1127 if (GetID() == LLDB_INVALID_PROCESS_ID) 1128 return error; 1129 1130 for (const auto &thread : m_threads) { 1131 Status e = Detach(thread->GetID()); 1132 if (e.Fail()) 1133 error = 1134 e; // Save the error, but still attempt to detach from other threads. 1135 } 1136 1137 m_processor_trace_monitor.clear(); 1138 m_pt_proces_trace_id = LLDB_INVALID_UID; 1139 1140 return error; 1141 } 1142 1143 Status NativeProcessLinux::Signal(int signo) { 1144 Status error; 1145 1146 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1147 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1148 Host::GetSignalAsCString(signo), GetID()); 1149 1150 if (kill(GetID(), signo)) 1151 error.SetErrorToErrno(); 1152 1153 return error; 1154 } 1155 1156 Status NativeProcessLinux::Interrupt() { 1157 // Pick a running thread (or if none, a not-dead stopped thread) as the 1158 // chosen thread that will be the stop-reason thread. 1159 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1160 1161 NativeThreadProtocol *running_thread = nullptr; 1162 NativeThreadProtocol *stopped_thread = nullptr; 1163 1164 LLDB_LOG(log, "selecting running thread for interrupt target"); 1165 for (const auto &thread : m_threads) { 1166 // If we have a running or stepping thread, we'll call that the target of 1167 // the interrupt. 1168 const auto thread_state = thread->GetState(); 1169 if (thread_state == eStateRunning || thread_state == eStateStepping) { 1170 running_thread = thread.get(); 1171 break; 1172 } else if (!stopped_thread && StateIsStoppedState(thread_state, true)) { 1173 // Remember the first non-dead stopped thread. We'll use that as a 1174 // backup if there are no running threads. 1175 stopped_thread = thread.get(); 1176 } 1177 } 1178 1179 if (!running_thread && !stopped_thread) { 1180 Status error("found no running/stepping or live stopped threads as target " 1181 "for interrupt"); 1182 LLDB_LOG(log, "skipping due to error: {0}", error); 1183 1184 return error; 1185 } 1186 1187 NativeThreadProtocol *deferred_signal_thread = 1188 running_thread ? running_thread : stopped_thread; 1189 1190 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1191 running_thread ? "running" : "stopped", 1192 deferred_signal_thread->GetID()); 1193 1194 StopRunningThreads(deferred_signal_thread->GetID()); 1195 1196 return Status(); 1197 } 1198 1199 Status NativeProcessLinux::Kill() { 1200 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1201 LLDB_LOG(log, "pid {0}", GetID()); 1202 1203 Status error; 1204 1205 switch (m_state) { 1206 case StateType::eStateInvalid: 1207 case StateType::eStateExited: 1208 case StateType::eStateCrashed: 1209 case StateType::eStateDetached: 1210 case StateType::eStateUnloaded: 1211 // Nothing to do - the process is already dead. 1212 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 1213 m_state); 1214 return error; 1215 1216 case StateType::eStateConnected: 1217 case StateType::eStateAttaching: 1218 case StateType::eStateLaunching: 1219 case StateType::eStateStopped: 1220 case StateType::eStateRunning: 1221 case StateType::eStateStepping: 1222 case StateType::eStateSuspended: 1223 // We can try to kill a process in these states. 1224 break; 1225 } 1226 1227 if (kill(GetID(), SIGKILL) != 0) { 1228 error.SetErrorToErrno(); 1229 return error; 1230 } 1231 1232 return error; 1233 } 1234 1235 static Status 1236 ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line, 1237 MemoryRegionInfo &memory_region_info) { 1238 memory_region_info.Clear(); 1239 1240 StringExtractor line_extractor(maps_line); 1241 1242 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode 1243 // pathname perms: rwxp (letter is present if set, '-' if not, final 1244 // character is p=private, s=shared). 1245 1246 // Parse out the starting address 1247 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0); 1248 1249 // Parse out hyphen separating start and end address from range. 1250 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-')) 1251 return Status( 1252 "malformed /proc/{pid}/maps entry, missing dash between address range"); 1253 1254 // Parse out the ending address 1255 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address); 1256 1257 // Parse out the space after the address. 1258 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' ')) 1259 return Status( 1260 "malformed /proc/{pid}/maps entry, missing space after range"); 1261 1262 // Save the range. 1263 memory_region_info.GetRange().SetRangeBase(start_address); 1264 memory_region_info.GetRange().SetRangeEnd(end_address); 1265 1266 // Any memory region in /proc/{pid}/maps is by definition mapped into the 1267 // process. 1268 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 1269 1270 // Parse out each permission entry. 1271 if (line_extractor.GetBytesLeft() < 4) 1272 return Status("malformed /proc/{pid}/maps entry, missing some portion of " 1273 "permissions"); 1274 1275 // Handle read permission. 1276 const char read_perm_char = line_extractor.GetChar(); 1277 if (read_perm_char == 'r') 1278 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 1279 else if (read_perm_char == '-') 1280 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1281 else 1282 return Status("unexpected /proc/{pid}/maps read permission char"); 1283 1284 // Handle write permission. 1285 const char write_perm_char = line_extractor.GetChar(); 1286 if (write_perm_char == 'w') 1287 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 1288 else if (write_perm_char == '-') 1289 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1290 else 1291 return Status("unexpected /proc/{pid}/maps write permission char"); 1292 1293 // Handle execute permission. 1294 const char exec_perm_char = line_extractor.GetChar(); 1295 if (exec_perm_char == 'x') 1296 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 1297 else if (exec_perm_char == '-') 1298 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1299 else 1300 return Status("unexpected /proc/{pid}/maps exec permission char"); 1301 1302 line_extractor.GetChar(); // Read the private bit 1303 line_extractor.SkipSpaces(); // Skip the separator 1304 line_extractor.GetHexMaxU64(false, 0); // Read the offset 1305 line_extractor.GetHexMaxU64(false, 0); // Read the major device number 1306 line_extractor.GetChar(); // Read the device id separator 1307 line_extractor.GetHexMaxU64(false, 0); // Read the major device number 1308 line_extractor.SkipSpaces(); // Skip the separator 1309 line_extractor.GetU64(0, 10); // Read the inode number 1310 1311 line_extractor.SkipSpaces(); 1312 const char *name = line_extractor.Peek(); 1313 if (name) 1314 memory_region_info.SetName(name); 1315 1316 return Status(); 1317 } 1318 1319 Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1320 MemoryRegionInfo &range_info) { 1321 // FIXME review that the final memory region returned extends to the end of 1322 // the virtual address space, 1323 // with no perms if it is not mapped. 1324 1325 // Use an approach that reads memory regions from /proc/{pid}/maps. Assume 1326 // proc maps entries are in ascending order. 1327 // FIXME assert if we find differently. 1328 1329 if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1330 // We're done. 1331 return Status("unsupported"); 1332 } 1333 1334 Status error = PopulateMemoryRegionCache(); 1335 if (error.Fail()) { 1336 return error; 1337 } 1338 1339 lldb::addr_t prev_base_address = 0; 1340 1341 // FIXME start by finding the last region that is <= target address using 1342 // binary search. Data is sorted. 1343 // There can be a ton of regions on pthreads apps with lots of threads. 1344 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1345 ++it) { 1346 MemoryRegionInfo &proc_entry_info = it->first; 1347 1348 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1349 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1350 "descending /proc/pid/maps entries detected, unexpected"); 1351 prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1352 UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1353 1354 // If the target address comes before this entry, indicate distance to next 1355 // region. 1356 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1357 range_info.GetRange().SetRangeBase(load_addr); 1358 range_info.GetRange().SetByteSize( 1359 proc_entry_info.GetRange().GetRangeBase() - load_addr); 1360 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1361 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1362 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1363 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1364 1365 return error; 1366 } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1367 // The target address is within the memory region we're processing here. 1368 range_info = proc_entry_info; 1369 return error; 1370 } 1371 1372 // The target memory address comes somewhere after the region we just 1373 // parsed. 1374 } 1375 1376 // If we made it here, we didn't find an entry that contained the given 1377 // address. Return the load_addr as start and the amount of bytes betwwen 1378 // load address and the end of the memory as size. 1379 range_info.GetRange().SetRangeBase(load_addr); 1380 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 1381 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1382 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1383 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1384 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1385 return error; 1386 } 1387 1388 Status NativeProcessLinux::PopulateMemoryRegionCache() { 1389 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1390 1391 // If our cache is empty, pull the latest. There should always be at least 1392 // one memory region if memory region handling is supported. 1393 if (!m_mem_region_cache.empty()) { 1394 LLDB_LOG(log, "reusing {0} cached memory region entries", 1395 m_mem_region_cache.size()); 1396 return Status(); 1397 } 1398 1399 auto BufferOrError = getProcFile(GetID(), "maps"); 1400 if (!BufferOrError) { 1401 m_supports_mem_region = LazyBool::eLazyBoolNo; 1402 return BufferOrError.getError(); 1403 } 1404 StringRef Rest = BufferOrError.get()->getBuffer(); 1405 while (! Rest.empty()) { 1406 StringRef Line; 1407 std::tie(Line, Rest) = Rest.split('\n'); 1408 MemoryRegionInfo info; 1409 const Status parse_error = 1410 ParseMemoryRegionInfoFromProcMapsLine(Line, info); 1411 if (parse_error.Fail()) { 1412 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line, 1413 parse_error); 1414 m_supports_mem_region = LazyBool::eLazyBoolNo; 1415 return parse_error; 1416 } 1417 FileSpec file_spec(info.GetName().GetCString()); 1418 FileSystem::Instance().Resolve(file_spec); 1419 m_mem_region_cache.emplace_back(info, file_spec); 1420 } 1421 1422 if (m_mem_region_cache.empty()) { 1423 // No entries after attempting to read them. This shouldn't happen if 1424 // /proc/{pid}/maps is supported. Assume we don't support map entries via 1425 // procfs. 1426 m_supports_mem_region = LazyBool::eLazyBoolNo; 1427 LLDB_LOG(log, 1428 "failed to find any procfs maps entries, assuming no support " 1429 "for memory region metadata retrieval"); 1430 return Status("not supported"); 1431 } 1432 1433 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1434 m_mem_region_cache.size(), GetID()); 1435 1436 // We support memory retrieval, remember that. 1437 m_supports_mem_region = LazyBool::eLazyBoolYes; 1438 return Status(); 1439 } 1440 1441 void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1442 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1443 LLDB_LOG(log, "newBumpId={0}", newBumpId); 1444 LLDB_LOG(log, "clearing {0} entries from memory region cache", 1445 m_mem_region_cache.size()); 1446 m_mem_region_cache.clear(); 1447 } 1448 1449 Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, 1450 lldb::addr_t &addr) { 1451 // FIXME implementing this requires the equivalent of 1452 // InferiorCallPOSIX::InferiorCallMmap, which depends on functional ThreadPlans 1453 // working with Native*Protocol. 1454 #if 1 1455 return Status("not implemented yet"); 1456 #else 1457 addr = LLDB_INVALID_ADDRESS; 1458 1459 unsigned prot = 0; 1460 if (permissions & lldb::ePermissionsReadable) 1461 prot |= eMmapProtRead; 1462 if (permissions & lldb::ePermissionsWritable) 1463 prot |= eMmapProtWrite; 1464 if (permissions & lldb::ePermissionsExecutable) 1465 prot |= eMmapProtExec; 1466 1467 // TODO implement this directly in NativeProcessLinux 1468 // (and lift to NativeProcessPOSIX if/when that class is refactored out). 1469 if (InferiorCallMmap(this, addr, 0, size, prot, 1470 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 1471 m_addr_to_mmap_size[addr] = size; 1472 return Status(); 1473 } else { 1474 addr = LLDB_INVALID_ADDRESS; 1475 return Status("unable to allocate %" PRIu64 1476 " bytes of memory with permissions %s", 1477 size, GetPermissionsAsCString(permissions)); 1478 } 1479 #endif 1480 } 1481 1482 Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 1483 // FIXME see comments in AllocateMemory - required lower-level 1484 // bits not in place yet (ThreadPlans) 1485 return Status("not implemented"); 1486 } 1487 1488 lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() { 1489 // punt on this for now 1490 return LLDB_INVALID_ADDRESS; 1491 } 1492 1493 size_t NativeProcessLinux::UpdateThreads() { 1494 // The NativeProcessLinux monitoring threads are always up to date with 1495 // respect to thread state and they keep the thread list populated properly. 1496 // All this method needs to do is return the thread count. 1497 return m_threads.size(); 1498 } 1499 1500 Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1501 bool hardware) { 1502 if (hardware) 1503 return SetHardwareBreakpoint(addr, size); 1504 else 1505 return SetSoftwareBreakpoint(addr, size); 1506 } 1507 1508 Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1509 if (hardware) 1510 return RemoveHardwareBreakpoint(addr); 1511 else 1512 return NativeProcessProtocol::RemoveBreakpoint(addr); 1513 } 1514 1515 llvm::Expected<llvm::ArrayRef<uint8_t>> 1516 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode(size_t size_hint) { 1517 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1518 // linux kernel does otherwise. 1519 static const uint8_t g_arm_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1520 static const uint8_t g_thumb_opcode[] = {0x01, 0xde}; 1521 1522 switch (GetArchitecture().GetMachine()) { 1523 case llvm::Triple::arm: 1524 switch (size_hint) { 1525 case 2: 1526 return llvm::makeArrayRef(g_thumb_opcode); 1527 case 4: 1528 return llvm::makeArrayRef(g_arm_opcode); 1529 default: 1530 return llvm::createStringError(llvm::inconvertibleErrorCode(), 1531 "Unrecognised trap opcode size hint!"); 1532 } 1533 default: 1534 return NativeProcessProtocol::GetSoftwareBreakpointTrapOpcode(size_hint); 1535 } 1536 } 1537 1538 Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1539 size_t &bytes_read) { 1540 if (ProcessVmReadvSupported()) { 1541 // The process_vm_readv path is about 50 times faster than ptrace api. We 1542 // want to use this syscall if it is supported. 1543 1544 const ::pid_t pid = GetID(); 1545 1546 struct iovec local_iov, remote_iov; 1547 local_iov.iov_base = buf; 1548 local_iov.iov_len = size; 1549 remote_iov.iov_base = reinterpret_cast<void *>(addr); 1550 remote_iov.iov_len = size; 1551 1552 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1553 const bool success = bytes_read == size; 1554 1555 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1556 LLDB_LOG(log, 1557 "using process_vm_readv to read {0} bytes from inferior " 1558 "address {1:x}: {2}", 1559 size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1560 1561 if (success) 1562 return Status(); 1563 // else the call failed for some reason, let's retry the read using ptrace 1564 // api. 1565 } 1566 1567 unsigned char *dst = static_cast<unsigned char *>(buf); 1568 size_t remainder; 1569 long data; 1570 1571 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1572 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 1573 1574 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 1575 Status error = NativeProcessLinux::PtraceWrapper( 1576 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1577 if (error.Fail()) 1578 return error; 1579 1580 remainder = size - bytes_read; 1581 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 1582 1583 // Copy the data into our buffer 1584 memcpy(dst, &data, remainder); 1585 1586 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1587 addr += k_ptrace_word_size; 1588 dst += k_ptrace_word_size; 1589 } 1590 return Status(); 1591 } 1592 1593 Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1594 size_t size, size_t &bytes_written) { 1595 const unsigned char *src = static_cast<const unsigned char *>(buf); 1596 size_t remainder; 1597 Status error; 1598 1599 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1600 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 1601 1602 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 1603 remainder = size - bytes_written; 1604 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 1605 1606 if (remainder == k_ptrace_word_size) { 1607 unsigned long data = 0; 1608 memcpy(&data, src, k_ptrace_word_size); 1609 1610 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1611 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1612 (void *)addr, (void *)data); 1613 if (error.Fail()) 1614 return error; 1615 } else { 1616 unsigned char buff[8]; 1617 size_t bytes_read; 1618 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1619 if (error.Fail()) 1620 return error; 1621 1622 memcpy(buff, src, remainder); 1623 1624 size_t bytes_written_rec; 1625 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1626 if (error.Fail()) 1627 return error; 1628 1629 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1630 *(unsigned long *)buff); 1631 } 1632 1633 addr += k_ptrace_word_size; 1634 src += k_ptrace_word_size; 1635 } 1636 return error; 1637 } 1638 1639 Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 1640 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1641 } 1642 1643 Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1644 unsigned long *message) { 1645 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1646 } 1647 1648 Status NativeProcessLinux::Detach(lldb::tid_t tid) { 1649 if (tid == LLDB_INVALID_THREAD_ID) 1650 return Status(); 1651 1652 return PtraceWrapper(PTRACE_DETACH, tid); 1653 } 1654 1655 bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1656 for (const auto &thread : m_threads) { 1657 assert(thread && "thread list should not contain NULL threads"); 1658 if (thread->GetID() == thread_id) { 1659 // We have this thread. 1660 return true; 1661 } 1662 } 1663 1664 // We don't have this thread. 1665 return false; 1666 } 1667 1668 bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1669 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1670 LLDB_LOG(log, "tid: {0})", thread_id); 1671 1672 bool found = false; 1673 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1674 if (*it && ((*it)->GetID() == thread_id)) { 1675 m_threads.erase(it); 1676 found = true; 1677 break; 1678 } 1679 } 1680 1681 if (found) 1682 StopTracingForThread(thread_id); 1683 SignalIfAllThreadsStopped(); 1684 return found; 1685 } 1686 1687 NativeThreadLinux &NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 1688 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 1689 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 1690 1691 assert(!HasThreadNoLock(thread_id) && 1692 "attempted to add a thread by id that already exists"); 1693 1694 // If this is the first thread, save it as the current thread 1695 if (m_threads.empty()) 1696 SetCurrentThreadID(thread_id); 1697 1698 m_threads.push_back(llvm::make_unique<NativeThreadLinux>(*this, thread_id)); 1699 1700 if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 1701 auto traceMonitor = ProcessorTraceMonitor::Create( 1702 GetID(), thread_id, m_pt_process_trace_config, true); 1703 if (traceMonitor) { 1704 m_pt_traced_thread_group.insert(thread_id); 1705 m_processor_trace_monitor.insert( 1706 std::make_pair(thread_id, std::move(*traceMonitor))); 1707 } else { 1708 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 1709 Status error(traceMonitor.takeError()); 1710 LLDB_LOG(log, "error {0}", error); 1711 } 1712 } 1713 1714 return static_cast<NativeThreadLinux &>(*m_threads.back()); 1715 } 1716 1717 Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 1718 FileSpec &file_spec) { 1719 Status error = PopulateMemoryRegionCache(); 1720 if (error.Fail()) 1721 return error; 1722 1723 FileSpec module_file_spec(module_path); 1724 FileSystem::Instance().Resolve(module_file_spec); 1725 1726 file_spec.Clear(); 1727 for (const auto &it : m_mem_region_cache) { 1728 if (it.second.GetFilename() == module_file_spec.GetFilename()) { 1729 file_spec = it.second; 1730 return Status(); 1731 } 1732 } 1733 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 1734 module_file_spec.GetFilename().AsCString(), GetID()); 1735 } 1736 1737 Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 1738 lldb::addr_t &load_addr) { 1739 load_addr = LLDB_INVALID_ADDRESS; 1740 Status error = PopulateMemoryRegionCache(); 1741 if (error.Fail()) 1742 return error; 1743 1744 FileSpec file(file_name); 1745 for (const auto &it : m_mem_region_cache) { 1746 if (it.second == file) { 1747 load_addr = it.first.GetRange().GetRangeBase(); 1748 return Status(); 1749 } 1750 } 1751 return Status("No load address found for specified file."); 1752 } 1753 1754 NativeThreadLinux *NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 1755 return static_cast<NativeThreadLinux *>( 1756 NativeProcessProtocol::GetThreadByID(tid)); 1757 } 1758 1759 Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 1760 lldb::StateType state, int signo) { 1761 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1762 LLDB_LOG(log, "tid: {0}", thread.GetID()); 1763 1764 // Before we do the resume below, first check if we have a pending stop 1765 // notification that is currently waiting for all threads to stop. This is 1766 // potentially a buggy situation since we're ostensibly waiting for threads 1767 // to stop before we send out the pending notification, and here we are 1768 // resuming one before we send out the pending stop notification. 1769 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 1770 LLDB_LOG(log, 1771 "about to resume tid {0} per explicit request but we have a " 1772 "pending stop notification (tid {1}) that is actively " 1773 "waiting for this thread to stop. Valid sequence of events?", 1774 thread.GetID(), m_pending_notification_tid); 1775 } 1776 1777 // Request a resume. We expect this to be synchronous and the system to 1778 // reflect it is running after this completes. 1779 switch (state) { 1780 case eStateRunning: { 1781 const auto resume_result = thread.Resume(signo); 1782 if (resume_result.Success()) 1783 SetState(eStateRunning, true); 1784 return resume_result; 1785 } 1786 case eStateStepping: { 1787 const auto step_result = thread.SingleStep(signo); 1788 if (step_result.Success()) 1789 SetState(eStateRunning, true); 1790 return step_result; 1791 } 1792 default: 1793 LLDB_LOG(log, "Unhandled state {0}.", state); 1794 llvm_unreachable("Unhandled state for resume"); 1795 } 1796 } 1797 1798 //===----------------------------------------------------------------------===// 1799 1800 void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 1801 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1802 LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 1803 triggering_tid); 1804 1805 m_pending_notification_tid = triggering_tid; 1806 1807 // Request a stop for all the thread stops that need to be stopped and are 1808 // not already known to be stopped. 1809 for (const auto &thread : m_threads) { 1810 if (StateIsRunningState(thread->GetState())) 1811 static_cast<NativeThreadLinux *>(thread.get())->RequestStop(); 1812 } 1813 1814 SignalIfAllThreadsStopped(); 1815 LLDB_LOG(log, "event processing done"); 1816 } 1817 1818 void NativeProcessLinux::SignalIfAllThreadsStopped() { 1819 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 1820 return; // No pending notification. Nothing to do. 1821 1822 for (const auto &thread_sp : m_threads) { 1823 if (StateIsRunningState(thread_sp->GetState())) 1824 return; // Some threads are still running. Don't signal yet. 1825 } 1826 1827 // We have a pending notification and all threads have stopped. 1828 Log *log( 1829 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 1830 1831 // Clear any temporary breakpoints we used to implement software single 1832 // stepping. 1833 for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 1834 Status error = RemoveBreakpoint(thread_info.second); 1835 if (error.Fail()) 1836 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 1837 thread_info.first, error); 1838 } 1839 m_threads_stepping_with_breakpoint.clear(); 1840 1841 // Notify the delegate about the stop 1842 SetCurrentThreadID(m_pending_notification_tid); 1843 SetState(StateType::eStateStopped, true); 1844 m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 1845 } 1846 1847 void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 1848 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1849 LLDB_LOG(log, "tid: {0}", thread.GetID()); 1850 1851 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 1852 StateIsRunningState(thread.GetState())) { 1853 // We will need to wait for this new thread to stop as well before firing 1854 // the notification. 1855 thread.RequestStop(); 1856 } 1857 } 1858 1859 void NativeProcessLinux::SigchldHandler() { 1860 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1861 // Process all pending waitpid notifications. 1862 while (true) { 1863 int status = -1; 1864 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 1865 __WALL | __WNOTHREAD | WNOHANG); 1866 1867 if (wait_pid == 0) 1868 break; // We are done. 1869 1870 if (wait_pid == -1) { 1871 Status error(errno, eErrorTypePOSIX); 1872 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 1873 break; 1874 } 1875 1876 WaitStatus wait_status = WaitStatus::Decode(status); 1877 bool exited = wait_status.type == WaitStatus::Exit || 1878 (wait_status.type == WaitStatus::Signal && 1879 wait_pid == static_cast<::pid_t>(GetID())); 1880 1881 LLDB_LOG( 1882 log, 1883 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 1884 wait_pid, wait_status, exited); 1885 1886 MonitorCallback(wait_pid, exited, wait_status); 1887 } 1888 } 1889 1890 // Wrapper for ptrace to catch errors and log calls. Note that ptrace sets 1891 // errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 1892 Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 1893 void *data, size_t data_size, 1894 long *result) { 1895 Status error; 1896 long int ret; 1897 1898 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1899 1900 PtraceDisplayBytes(req, data, data_size); 1901 1902 errno = 0; 1903 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 1904 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1905 *(unsigned int *)addr, data); 1906 else 1907 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 1908 addr, data); 1909 1910 if (ret == -1) 1911 error.SetErrorToErrno(); 1912 1913 if (result) 1914 *result = ret; 1915 1916 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 1917 data_size, ret); 1918 1919 PtraceDisplayBytes(req, data, data_size); 1920 1921 if (error.Fail()) 1922 LLDB_LOG(log, "ptrace() failed: {0}", error); 1923 1924 return error; 1925 } 1926 1927 llvm::Expected<ProcessorTraceMonitor &> 1928 NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 1929 lldb::tid_t thread) { 1930 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1931 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 1932 LLDB_LOG(log, "thread not specified: {0}", traceid); 1933 return Status("tracing not active thread not specified").ToError(); 1934 } 1935 1936 for (auto& iter : m_processor_trace_monitor) { 1937 if (traceid == iter.second->GetTraceID() && 1938 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 1939 return *(iter.second); 1940 } 1941 1942 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 1943 return Status("tracing not active for this thread").ToError(); 1944 } 1945 1946 Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 1947 lldb::tid_t thread, 1948 llvm::MutableArrayRef<uint8_t> &buffer, 1949 size_t offset) { 1950 TraceOptions trace_options; 1951 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1952 Status error; 1953 1954 LLDB_LOG(log, "traceid {0}", traceid); 1955 1956 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 1957 if (!perf_monitor) { 1958 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 1959 buffer = buffer.slice(buffer.size()); 1960 error = perf_monitor.takeError(); 1961 return error; 1962 } 1963 return (*perf_monitor).ReadPerfTraceData(buffer, offset); 1964 } 1965 1966 Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 1967 llvm::MutableArrayRef<uint8_t> &buffer, 1968 size_t offset) { 1969 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 1970 Status error; 1971 1972 LLDB_LOG(log, "traceid {0}", traceid); 1973 1974 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 1975 if (!perf_monitor) { 1976 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 1977 buffer = buffer.slice(buffer.size()); 1978 error = perf_monitor.takeError(); 1979 return error; 1980 } 1981 return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 1982 } 1983 1984 Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 1985 TraceOptions &config) { 1986 Status error; 1987 if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 1988 m_pt_proces_trace_id == traceid) { 1989 if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 1990 error.SetErrorString("tracing not active for this process"); 1991 return error; 1992 } 1993 config = m_pt_process_trace_config; 1994 } else { 1995 auto perf_monitor = 1996 LookupProcessorTraceInstance(traceid, config.getThreadID()); 1997 if (!perf_monitor) { 1998 error = perf_monitor.takeError(); 1999 return error; 2000 } 2001 error = (*perf_monitor).GetTraceConfig(config); 2002 } 2003 return error; 2004 } 2005 2006 lldb::user_id_t 2007 NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 2008 Status &error) { 2009 2010 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2011 if (config.getType() != TraceType::eTraceTypeProcessorTrace) 2012 return LLDB_INVALID_UID; 2013 2014 if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 2015 error.SetErrorString("tracing already active on this process"); 2016 return m_pt_proces_trace_id; 2017 } 2018 2019 for (const auto &thread_sp : m_threads) { 2020 if (auto traceInstance = ProcessorTraceMonitor::Create( 2021 GetID(), thread_sp->GetID(), config, true)) { 2022 m_pt_traced_thread_group.insert(thread_sp->GetID()); 2023 m_processor_trace_monitor.insert( 2024 std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 2025 } 2026 } 2027 2028 m_pt_process_trace_config = config; 2029 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 2030 2031 // Trace on Complete process will have traceid of 0 2032 m_pt_proces_trace_id = 0; 2033 2034 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 2035 return m_pt_proces_trace_id; 2036 } 2037 2038 lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 2039 Status &error) { 2040 if (config.getType() != TraceType::eTraceTypeProcessorTrace) 2041 return NativeProcessProtocol::StartTrace(config, error); 2042 2043 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2044 2045 lldb::tid_t threadid = config.getThreadID(); 2046 2047 if (threadid == LLDB_INVALID_THREAD_ID) 2048 return StartTraceGroup(config, error); 2049 2050 auto thread_sp = GetThreadByID(threadid); 2051 if (!thread_sp) { 2052 // Thread not tracked by lldb so don't trace. 2053 error.SetErrorString("invalid thread id"); 2054 return LLDB_INVALID_UID; 2055 } 2056 2057 const auto &iter = m_processor_trace_monitor.find(threadid); 2058 if (iter != m_processor_trace_monitor.end()) { 2059 LLDB_LOG(log, "Thread already being traced"); 2060 error.SetErrorString("tracing already active on this thread"); 2061 return LLDB_INVALID_UID; 2062 } 2063 2064 auto traceMonitor = 2065 ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 2066 if (!traceMonitor) { 2067 error = traceMonitor.takeError(); 2068 LLDB_LOG(log, "error {0}", error); 2069 return LLDB_INVALID_UID; 2070 } 2071 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 2072 m_processor_trace_monitor.insert( 2073 std::make_pair(threadid, std::move(*traceMonitor))); 2074 return ret_trace_id; 2075 } 2076 2077 Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 2078 Status error; 2079 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2080 LLDB_LOG(log, "Thread {0}", thread); 2081 2082 const auto& iter = m_processor_trace_monitor.find(thread); 2083 if (iter == m_processor_trace_monitor.end()) { 2084 error.SetErrorString("tracing not active for this thread"); 2085 return error; 2086 } 2087 2088 if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 2089 // traceid maps to the whole process so we have to erase it from the thread 2090 // group. 2091 LLDB_LOG(log, "traceid maps to process"); 2092 m_pt_traced_thread_group.erase(thread); 2093 } 2094 m_processor_trace_monitor.erase(iter); 2095 2096 return error; 2097 } 2098 2099 Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 2100 lldb::tid_t thread) { 2101 Status error; 2102 2103 TraceOptions trace_options; 2104 trace_options.setThreadID(thread); 2105 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 2106 2107 if (error.Fail()) 2108 return error; 2109 2110 switch (trace_options.getType()) { 2111 case lldb::TraceType::eTraceTypeProcessorTrace: 2112 if (traceid == m_pt_proces_trace_id && 2113 thread == LLDB_INVALID_THREAD_ID) 2114 StopProcessorTracingOnProcess(); 2115 else 2116 error = StopProcessorTracingOnThread(traceid, thread); 2117 break; 2118 default: 2119 error.SetErrorString("trace not supported"); 2120 break; 2121 } 2122 2123 return error; 2124 } 2125 2126 void NativeProcessLinux::StopProcessorTracingOnProcess() { 2127 for (auto thread_id_iter : m_pt_traced_thread_group) 2128 m_processor_trace_monitor.erase(thread_id_iter); 2129 m_pt_traced_thread_group.clear(); 2130 m_pt_proces_trace_id = LLDB_INVALID_UID; 2131 } 2132 2133 Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 2134 lldb::tid_t thread) { 2135 Status error; 2136 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2137 2138 if (thread == LLDB_INVALID_THREAD_ID) { 2139 for (auto& iter : m_processor_trace_monitor) { 2140 if (iter.second->GetTraceID() == traceid) { 2141 // Stopping a trace instance for an individual thread hence there will 2142 // only be one traceid that can match. 2143 m_processor_trace_monitor.erase(iter.first); 2144 return error; 2145 } 2146 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 2147 } 2148 2149 LLDB_LOG(log, "Invalid TraceID"); 2150 error.SetErrorString("invalid trace id"); 2151 return error; 2152 } 2153 2154 // thread is specified so we can use find function on the map. 2155 const auto& iter = m_processor_trace_monitor.find(thread); 2156 if (iter == m_processor_trace_monitor.end()) { 2157 // thread not found in our map. 2158 LLDB_LOG(log, "thread not being traced"); 2159 error.SetErrorString("tracing not active for this thread"); 2160 return error; 2161 } 2162 if (iter->second->GetTraceID() != traceid) { 2163 // traceid did not match so it has to be invalid. 2164 LLDB_LOG(log, "Invalid TraceID"); 2165 error.SetErrorString("invalid trace id"); 2166 return error; 2167 } 2168 2169 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 2170 2171 if (traceid == m_pt_proces_trace_id) { 2172 // traceid maps to the whole process so we have to erase it from the thread 2173 // group. 2174 LLDB_LOG(log, "traceid maps to process"); 2175 m_pt_traced_thread_group.erase(thread); 2176 } 2177 m_processor_trace_monitor.erase(iter); 2178 2179 return error; 2180 } 2181