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