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/Core/RegisterValue.h" 29 #include "lldb/Core/State.h" 30 #include "lldb/Host/Host.h" 31 #include "lldb/Host/HostProcess.h" 32 #include "lldb/Host/PseudoTerminal.h" 33 #include "lldb/Host/ThreadLauncher.h" 34 #include "lldb/Host/common/NativeBreakpoint.h" 35 #include "lldb/Host/common/NativeRegisterContext.h" 36 #include "lldb/Host/linux/Ptrace.h" 37 #include "lldb/Host/linux/Uio.h" 38 #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 39 #include "lldb/Symbol/ObjectFile.h" 40 #include "lldb/Target/Process.h" 41 #include "lldb/Target/ProcessLaunchInfo.h" 42 #include "lldb/Target/Target.h" 43 #include "lldb/Utility/LLDBAssert.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 ArchSpec arch; 249 if ((status = ResolveProcessArchitecture(pid, arch)).Fail()) 250 return status.ToError(); 251 252 // Set the architecture to the exe architecture. 253 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 254 arch.GetArchitectureName()); 255 256 status = SetDefaultPtraceOpts(pid); 257 if (status.Fail()) { 258 LLDB_LOG(log, "failed to set default ptrace options: {0}", status); 259 return status.ToError(); 260 } 261 262 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 263 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate, 264 arch, mainloop, {pid})); 265 } 266 267 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 268 NativeProcessLinux::Factory::Attach( 269 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 270 MainLoop &mainloop) const { 271 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 272 LLDB_LOG(log, "pid = {0:x}", pid); 273 274 // Retrieve the architecture for the running process. 275 ArchSpec arch; 276 Status status = ResolveProcessArchitecture(pid, arch); 277 if (!status.Success()) 278 return status.ToError(); 279 280 auto tids_or = NativeProcessLinux::Attach(pid); 281 if (!tids_or) 282 return tids_or.takeError(); 283 284 return std::unique_ptr<NativeProcessLinux>(new NativeProcessLinux( 285 pid, -1, native_delegate, arch, mainloop, *tids_or)); 286 } 287 288 // ----------------------------------------------------------------------------- 289 // Public Instance Methods 290 // ----------------------------------------------------------------------------- 291 292 NativeProcessLinux::NativeProcessLinux(::pid_t pid, int terminal_fd, 293 NativeDelegate &delegate, 294 const ArchSpec &arch, MainLoop &mainloop, 295 llvm::ArrayRef<::pid_t> tids) 296 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { 297 if (m_terminal_fd != -1) { 298 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 299 assert(status.Success()); 300 } 301 302 Status status; 303 m_sigchld_handle = mainloop.RegisterSignal( 304 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 305 assert(m_sigchld_handle && status.Success()); 306 307 for (const auto &tid : tids) { 308 NativeThreadLinuxSP thread_sp = AddThread(tid); 309 assert(thread_sp && "AddThread() returned a nullptr thread"); 310 thread_sp->SetStoppedBySignal(SIGSTOP); 311 ThreadWasCreated(*thread_sp); 312 } 313 314 // Let our process instance know the thread has stopped. 315 SetCurrentThreadID(tids[0]); 316 SetState(StateType::eStateStopped, false); 317 318 // Proccess any signals we received before installing our handler 319 SigchldHandler(); 320 } 321 322 llvm::Expected<std::vector<::pid_t>> NativeProcessLinux::Attach(::pid_t pid) { 323 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 324 325 Status status; 326 // Use a map to keep track of the threads which we have attached/need to 327 // attach. 328 Host::TidMap tids_to_attach; 329 while (Host::FindProcessThreads(pid, tids_to_attach)) { 330 for (Host::TidMap::iterator it = tids_to_attach.begin(); 331 it != tids_to_attach.end();) { 332 if (it->second == false) { 333 lldb::tid_t tid = it->first; 334 335 // Attach to the requested process. 336 // An attach will cause the thread to stop with a SIGSTOP. 337 if ((status = PtraceWrapper(PTRACE_ATTACH, tid)).Fail()) { 338 // No such thread. The thread may have exited. 339 // More error handling may be needed. 340 if (status.GetError() == ESRCH) { 341 it = tids_to_attach.erase(it); 342 continue; 343 } 344 return status.ToError(); 345 } 346 347 int wpid = 348 llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, nullptr, __WALL); 349 // Need to use __WALL otherwise we receive an error with errno=ECHLD 350 // At this point we should have a thread stopped if waitpid succeeds. 351 if (wpid < 0) { 352 // No such thread. The thread may have exited. 353 // More error handling may be needed. 354 if (errno == ESRCH) { 355 it = tids_to_attach.erase(it); 356 continue; 357 } 358 return llvm::errorCodeToError( 359 std::error_code(errno, std::generic_category())); 360 } 361 362 if ((status = SetDefaultPtraceOpts(tid)).Fail()) 363 return status.ToError(); 364 365 LLDB_LOG(log, "adding tid = {0}", tid); 366 it->second = true; 367 } 368 369 // move the loop forward 370 ++it; 371 } 372 } 373 374 size_t tid_count = tids_to_attach.size(); 375 if (tid_count == 0) 376 return llvm::make_error<StringError>("No such process", 377 llvm::inconvertibleErrorCode()); 378 379 std::vector<::pid_t> tids; 380 tids.reserve(tid_count); 381 for (const auto &p : tids_to_attach) 382 tids.push_back(p.first); 383 return std::move(tids); 384 } 385 386 Status NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) { 387 long ptrace_opts = 0; 388 389 // Have the child raise an event on exit. This is used to keep the child in 390 // limbo until it is destroyed. 391 ptrace_opts |= PTRACE_O_TRACEEXIT; 392 393 // Have the tracer trace threads which spawn in the inferior process. 394 // TODO: if we want to support tracing the inferiors' child, add the 395 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 396 ptrace_opts |= PTRACE_O_TRACECLONE; 397 398 // Have the tracer notify us before execve returns 399 // (needed to disable legacy SIGTRAP generation) 400 ptrace_opts |= PTRACE_O_TRACEEXEC; 401 402 return PtraceWrapper(PTRACE_SETOPTIONS, pid, nullptr, (void *)ptrace_opts); 403 } 404 405 // Handles all waitpid events from the inferior process. 406 void NativeProcessLinux::MonitorCallback(lldb::pid_t pid, bool exited, 407 WaitStatus status) { 408 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); 409 410 // Certain activities differ based on whether the pid is the tid of the main 411 // thread. 412 const bool is_main_thread = (pid == GetID()); 413 414 // Handle when the thread exits. 415 if (exited) { 416 LLDB_LOG(log, "got exit signal({0}) , tid = {1} ({2} main thread)", signal, 417 pid, is_main_thread ? "is" : "is not"); 418 419 // This is a thread that exited. Ensure we're not tracking it anymore. 420 const bool thread_found = StopTrackingThread(pid); 421 422 if (is_main_thread) { 423 // We only set the exit status and notify the delegate if we haven't 424 // already set the process 425 // state to an exited state. We normally should have received a SIGTRAP | 426 // (PTRACE_EVENT_EXIT << 8) 427 // for the main thread. 428 const bool already_notified = (GetState() == StateType::eStateExited) || 429 (GetState() == StateType::eStateCrashed); 430 if (!already_notified) { 431 LLDB_LOG( 432 log, 433 "tid = {0} handling main thread exit ({1}), expected exit state " 434 "already set but state was {2} instead, setting exit state now", 435 pid, 436 thread_found ? "stopped tracking thread metadata" 437 : "thread metadata not found", 438 GetState()); 439 // The main thread exited. We're done monitoring. Report to delegate. 440 SetExitStatus(status, true); 441 442 // Notify delegate that our process has exited. 443 SetState(StateType::eStateExited, true); 444 } else 445 LLDB_LOG(log, "tid = {0} main thread now exited (%s)", pid, 446 thread_found ? "stopped tracking thread metadata" 447 : "thread metadata not found"); 448 } else { 449 // Do we want to report to the delegate in this case? I think not. If 450 // this was an orderly thread exit, we would already have received the 451 // SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, and we would have done an 452 // all-stop then. 453 LLDB_LOG(log, "tid = {0} handling non-main thread exit (%s)", pid, 454 thread_found ? "stopped tracking thread metadata" 455 : "thread metadata not found"); 456 } 457 return; 458 } 459 460 siginfo_t info; 461 const auto info_err = GetSignalInfo(pid, &info); 462 auto thread_sp = GetThreadByID(pid); 463 464 if (!thread_sp) { 465 // Normally, the only situation when we cannot find the thread is if we have 466 // just received a new thread notification. This is indicated by 467 // GetSignalInfo() returning si_code == SI_USER and si_pid == 0 468 LLDB_LOG(log, "received notification about an unknown tid {0}.", pid); 469 470 if (info_err.Fail()) { 471 LLDB_LOG(log, 472 "(tid {0}) GetSignalInfo failed ({1}). " 473 "Ingoring this notification.", 474 pid, info_err); 475 return; 476 } 477 478 LLDB_LOG(log, "tid {0}, si_code: {1}, si_pid: {2}", pid, info.si_code, 479 info.si_pid); 480 481 auto thread_sp = AddThread(pid); 482 483 // Resume the newly created thread. 484 ResumeThread(*thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 485 ThreadWasCreated(*thread_sp); 486 return; 487 } 488 489 // Get details on the signal raised. 490 if (info_err.Success()) { 491 // We have retrieved the signal info. Dispatch appropriately. 492 if (info.si_signo == SIGTRAP) 493 MonitorSIGTRAP(info, *thread_sp); 494 else 495 MonitorSignal(info, *thread_sp, exited); 496 } else { 497 if (info_err.GetError() == EINVAL) { 498 // This is a group stop reception for this tid. 499 // We can reach here if we reinject SIGSTOP, SIGSTP, SIGTTIN or SIGTTOU 500 // into the tracee, triggering the group-stop mechanism. Normally 501 // receiving these would stop the process, pending a SIGCONT. Simulating 502 // this state in a debugger is hard and is generally not needed (one use 503 // case is debugging background task being managed by a shell). For 504 // general use, it is sufficient to stop the process in a signal-delivery 505 // stop which happens before the group stop. This done by MonitorSignal 506 // and works correctly for all signals. 507 LLDB_LOG(log, 508 "received a group stop for pid {0} tid {1}. Transparent " 509 "handling of group stops not supported, resuming the " 510 "thread.", 511 GetID(), pid); 512 ResumeThread(*thread_sp, thread_sp->GetState(), 513 LLDB_INVALID_SIGNAL_NUMBER); 514 } else { 515 // ptrace(GETSIGINFO) failed (but not due to group-stop). 516 517 // A return value of ESRCH means the thread/process is no longer on the 518 // system, so it was killed somehow outside of our control. Either way, 519 // we can't do anything with it anymore. 520 521 // Stop tracking the metadata for the thread since it's entirely off the 522 // system now. 523 const bool thread_found = StopTrackingThread(pid); 524 525 LLDB_LOG(log, 526 "GetSignalInfo failed: {0}, tid = {1}, signal = {2}, " 527 "status = {3}, main_thread = {4}, thread_found: {5}", 528 info_err, pid, signal, status, is_main_thread, thread_found); 529 530 if (is_main_thread) { 531 // Notify the delegate - our process is not available but appears to 532 // have been killed outside 533 // our control. Is eStateExited the right exit state in this case? 534 SetExitStatus(status, true); 535 SetState(StateType::eStateExited, true); 536 } else { 537 // This thread was pulled out from underneath us. Anything to do here? 538 // Do we want to do an all stop? 539 LLDB_LOG(log, 540 "pid {0} tid {1} non-main thread exit occurred, didn't " 541 "tell delegate anything since thread disappeared out " 542 "from underneath us", 543 GetID(), pid); 544 } 545 } 546 } 547 } 548 549 void NativeProcessLinux::WaitForNewThread(::pid_t tid) { 550 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 551 552 NativeThreadLinuxSP new_thread_sp = GetThreadByID(tid); 553 554 if (new_thread_sp) { 555 // We are already tracking the thread - we got the event on the new thread 556 // (see 557 // MonitorSignal) before this one. We are done. 558 return; 559 } 560 561 // The thread is not tracked yet, let's wait for it to appear. 562 int status = -1; 563 LLDB_LOG(log, 564 "received thread creation event for tid {0}. tid not tracked " 565 "yet, waiting for thread to appear...", 566 tid); 567 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, tid, &status, __WALL); 568 // Since we are waiting on a specific tid, this must be the creation event. 569 // But let's do some checks just in case. 570 if (wait_pid != tid) { 571 LLDB_LOG(log, 572 "waiting for tid {0} failed. Assuming the thread has " 573 "disappeared in the meantime", 574 tid); 575 // The only way I know of this could happen is if the whole process was 576 // SIGKILLed in the mean time. In any case, we can't do anything about that 577 // now. 578 return; 579 } 580 if (WIFEXITED(status)) { 581 LLDB_LOG(log, 582 "waiting for tid {0} returned an 'exited' event. Not " 583 "tracking the thread.", 584 tid); 585 // Also a very improbable event. 586 return; 587 } 588 589 LLDB_LOG(log, "pid = {0}: tracking new thread tid {1}", GetID(), tid); 590 new_thread_sp = AddThread(tid); 591 592 ResumeThread(*new_thread_sp, eStateRunning, LLDB_INVALID_SIGNAL_NUMBER); 593 ThreadWasCreated(*new_thread_sp); 594 } 595 596 void NativeProcessLinux::MonitorSIGTRAP(const siginfo_t &info, 597 NativeThreadLinux &thread) { 598 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 599 const bool is_main_thread = (thread.GetID() == GetID()); 600 601 assert(info.si_signo == SIGTRAP && "Unexpected child signal!"); 602 603 switch (info.si_code) { 604 // TODO: these two cases are required if we want to support tracing of the 605 // inferiors' children. We'd need this to debug a monitor. 606 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)): 607 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 608 609 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): { 610 // This is the notification on the parent thread which informs us of new 611 // thread 612 // creation. 613 // We don't want to do anything with the parent thread so we just resume it. 614 // In case we 615 // want to implement "break on thread creation" functionality, we would need 616 // to stop 617 // here. 618 619 unsigned long event_message = 0; 620 if (GetEventMessage(thread.GetID(), &event_message).Fail()) { 621 LLDB_LOG(log, 622 "pid {0} received thread creation event but " 623 "GetEventMessage failed so we don't know the new tid", 624 thread.GetID()); 625 } else 626 WaitForNewThread(event_message); 627 628 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 629 break; 630 } 631 632 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): { 633 NativeThreadLinuxSP main_thread_sp; 634 LLDB_LOG(log, "received exec event, code = {0}", info.si_code ^ SIGTRAP); 635 636 // Exec clears any pending notifications. 637 m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 638 639 // Remove all but the main thread here. Linux fork creates a new process 640 // which only copies the main thread. 641 LLDB_LOG(log, "exec received, stop tracking all but main thread"); 642 643 for (auto thread_sp : m_threads) { 644 const bool is_main_thread = thread_sp && thread_sp->GetID() == GetID(); 645 if (is_main_thread) { 646 main_thread_sp = std::static_pointer_cast<NativeThreadLinux>(thread_sp); 647 LLDB_LOG(log, "found main thread with tid {0}, keeping", 648 main_thread_sp->GetID()); 649 } else { 650 LLDB_LOG(log, "discarding non-main-thread tid {0} due to exec", 651 thread_sp->GetID()); 652 } 653 } 654 655 m_threads.clear(); 656 657 if (main_thread_sp) { 658 m_threads.push_back(main_thread_sp); 659 SetCurrentThreadID(main_thread_sp->GetID()); 660 main_thread_sp->SetStoppedByExec(); 661 } else { 662 SetCurrentThreadID(LLDB_INVALID_THREAD_ID); 663 LLDB_LOG(log, 664 "pid {0} no main thread found, discarded all threads, " 665 "we're in a no-thread state!", 666 GetID()); 667 } 668 669 // Tell coordinator about about the "new" (since exec) stopped main thread. 670 ThreadWasCreated(*main_thread_sp); 671 672 // Let our delegate know we have just exec'd. 673 NotifyDidExec(); 674 675 // If we have a main thread, indicate we are stopped. 676 assert(main_thread_sp && "exec called during ptraced process but no main " 677 "thread metadata tracked"); 678 679 // Let the process know we're stopped. 680 StopRunningThreads(main_thread_sp->GetID()); 681 682 break; 683 } 684 685 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): { 686 // The inferior process or one of its threads is about to exit. 687 // We don't want to do anything with the thread so we just resume it. In 688 // case we 689 // want to implement "break on thread exit" functionality, we would need to 690 // stop 691 // here. 692 693 unsigned long data = 0; 694 if (GetEventMessage(thread.GetID(), &data).Fail()) 695 data = -1; 696 697 LLDB_LOG(log, 698 "received PTRACE_EVENT_EXIT, data = {0:x}, WIFEXITED={1}, " 699 "WIFSIGNALED={2}, pid = {3}, main_thread = {4}", 700 data, WIFEXITED(data), WIFSIGNALED(data), thread.GetID(), 701 is_main_thread); 702 703 if (is_main_thread) 704 SetExitStatus(WaitStatus::Decode(data), true); 705 706 StateType state = thread.GetState(); 707 if (!StateIsRunningState(state)) { 708 // Due to a kernel bug, we may sometimes get this stop after the inferior 709 // gets a 710 // SIGKILL. This confuses our state tracking logic in ResumeThread(), 711 // since normally, 712 // we should not be receiving any ptrace events while the inferior is 713 // stopped. This 714 // makes sure that the inferior is resumed and exits normally. 715 state = eStateRunning; 716 } 717 ResumeThread(thread, state, LLDB_INVALID_SIGNAL_NUMBER); 718 719 break; 720 } 721 722 case 0: 723 case TRAP_TRACE: // We receive this on single stepping. 724 case TRAP_HWBKPT: // We receive this on watchpoint hit 725 { 726 // If a watchpoint was hit, report it 727 uint32_t wp_index; 728 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex( 729 wp_index, (uintptr_t)info.si_addr); 730 if (error.Fail()) 731 LLDB_LOG(log, 732 "received error while checking for watchpoint hits, pid = " 733 "{0}, error = {1}", 734 thread.GetID(), error); 735 if (wp_index != LLDB_INVALID_INDEX32) { 736 MonitorWatchpoint(thread, wp_index); 737 break; 738 } 739 740 // If a breakpoint was hit, report it 741 uint32_t bp_index; 742 error = thread.GetRegisterContext()->GetHardwareBreakHitIndex( 743 bp_index, (uintptr_t)info.si_addr); 744 if (error.Fail()) 745 LLDB_LOG(log, "received error while checking for hardware " 746 "breakpoint hits, pid = {0}, error = {1}", 747 thread.GetID(), error); 748 if (bp_index != LLDB_INVALID_INDEX32) { 749 MonitorBreakpoint(thread); 750 break; 751 } 752 753 // Otherwise, report step over 754 MonitorTrace(thread); 755 break; 756 } 757 758 case SI_KERNEL: 759 #if defined __mips__ 760 // For mips there is no special signal for watchpoint 761 // So we check for watchpoint in kernel trap 762 { 763 // If a watchpoint was hit, report it 764 uint32_t wp_index; 765 Status error = thread.GetRegisterContext()->GetWatchpointHitIndex( 766 wp_index, LLDB_INVALID_ADDRESS); 767 if (error.Fail()) 768 LLDB_LOG(log, 769 "received error while checking for watchpoint hits, pid = " 770 "{0}, error = {1}", 771 thread.GetID(), error); 772 if (wp_index != LLDB_INVALID_INDEX32) { 773 MonitorWatchpoint(thread, wp_index); 774 break; 775 } 776 } 777 // NO BREAK 778 #endif 779 case TRAP_BRKPT: 780 MonitorBreakpoint(thread); 781 break; 782 783 case SIGTRAP: 784 case (SIGTRAP | 0x80): 785 LLDB_LOG( 786 log, 787 "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}, resuming", 788 info.si_code, GetID(), thread.GetID()); 789 790 // Ignore these signals until we know more about them. 791 ResumeThread(thread, thread.GetState(), LLDB_INVALID_SIGNAL_NUMBER); 792 break; 793 794 default: 795 LLDB_LOG(log, "received unknown SIGTRAP stop event ({0}, pid {1} tid {2}", 796 info.si_code, GetID(), thread.GetID()); 797 MonitorSignal(info, thread, false); 798 break; 799 } 800 } 801 802 void NativeProcessLinux::MonitorTrace(NativeThreadLinux &thread) { 803 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 804 LLDB_LOG(log, "received trace event, pid = {0}", thread.GetID()); 805 806 // This thread is currently stopped. 807 thread.SetStoppedByTrace(); 808 809 StopRunningThreads(thread.GetID()); 810 } 811 812 void NativeProcessLinux::MonitorBreakpoint(NativeThreadLinux &thread) { 813 Log *log( 814 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 815 LLDB_LOG(log, "received breakpoint event, pid = {0}", thread.GetID()); 816 817 // Mark the thread as stopped at breakpoint. 818 thread.SetStoppedByBreakpoint(); 819 Status error = FixupBreakpointPCAsNeeded(thread); 820 if (error.Fail()) 821 LLDB_LOG(log, "pid = {0} fixup: {1}", thread.GetID(), error); 822 823 if (m_threads_stepping_with_breakpoint.find(thread.GetID()) != 824 m_threads_stepping_with_breakpoint.end()) 825 thread.SetStoppedByTrace(); 826 827 StopRunningThreads(thread.GetID()); 828 } 829 830 void NativeProcessLinux::MonitorWatchpoint(NativeThreadLinux &thread, 831 uint32_t wp_index) { 832 Log *log( 833 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 834 LLDB_LOG(log, "received watchpoint event, pid = {0}, wp_index = {1}", 835 thread.GetID(), wp_index); 836 837 // Mark the thread as stopped at watchpoint. 838 // The address is at (lldb::addr_t)info->si_addr if we need it. 839 thread.SetStoppedByWatchpoint(wp_index); 840 841 // We need to tell all other running threads before we notify the delegate 842 // about this stop. 843 StopRunningThreads(thread.GetID()); 844 } 845 846 void NativeProcessLinux::MonitorSignal(const siginfo_t &info, 847 NativeThreadLinux &thread, bool exited) { 848 const int signo = info.si_signo; 849 const bool is_from_llgs = info.si_pid == getpid(); 850 851 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 852 853 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 854 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a 855 // kill(2) or raise(3). Similarly for tgkill(2) on Linux. 856 // 857 // IOW, user generated signals never generate what we consider to be a 858 // "crash". 859 // 860 // Similarly, ACK signals generated by this monitor. 861 862 // Handle the signal. 863 LLDB_LOG(log, 864 "received signal {0} ({1}) with code {2}, (siginfo pid = {3}, " 865 "waitpid pid = {4})", 866 Host::GetSignalAsCString(signo), signo, info.si_code, 867 thread.GetID()); 868 869 // Check for thread stop notification. 870 if (is_from_llgs && (info.si_code == SI_TKILL) && (signo == SIGSTOP)) { 871 // This is a tgkill()-based stop. 872 LLDB_LOG(log, "pid {0} tid {1}, thread stopped", GetID(), thread.GetID()); 873 874 // Check that we're not already marked with a stop reason. 875 // Note this thread really shouldn't already be marked as stopped - if we 876 // were, that would imply that the kernel signaled us with the thread 877 // stopping which we handled and marked as stopped, and that, without an 878 // intervening resume, we received another stop. It is more likely that we 879 // are missing the marking of a run state somewhere if we find that the 880 // thread was marked as stopped. 881 const StateType thread_state = thread.GetState(); 882 if (!StateIsStoppedState(thread_state, false)) { 883 // An inferior thread has stopped because of a SIGSTOP we have sent it. 884 // Generally, these are not important stops and we don't want to report 885 // them as they are just used to stop other threads when one thread (the 886 // one with the *real* stop reason) hits a breakpoint (watchpoint, 887 // etc...). However, in the case of an asynchronous Interrupt(), this *is* 888 // the real stop reason, so we leave the signal intact if this is the 889 // thread that was chosen as the triggering thread. 890 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 891 if (m_pending_notification_tid == thread.GetID()) 892 thread.SetStoppedBySignal(SIGSTOP, &info); 893 else 894 thread.SetStoppedWithNoReason(); 895 896 SetCurrentThreadID(thread.GetID()); 897 SignalIfAllThreadsStopped(); 898 } else { 899 // We can end up here if stop was initiated by LLGS but by this time a 900 // thread stop has occurred - maybe initiated by another event. 901 Status error = ResumeThread(thread, thread.GetState(), 0); 902 if (error.Fail()) 903 LLDB_LOG(log, "failed to resume thread {0}: {1}", thread.GetID(), 904 error); 905 } 906 } else { 907 LLDB_LOG(log, 908 "pid {0} tid {1}, thread was already marked as a stopped " 909 "state (state={2}), leaving stop signal as is", 910 GetID(), thread.GetID(), thread_state); 911 SignalIfAllThreadsStopped(); 912 } 913 914 // Done handling. 915 return; 916 } 917 918 // Check if debugger should stop at this signal or just ignore it 919 // and resume the inferior. 920 if (m_signals_to_ignore.find(signo) != m_signals_to_ignore.end()) { 921 ResumeThread(thread, thread.GetState(), signo); 922 return; 923 } 924 925 // This thread is stopped. 926 LLDB_LOG(log, "received signal {0}", Host::GetSignalAsCString(signo)); 927 thread.SetStoppedBySignal(signo, &info); 928 929 // Send a stop to the debugger after we get all other threads to stop. 930 StopRunningThreads(thread.GetID()); 931 } 932 933 namespace { 934 935 struct EmulatorBaton { 936 NativeProcessLinux *m_process; 937 NativeRegisterContext *m_reg_context; 938 939 // eRegisterKindDWARF -> RegsiterValue 940 std::unordered_map<uint32_t, RegisterValue> m_register_values; 941 942 EmulatorBaton(NativeProcessLinux *process, NativeRegisterContext *reg_context) 943 : m_process(process), m_reg_context(reg_context) {} 944 }; 945 946 } // anonymous namespace 947 948 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton, 949 const EmulateInstruction::Context &context, 950 lldb::addr_t addr, void *dst, size_t length) { 951 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 952 953 size_t bytes_read; 954 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read); 955 return bytes_read; 956 } 957 958 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton, 959 const RegisterInfo *reg_info, 960 RegisterValue ®_value) { 961 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 962 963 auto it = emulator_baton->m_register_values.find( 964 reg_info->kinds[eRegisterKindDWARF]); 965 if (it != emulator_baton->m_register_values.end()) { 966 reg_value = it->second; 967 return true; 968 } 969 970 // The emulator only fill in the dwarf regsiter numbers (and in some case 971 // the generic register numbers). Get the full register info from the 972 // register context based on the dwarf register numbers. 973 const RegisterInfo *full_reg_info = 974 emulator_baton->m_reg_context->GetRegisterInfo( 975 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 976 977 Status error = 978 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value); 979 if (error.Success()) 980 return true; 981 982 return false; 983 } 984 985 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton, 986 const EmulateInstruction::Context &context, 987 const RegisterInfo *reg_info, 988 const RegisterValue ®_value) { 989 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton); 990 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = 991 reg_value; 992 return true; 993 } 994 995 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton, 996 const EmulateInstruction::Context &context, 997 lldb::addr_t addr, const void *dst, 998 size_t length) { 999 return length; 1000 } 1001 1002 static lldb::addr_t ReadFlags(NativeRegisterContext *regsiter_context) { 1003 const RegisterInfo *flags_info = regsiter_context->GetRegisterInfo( 1004 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 1005 return regsiter_context->ReadRegisterAsUnsigned(flags_info, 1006 LLDB_INVALID_ADDRESS); 1007 } 1008 1009 Status 1010 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadLinux &thread) { 1011 Status error; 1012 NativeRegisterContextSP register_context_sp = thread.GetRegisterContext(); 1013 1014 std::unique_ptr<EmulateInstruction> emulator_ap( 1015 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, 1016 nullptr)); 1017 1018 if (emulator_ap == nullptr) 1019 return Status("Instruction emulator not found!"); 1020 1021 EmulatorBaton baton(this, register_context_sp.get()); 1022 emulator_ap->SetBaton(&baton); 1023 emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 1024 emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 1025 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 1026 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 1027 1028 if (!emulator_ap->ReadInstruction()) 1029 return Status("Read instruction failed!"); 1030 1031 bool emulation_result = 1032 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 1033 1034 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo( 1035 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 1036 const RegisterInfo *reg_info_flags = register_context_sp->GetRegisterInfo( 1037 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 1038 1039 auto pc_it = 1040 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 1041 auto flags_it = 1042 baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 1043 1044 lldb::addr_t next_pc; 1045 lldb::addr_t next_flags; 1046 if (emulation_result) { 1047 assert(pc_it != baton.m_register_values.end() && 1048 "Emulation was successfull but PC wasn't updated"); 1049 next_pc = pc_it->second.GetAsUInt64(); 1050 1051 if (flags_it != baton.m_register_values.end()) 1052 next_flags = flags_it->second.GetAsUInt64(); 1053 else 1054 next_flags = ReadFlags(register_context_sp.get()); 1055 } else if (pc_it == baton.m_register_values.end()) { 1056 // Emulate instruction failed and it haven't changed PC. Advance PC 1057 // with the size of the current opcode because the emulation of all 1058 // PC modifying instruction should be successful. The failure most 1059 // likely caused by a not supported instruction which don't modify PC. 1060 next_pc = 1061 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize(); 1062 next_flags = ReadFlags(register_context_sp.get()); 1063 } else { 1064 // The instruction emulation failed after it modified the PC. It is an 1065 // unknown error where we can't continue because the next instruction is 1066 // modifying the PC but we don't know how. 1067 return Status("Instruction emulation failed unexpectedly."); 1068 } 1069 1070 if (m_arch.GetMachine() == llvm::Triple::arm) { 1071 if (next_flags & 0x20) { 1072 // Thumb mode 1073 error = SetSoftwareBreakpoint(next_pc, 2); 1074 } else { 1075 // Arm mode 1076 error = SetSoftwareBreakpoint(next_pc, 4); 1077 } 1078 } else if (m_arch.GetMachine() == llvm::Triple::mips64 || 1079 m_arch.GetMachine() == llvm::Triple::mips64el || 1080 m_arch.GetMachine() == llvm::Triple::mips || 1081 m_arch.GetMachine() == llvm::Triple::mipsel || 1082 m_arch.GetMachine() == llvm::Triple::ppc64le) 1083 error = SetSoftwareBreakpoint(next_pc, 4); 1084 else { 1085 // No size hint is given for the next breakpoint 1086 error = SetSoftwareBreakpoint(next_pc, 0); 1087 } 1088 1089 // If setting the breakpoint fails because next_pc is out of 1090 // the address space, ignore it and let the debugee segfault. 1091 if (error.GetError() == EIO || error.GetError() == EFAULT) { 1092 return Status(); 1093 } else if (error.Fail()) 1094 return error; 1095 1096 m_threads_stepping_with_breakpoint.insert({thread.GetID(), next_pc}); 1097 1098 return Status(); 1099 } 1100 1101 bool NativeProcessLinux::SupportHardwareSingleStepping() const { 1102 if (m_arch.GetMachine() == llvm::Triple::arm || 1103 m_arch.GetMachine() == llvm::Triple::mips64 || 1104 m_arch.GetMachine() == llvm::Triple::mips64el || 1105 m_arch.GetMachine() == llvm::Triple::mips || 1106 m_arch.GetMachine() == llvm::Triple::mipsel) 1107 return false; 1108 return true; 1109 } 1110 1111 Status NativeProcessLinux::Resume(const ResumeActionList &resume_actions) { 1112 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1113 LLDB_LOG(log, "pid {0}", GetID()); 1114 1115 bool software_single_step = !SupportHardwareSingleStepping(); 1116 1117 if (software_single_step) { 1118 for (auto thread_sp : m_threads) { 1119 assert(thread_sp && "thread list should not contain NULL threads"); 1120 1121 const ResumeAction *const action = 1122 resume_actions.GetActionForThread(thread_sp->GetID(), true); 1123 if (action == nullptr) 1124 continue; 1125 1126 if (action->state == eStateStepping) { 1127 Status error = SetupSoftwareSingleStepping( 1128 static_cast<NativeThreadLinux &>(*thread_sp)); 1129 if (error.Fail()) 1130 return error; 1131 } 1132 } 1133 } 1134 1135 for (auto thread_sp : m_threads) { 1136 assert(thread_sp && "thread list should not contain NULL threads"); 1137 1138 const ResumeAction *const action = 1139 resume_actions.GetActionForThread(thread_sp->GetID(), true); 1140 1141 if (action == nullptr) { 1142 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 1143 thread_sp->GetID()); 1144 continue; 1145 } 1146 1147 LLDB_LOG(log, "processing resume action state {0} for pid {1} tid {2}", 1148 action->state, GetID(), thread_sp->GetID()); 1149 1150 switch (action->state) { 1151 case eStateRunning: 1152 case eStateStepping: { 1153 // Run the thread, possibly feeding it the signal. 1154 const int signo = action->signal; 1155 ResumeThread(static_cast<NativeThreadLinux &>(*thread_sp), action->state, 1156 signo); 1157 break; 1158 } 1159 1160 case eStateSuspended: 1161 case eStateStopped: 1162 llvm_unreachable("Unexpected state"); 1163 1164 default: 1165 return Status("NativeProcessLinux::%s (): unexpected state %s specified " 1166 "for pid %" PRIu64 ", tid %" PRIu64, 1167 __FUNCTION__, StateAsCString(action->state), GetID(), 1168 thread_sp->GetID()); 1169 } 1170 } 1171 1172 return Status(); 1173 } 1174 1175 Status NativeProcessLinux::Halt() { 1176 Status error; 1177 1178 if (kill(GetID(), SIGSTOP) != 0) 1179 error.SetErrorToErrno(); 1180 1181 return error; 1182 } 1183 1184 Status NativeProcessLinux::Detach() { 1185 Status error; 1186 1187 // Stop monitoring the inferior. 1188 m_sigchld_handle.reset(); 1189 1190 // Tell ptrace to detach from the process. 1191 if (GetID() == LLDB_INVALID_PROCESS_ID) 1192 return error; 1193 1194 for (auto thread_sp : m_threads) { 1195 Status e = Detach(thread_sp->GetID()); 1196 if (e.Fail()) 1197 error = 1198 e; // Save the error, but still attempt to detach from other threads. 1199 } 1200 1201 m_processor_trace_monitor.clear(); 1202 m_pt_proces_trace_id = LLDB_INVALID_UID; 1203 1204 return error; 1205 } 1206 1207 Status NativeProcessLinux::Signal(int signo) { 1208 Status error; 1209 1210 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1211 LLDB_LOG(log, "sending signal {0} ({1}) to pid {1}", signo, 1212 Host::GetSignalAsCString(signo), GetID()); 1213 1214 if (kill(GetID(), signo)) 1215 error.SetErrorToErrno(); 1216 1217 return error; 1218 } 1219 1220 Status NativeProcessLinux::Interrupt() { 1221 // Pick a running thread (or if none, a not-dead stopped thread) as 1222 // the chosen thread that will be the stop-reason thread. 1223 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1224 1225 NativeThreadProtocolSP running_thread_sp; 1226 NativeThreadProtocolSP stopped_thread_sp; 1227 1228 LLDB_LOG(log, "selecting running thread for interrupt target"); 1229 for (auto thread_sp : m_threads) { 1230 // The thread shouldn't be null but lets just cover that here. 1231 if (!thread_sp) 1232 continue; 1233 1234 // If we have a running or stepping thread, we'll call that the 1235 // target of the interrupt. 1236 const auto thread_state = thread_sp->GetState(); 1237 if (thread_state == eStateRunning || thread_state == eStateStepping) { 1238 running_thread_sp = thread_sp; 1239 break; 1240 } else if (!stopped_thread_sp && StateIsStoppedState(thread_state, true)) { 1241 // Remember the first non-dead stopped thread. We'll use that as a backup 1242 // if there are no running threads. 1243 stopped_thread_sp = thread_sp; 1244 } 1245 } 1246 1247 if (!running_thread_sp && !stopped_thread_sp) { 1248 Status error("found no running/stepping or live stopped threads as target " 1249 "for interrupt"); 1250 LLDB_LOG(log, "skipping due to error: {0}", error); 1251 1252 return error; 1253 } 1254 1255 NativeThreadProtocolSP deferred_signal_thread_sp = 1256 running_thread_sp ? running_thread_sp : stopped_thread_sp; 1257 1258 LLDB_LOG(log, "pid {0} {1} tid {2} chosen for interrupt target", GetID(), 1259 running_thread_sp ? "running" : "stopped", 1260 deferred_signal_thread_sp->GetID()); 1261 1262 StopRunningThreads(deferred_signal_thread_sp->GetID()); 1263 1264 return Status(); 1265 } 1266 1267 Status NativeProcessLinux::Kill() { 1268 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1269 LLDB_LOG(log, "pid {0}", GetID()); 1270 1271 Status error; 1272 1273 switch (m_state) { 1274 case StateType::eStateInvalid: 1275 case StateType::eStateExited: 1276 case StateType::eStateCrashed: 1277 case StateType::eStateDetached: 1278 case StateType::eStateUnloaded: 1279 // Nothing to do - the process is already dead. 1280 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 1281 m_state); 1282 return error; 1283 1284 case StateType::eStateConnected: 1285 case StateType::eStateAttaching: 1286 case StateType::eStateLaunching: 1287 case StateType::eStateStopped: 1288 case StateType::eStateRunning: 1289 case StateType::eStateStepping: 1290 case StateType::eStateSuspended: 1291 // We can try to kill a process in these states. 1292 break; 1293 } 1294 1295 if (kill(GetID(), SIGKILL) != 0) { 1296 error.SetErrorToErrno(); 1297 return error; 1298 } 1299 1300 return error; 1301 } 1302 1303 static Status 1304 ParseMemoryRegionInfoFromProcMapsLine(llvm::StringRef &maps_line, 1305 MemoryRegionInfo &memory_region_info) { 1306 memory_region_info.Clear(); 1307 1308 StringExtractor line_extractor(maps_line); 1309 1310 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode 1311 // pathname 1312 // perms: rwxp (letter is present if set, '-' if not, final character is 1313 // p=private, s=shared). 1314 1315 // Parse out the starting address 1316 lldb::addr_t start_address = line_extractor.GetHexMaxU64(false, 0); 1317 1318 // Parse out hyphen separating start and end address from range. 1319 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != '-')) 1320 return Status( 1321 "malformed /proc/{pid}/maps entry, missing dash between address range"); 1322 1323 // Parse out the ending address 1324 lldb::addr_t end_address = line_extractor.GetHexMaxU64(false, start_address); 1325 1326 // Parse out the space after the address. 1327 if (!line_extractor.GetBytesLeft() || (line_extractor.GetChar() != ' ')) 1328 return Status( 1329 "malformed /proc/{pid}/maps entry, missing space after range"); 1330 1331 // Save the range. 1332 memory_region_info.GetRange().SetRangeBase(start_address); 1333 memory_region_info.GetRange().SetRangeEnd(end_address); 1334 1335 // Any memory region in /proc/{pid}/maps is by definition mapped into the 1336 // process. 1337 memory_region_info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 1338 1339 // Parse out each permission entry. 1340 if (line_extractor.GetBytesLeft() < 4) 1341 return Status("malformed /proc/{pid}/maps entry, missing some portion of " 1342 "permissions"); 1343 1344 // Handle read permission. 1345 const char read_perm_char = line_extractor.GetChar(); 1346 if (read_perm_char == 'r') 1347 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 1348 else if (read_perm_char == '-') 1349 memory_region_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1350 else 1351 return Status("unexpected /proc/{pid}/maps read permission char"); 1352 1353 // Handle write permission. 1354 const char write_perm_char = line_extractor.GetChar(); 1355 if (write_perm_char == 'w') 1356 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 1357 else if (write_perm_char == '-') 1358 memory_region_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1359 else 1360 return Status("unexpected /proc/{pid}/maps write permission char"); 1361 1362 // Handle execute permission. 1363 const char exec_perm_char = line_extractor.GetChar(); 1364 if (exec_perm_char == 'x') 1365 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 1366 else if (exec_perm_char == '-') 1367 memory_region_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1368 else 1369 return Status("unexpected /proc/{pid}/maps exec permission char"); 1370 1371 line_extractor.GetChar(); // Read the private bit 1372 line_extractor.SkipSpaces(); // Skip the separator 1373 line_extractor.GetHexMaxU64(false, 0); // Read the offset 1374 line_extractor.GetHexMaxU64(false, 0); // Read the major device number 1375 line_extractor.GetChar(); // Read the device id separator 1376 line_extractor.GetHexMaxU64(false, 0); // Read the major device number 1377 line_extractor.SkipSpaces(); // Skip the separator 1378 line_extractor.GetU64(0, 10); // Read the inode number 1379 1380 line_extractor.SkipSpaces(); 1381 const char *name = line_extractor.Peek(); 1382 if (name) 1383 memory_region_info.SetName(name); 1384 1385 return Status(); 1386 } 1387 1388 Status NativeProcessLinux::GetMemoryRegionInfo(lldb::addr_t load_addr, 1389 MemoryRegionInfo &range_info) { 1390 // FIXME review that the final memory region returned extends to the end of 1391 // the virtual address space, 1392 // with no perms if it is not mapped. 1393 1394 // Use an approach that reads memory regions from /proc/{pid}/maps. 1395 // Assume proc maps entries are in ascending order. 1396 // FIXME assert if we find differently. 1397 1398 if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 1399 // We're done. 1400 return Status("unsupported"); 1401 } 1402 1403 Status error = PopulateMemoryRegionCache(); 1404 if (error.Fail()) { 1405 return error; 1406 } 1407 1408 lldb::addr_t prev_base_address = 0; 1409 1410 // FIXME start by finding the last region that is <= target address using 1411 // binary search. Data is sorted. 1412 // There can be a ton of regions on pthreads apps with lots of threads. 1413 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 1414 ++it) { 1415 MemoryRegionInfo &proc_entry_info = it->first; 1416 1417 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 1418 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 1419 "descending /proc/pid/maps entries detected, unexpected"); 1420 prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 1421 UNUSED_IF_ASSERT_DISABLED(prev_base_address); 1422 1423 // If the target address comes before this entry, indicate distance to next 1424 // region. 1425 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 1426 range_info.GetRange().SetRangeBase(load_addr); 1427 range_info.GetRange().SetByteSize( 1428 proc_entry_info.GetRange().GetRangeBase() - load_addr); 1429 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1430 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1431 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1432 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1433 1434 return error; 1435 } else if (proc_entry_info.GetRange().Contains(load_addr)) { 1436 // The target address is within the memory region we're processing here. 1437 range_info = proc_entry_info; 1438 return error; 1439 } 1440 1441 // The target memory address comes somewhere after the region we just 1442 // parsed. 1443 } 1444 1445 // If we made it here, we didn't find an entry that contained the given 1446 // address. Return the 1447 // load_addr as start and the amount of bytes betwwen load address and the end 1448 // of the memory as 1449 // size. 1450 range_info.GetRange().SetRangeBase(load_addr); 1451 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 1452 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 1453 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 1454 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 1455 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 1456 return error; 1457 } 1458 1459 Status NativeProcessLinux::PopulateMemoryRegionCache() { 1460 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1461 1462 // If our cache is empty, pull the latest. There should always be at least 1463 // one memory region if memory region handling is supported. 1464 if (!m_mem_region_cache.empty()) { 1465 LLDB_LOG(log, "reusing {0} cached memory region entries", 1466 m_mem_region_cache.size()); 1467 return Status(); 1468 } 1469 1470 auto BufferOrError = getProcFile(GetID(), "maps"); 1471 if (!BufferOrError) { 1472 m_supports_mem_region = LazyBool::eLazyBoolNo; 1473 return BufferOrError.getError(); 1474 } 1475 StringRef Rest = BufferOrError.get()->getBuffer(); 1476 while (! Rest.empty()) { 1477 StringRef Line; 1478 std::tie(Line, Rest) = Rest.split('\n'); 1479 MemoryRegionInfo info; 1480 const Status parse_error = 1481 ParseMemoryRegionInfoFromProcMapsLine(Line, info); 1482 if (parse_error.Fail()) { 1483 LLDB_LOG(log, "failed to parse proc maps line '{0}': {1}", Line, 1484 parse_error); 1485 m_supports_mem_region = LazyBool::eLazyBoolNo; 1486 return parse_error; 1487 } 1488 m_mem_region_cache.emplace_back( 1489 info, FileSpec(info.GetName().GetCString(), true)); 1490 } 1491 1492 if (m_mem_region_cache.empty()) { 1493 // No entries after attempting to read them. This shouldn't happen if 1494 // /proc/{pid}/maps is supported. Assume we don't support map entries 1495 // via procfs. 1496 m_supports_mem_region = LazyBool::eLazyBoolNo; 1497 LLDB_LOG(log, 1498 "failed to find any procfs maps entries, assuming no support " 1499 "for memory region metadata retrieval"); 1500 return Status("not supported"); 1501 } 1502 1503 LLDB_LOG(log, "read {0} memory region entries from /proc/{1}/maps", 1504 m_mem_region_cache.size(), GetID()); 1505 1506 // We support memory retrieval, remember that. 1507 m_supports_mem_region = LazyBool::eLazyBoolYes; 1508 return Status(); 1509 } 1510 1511 void NativeProcessLinux::DoStopIDBumped(uint32_t newBumpId) { 1512 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1513 LLDB_LOG(log, "newBumpId={0}", newBumpId); 1514 LLDB_LOG(log, "clearing {0} entries from memory region cache", 1515 m_mem_region_cache.size()); 1516 m_mem_region_cache.clear(); 1517 } 1518 1519 Status NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, 1520 lldb::addr_t &addr) { 1521 // FIXME implementing this requires the equivalent of 1522 // InferiorCallPOSIX::InferiorCallMmap, which depends on 1523 // functional ThreadPlans working with Native*Protocol. 1524 #if 1 1525 return Status("not implemented yet"); 1526 #else 1527 addr = LLDB_INVALID_ADDRESS; 1528 1529 unsigned prot = 0; 1530 if (permissions & lldb::ePermissionsReadable) 1531 prot |= eMmapProtRead; 1532 if (permissions & lldb::ePermissionsWritable) 1533 prot |= eMmapProtWrite; 1534 if (permissions & lldb::ePermissionsExecutable) 1535 prot |= eMmapProtExec; 1536 1537 // TODO implement this directly in NativeProcessLinux 1538 // (and lift to NativeProcessPOSIX if/when that class is 1539 // refactored out). 1540 if (InferiorCallMmap(this, addr, 0, size, prot, 1541 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 1542 m_addr_to_mmap_size[addr] = size; 1543 return Status(); 1544 } else { 1545 addr = LLDB_INVALID_ADDRESS; 1546 return Status("unable to allocate %" PRIu64 1547 " bytes of memory with permissions %s", 1548 size, GetPermissionsAsCString(permissions)); 1549 } 1550 #endif 1551 } 1552 1553 Status NativeProcessLinux::DeallocateMemory(lldb::addr_t addr) { 1554 // FIXME see comments in AllocateMemory - required lower-level 1555 // bits not in place yet (ThreadPlans) 1556 return Status("not implemented"); 1557 } 1558 1559 lldb::addr_t NativeProcessLinux::GetSharedLibraryInfoAddress() { 1560 // punt on this for now 1561 return LLDB_INVALID_ADDRESS; 1562 } 1563 1564 size_t NativeProcessLinux::UpdateThreads() { 1565 // The NativeProcessLinux monitoring threads are always up to date 1566 // with respect to thread state and they keep the thread list 1567 // populated properly. All this method needs to do is return the 1568 // thread count. 1569 return m_threads.size(); 1570 } 1571 1572 bool NativeProcessLinux::GetArchitecture(ArchSpec &arch) const { 1573 arch = m_arch; 1574 return true; 1575 } 1576 1577 Status NativeProcessLinux::GetSoftwareBreakpointPCOffset( 1578 uint32_t &actual_opcode_size) { 1579 // FIXME put this behind a breakpoint protocol class that can be 1580 // set per architecture. Need ARM, MIPS support here. 1581 static const uint8_t g_i386_opcode[] = {0xCC}; 1582 static const uint8_t g_s390x_opcode[] = {0x00, 0x01}; 1583 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 1584 1585 switch (m_arch.GetMachine()) { 1586 case llvm::Triple::x86: 1587 case llvm::Triple::x86_64: 1588 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode)); 1589 return Status(); 1590 1591 case llvm::Triple::systemz: 1592 actual_opcode_size = static_cast<uint32_t>(sizeof(g_s390x_opcode)); 1593 return Status(); 1594 1595 case llvm::Triple::ppc64le: 1596 actual_opcode_size = static_cast<uint32_t>(sizeof(g_ppc64le_opcode)); 1597 return Status(); 1598 1599 case llvm::Triple::arm: 1600 case llvm::Triple::aarch64: 1601 case llvm::Triple::mips64: 1602 case llvm::Triple::mips64el: 1603 case llvm::Triple::mips: 1604 case llvm::Triple::mipsel: 1605 // On these architectures the PC don't get updated for breakpoint hits 1606 actual_opcode_size = 0; 1607 return Status(); 1608 1609 default: 1610 assert(false && "CPU type not supported!"); 1611 return Status("CPU type not supported"); 1612 } 1613 } 1614 1615 Status NativeProcessLinux::SetBreakpoint(lldb::addr_t addr, uint32_t size, 1616 bool hardware) { 1617 if (hardware) 1618 return SetHardwareBreakpoint(addr, size); 1619 else 1620 return SetSoftwareBreakpoint(addr, size); 1621 } 1622 1623 Status NativeProcessLinux::RemoveBreakpoint(lldb::addr_t addr, bool hardware) { 1624 if (hardware) 1625 return RemoveHardwareBreakpoint(addr); 1626 else 1627 return NativeProcessProtocol::RemoveBreakpoint(addr); 1628 } 1629 1630 Status NativeProcessLinux::GetSoftwareBreakpointTrapOpcode( 1631 size_t trap_opcode_size_hint, size_t &actual_opcode_size, 1632 const uint8_t *&trap_opcode_bytes) { 1633 // FIXME put this behind a breakpoint protocol class that can be set per 1634 // architecture. Need MIPS support here. 1635 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; 1636 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1637 // linux kernel does otherwise. 1638 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1639 static const uint8_t g_i386_opcode[] = {0xCC}; 1640 static const uint8_t g_mips64_opcode[] = {0x00, 0x00, 0x00, 0x0d}; 1641 static const uint8_t g_mips64el_opcode[] = {0x0d, 0x00, 0x00, 0x00}; 1642 static const uint8_t g_s390x_opcode[] = {0x00, 0x01}; 1643 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde}; 1644 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 1645 1646 switch (m_arch.GetMachine()) { 1647 case llvm::Triple::aarch64: 1648 trap_opcode_bytes = g_aarch64_opcode; 1649 actual_opcode_size = sizeof(g_aarch64_opcode); 1650 return Status(); 1651 1652 case llvm::Triple::arm: 1653 switch (trap_opcode_size_hint) { 1654 case 2: 1655 trap_opcode_bytes = g_thumb_breakpoint_opcode; 1656 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode); 1657 return Status(); 1658 case 4: 1659 trap_opcode_bytes = g_arm_breakpoint_opcode; 1660 actual_opcode_size = sizeof(g_arm_breakpoint_opcode); 1661 return Status(); 1662 default: 1663 assert(false && "Unrecognised trap opcode size hint!"); 1664 return Status("Unrecognised trap opcode size hint!"); 1665 } 1666 1667 case llvm::Triple::x86: 1668 case llvm::Triple::x86_64: 1669 trap_opcode_bytes = g_i386_opcode; 1670 actual_opcode_size = sizeof(g_i386_opcode); 1671 return Status(); 1672 1673 case llvm::Triple::mips: 1674 case llvm::Triple::mips64: 1675 trap_opcode_bytes = g_mips64_opcode; 1676 actual_opcode_size = sizeof(g_mips64_opcode); 1677 return Status(); 1678 1679 case llvm::Triple::mipsel: 1680 case llvm::Triple::mips64el: 1681 trap_opcode_bytes = g_mips64el_opcode; 1682 actual_opcode_size = sizeof(g_mips64el_opcode); 1683 return Status(); 1684 1685 case llvm::Triple::systemz: 1686 trap_opcode_bytes = g_s390x_opcode; 1687 actual_opcode_size = sizeof(g_s390x_opcode); 1688 return Status(); 1689 1690 case llvm::Triple::ppc64le: 1691 trap_opcode_bytes = g_ppc64le_opcode; 1692 actual_opcode_size = sizeof(g_ppc64le_opcode); 1693 return Status(); 1694 1695 default: 1696 assert(false && "CPU type not supported!"); 1697 return Status("CPU type not supported"); 1698 } 1699 } 1700 1701 #if 0 1702 ProcessMessage::CrashReason 1703 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info) 1704 { 1705 ProcessMessage::CrashReason reason; 1706 assert(info->si_signo == SIGSEGV); 1707 1708 reason = ProcessMessage::eInvalidCrashReason; 1709 1710 switch (info->si_code) 1711 { 1712 default: 1713 assert(false && "unexpected si_code for SIGSEGV"); 1714 break; 1715 case SI_KERNEL: 1716 // Linux will occasionally send spurious SI_KERNEL codes. 1717 // (this is poorly documented in sigaction) 1718 // One way to get this is via unaligned SIMD loads. 1719 reason = ProcessMessage::eInvalidAddress; // for lack of anything better 1720 break; 1721 case SEGV_MAPERR: 1722 reason = ProcessMessage::eInvalidAddress; 1723 break; 1724 case SEGV_ACCERR: 1725 reason = ProcessMessage::ePrivilegedAddress; 1726 break; 1727 } 1728 1729 return reason; 1730 } 1731 #endif 1732 1733 #if 0 1734 ProcessMessage::CrashReason 1735 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info) 1736 { 1737 ProcessMessage::CrashReason reason; 1738 assert(info->si_signo == SIGILL); 1739 1740 reason = ProcessMessage::eInvalidCrashReason; 1741 1742 switch (info->si_code) 1743 { 1744 default: 1745 assert(false && "unexpected si_code for SIGILL"); 1746 break; 1747 case ILL_ILLOPC: 1748 reason = ProcessMessage::eIllegalOpcode; 1749 break; 1750 case ILL_ILLOPN: 1751 reason = ProcessMessage::eIllegalOperand; 1752 break; 1753 case ILL_ILLADR: 1754 reason = ProcessMessage::eIllegalAddressingMode; 1755 break; 1756 case ILL_ILLTRP: 1757 reason = ProcessMessage::eIllegalTrap; 1758 break; 1759 case ILL_PRVOPC: 1760 reason = ProcessMessage::ePrivilegedOpcode; 1761 break; 1762 case ILL_PRVREG: 1763 reason = ProcessMessage::ePrivilegedRegister; 1764 break; 1765 case ILL_COPROC: 1766 reason = ProcessMessage::eCoprocessorError; 1767 break; 1768 case ILL_BADSTK: 1769 reason = ProcessMessage::eInternalStackError; 1770 break; 1771 } 1772 1773 return reason; 1774 } 1775 #endif 1776 1777 #if 0 1778 ProcessMessage::CrashReason 1779 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info) 1780 { 1781 ProcessMessage::CrashReason reason; 1782 assert(info->si_signo == SIGFPE); 1783 1784 reason = ProcessMessage::eInvalidCrashReason; 1785 1786 switch (info->si_code) 1787 { 1788 default: 1789 assert(false && "unexpected si_code for SIGFPE"); 1790 break; 1791 case FPE_INTDIV: 1792 reason = ProcessMessage::eIntegerDivideByZero; 1793 break; 1794 case FPE_INTOVF: 1795 reason = ProcessMessage::eIntegerOverflow; 1796 break; 1797 case FPE_FLTDIV: 1798 reason = ProcessMessage::eFloatDivideByZero; 1799 break; 1800 case FPE_FLTOVF: 1801 reason = ProcessMessage::eFloatOverflow; 1802 break; 1803 case FPE_FLTUND: 1804 reason = ProcessMessage::eFloatUnderflow; 1805 break; 1806 case FPE_FLTRES: 1807 reason = ProcessMessage::eFloatInexactResult; 1808 break; 1809 case FPE_FLTINV: 1810 reason = ProcessMessage::eFloatInvalidOperation; 1811 break; 1812 case FPE_FLTSUB: 1813 reason = ProcessMessage::eFloatSubscriptRange; 1814 break; 1815 } 1816 1817 return reason; 1818 } 1819 #endif 1820 1821 #if 0 1822 ProcessMessage::CrashReason 1823 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info) 1824 { 1825 ProcessMessage::CrashReason reason; 1826 assert(info->si_signo == SIGBUS); 1827 1828 reason = ProcessMessage::eInvalidCrashReason; 1829 1830 switch (info->si_code) 1831 { 1832 default: 1833 assert(false && "unexpected si_code for SIGBUS"); 1834 break; 1835 case BUS_ADRALN: 1836 reason = ProcessMessage::eIllegalAlignment; 1837 break; 1838 case BUS_ADRERR: 1839 reason = ProcessMessage::eIllegalAddress; 1840 break; 1841 case BUS_OBJERR: 1842 reason = ProcessMessage::eHardwareError; 1843 break; 1844 } 1845 1846 return reason; 1847 } 1848 #endif 1849 1850 Status NativeProcessLinux::ReadMemory(lldb::addr_t addr, void *buf, size_t size, 1851 size_t &bytes_read) { 1852 if (ProcessVmReadvSupported()) { 1853 // The process_vm_readv path is about 50 times faster than ptrace api. We 1854 // want to use 1855 // this syscall if it is supported. 1856 1857 const ::pid_t pid = GetID(); 1858 1859 struct iovec local_iov, remote_iov; 1860 local_iov.iov_base = buf; 1861 local_iov.iov_len = size; 1862 remote_iov.iov_base = reinterpret_cast<void *>(addr); 1863 remote_iov.iov_len = size; 1864 1865 bytes_read = process_vm_readv(pid, &local_iov, 1, &remote_iov, 1, 0); 1866 const bool success = bytes_read == size; 1867 1868 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 1869 LLDB_LOG(log, 1870 "using process_vm_readv to read {0} bytes from inferior " 1871 "address {1:x}: {2}", 1872 size, addr, success ? "Success" : llvm::sys::StrError(errno)); 1873 1874 if (success) 1875 return Status(); 1876 // else the call failed for some reason, let's retry the read using ptrace 1877 // api. 1878 } 1879 1880 unsigned char *dst = static_cast<unsigned char *>(buf); 1881 size_t remainder; 1882 long data; 1883 1884 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1885 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 1886 1887 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) { 1888 Status error = NativeProcessLinux::PtraceWrapper( 1889 PTRACE_PEEKDATA, GetID(), (void *)addr, nullptr, 0, &data); 1890 if (error.Fail()) 1891 return error; 1892 1893 remainder = size - bytes_read; 1894 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 1895 1896 // Copy the data into our buffer 1897 memcpy(dst, &data, remainder); 1898 1899 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1900 addr += k_ptrace_word_size; 1901 dst += k_ptrace_word_size; 1902 } 1903 return Status(); 1904 } 1905 1906 Status NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, 1907 size_t size, 1908 size_t &bytes_read) { 1909 Status error = ReadMemory(addr, buf, size, bytes_read); 1910 if (error.Fail()) 1911 return error; 1912 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); 1913 } 1914 1915 Status NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, 1916 size_t size, size_t &bytes_written) { 1917 const unsigned char *src = static_cast<const unsigned char *>(buf); 1918 size_t remainder; 1919 Status error; 1920 1921 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 1922 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 1923 1924 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) { 1925 remainder = size - bytes_written; 1926 remainder = remainder > k_ptrace_word_size ? k_ptrace_word_size : remainder; 1927 1928 if (remainder == k_ptrace_word_size) { 1929 unsigned long data = 0; 1930 memcpy(&data, src, k_ptrace_word_size); 1931 1932 LLDB_LOG(log, "[{0:x}]:{1:x}", addr, data); 1933 error = NativeProcessLinux::PtraceWrapper(PTRACE_POKEDATA, GetID(), 1934 (void *)addr, (void *)data); 1935 if (error.Fail()) 1936 return error; 1937 } else { 1938 unsigned char buff[8]; 1939 size_t bytes_read; 1940 error = ReadMemory(addr, buff, k_ptrace_word_size, bytes_read); 1941 if (error.Fail()) 1942 return error; 1943 1944 memcpy(buff, src, remainder); 1945 1946 size_t bytes_written_rec; 1947 error = WriteMemory(addr, buff, k_ptrace_word_size, bytes_written_rec); 1948 if (error.Fail()) 1949 return error; 1950 1951 LLDB_LOG(log, "[{0:x}]:{1:x} ({2:x})", addr, *(const unsigned long *)src, 1952 *(unsigned long *)buff); 1953 } 1954 1955 addr += k_ptrace_word_size; 1956 src += k_ptrace_word_size; 1957 } 1958 return error; 1959 } 1960 1961 Status NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) { 1962 return PtraceWrapper(PTRACE_GETSIGINFO, tid, nullptr, siginfo); 1963 } 1964 1965 Status NativeProcessLinux::GetEventMessage(lldb::tid_t tid, 1966 unsigned long *message) { 1967 return PtraceWrapper(PTRACE_GETEVENTMSG, tid, nullptr, message); 1968 } 1969 1970 Status NativeProcessLinux::Detach(lldb::tid_t tid) { 1971 if (tid == LLDB_INVALID_THREAD_ID) 1972 return Status(); 1973 1974 return PtraceWrapper(PTRACE_DETACH, tid); 1975 } 1976 1977 bool NativeProcessLinux::HasThreadNoLock(lldb::tid_t thread_id) { 1978 for (auto thread_sp : m_threads) { 1979 assert(thread_sp && "thread list should not contain NULL threads"); 1980 if (thread_sp->GetID() == thread_id) { 1981 // We have this thread. 1982 return true; 1983 } 1984 } 1985 1986 // We don't have this thread. 1987 return false; 1988 } 1989 1990 bool NativeProcessLinux::StopTrackingThread(lldb::tid_t thread_id) { 1991 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 1992 LLDB_LOG(log, "tid: {0})", thread_id); 1993 1994 bool found = false; 1995 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 1996 if (*it && ((*it)->GetID() == thread_id)) { 1997 m_threads.erase(it); 1998 found = true; 1999 break; 2000 } 2001 } 2002 2003 if (found) 2004 StopTracingForThread(thread_id); 2005 SignalIfAllThreadsStopped(); 2006 return found; 2007 } 2008 2009 NativeThreadLinuxSP NativeProcessLinux::AddThread(lldb::tid_t thread_id) { 2010 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 2011 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 2012 2013 assert(!HasThreadNoLock(thread_id) && 2014 "attempted to add a thread by id that already exists"); 2015 2016 // If this is the first thread, save it as the current thread 2017 if (m_threads.empty()) 2018 SetCurrentThreadID(thread_id); 2019 2020 auto thread_sp = std::make_shared<NativeThreadLinux>(*this, thread_id); 2021 m_threads.push_back(thread_sp); 2022 2023 if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 2024 auto traceMonitor = ProcessorTraceMonitor::Create( 2025 GetID(), thread_id, m_pt_process_trace_config, true); 2026 if (traceMonitor) { 2027 m_pt_traced_thread_group.insert(thread_id); 2028 m_processor_trace_monitor.insert( 2029 std::make_pair(thread_id, std::move(*traceMonitor))); 2030 } else { 2031 LLDB_LOG(log, "failed to start trace on thread {0}", thread_id); 2032 Status error(traceMonitor.takeError()); 2033 LLDB_LOG(log, "error {0}", error); 2034 } 2035 } 2036 2037 return thread_sp; 2038 } 2039 2040 Status 2041 NativeProcessLinux::FixupBreakpointPCAsNeeded(NativeThreadLinux &thread) { 2042 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS)); 2043 2044 Status error; 2045 2046 // Find out the size of a breakpoint (might depend on where we are in the 2047 // code). 2048 NativeRegisterContextSP context_sp = thread.GetRegisterContext(); 2049 if (!context_sp) { 2050 error.SetErrorString("cannot get a NativeRegisterContext for the thread"); 2051 LLDB_LOG(log, "failed: {0}", error); 2052 return error; 2053 } 2054 2055 uint32_t breakpoint_size = 0; 2056 error = GetSoftwareBreakpointPCOffset(breakpoint_size); 2057 if (error.Fail()) { 2058 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error); 2059 return error; 2060 } else 2061 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size); 2062 2063 // First try probing for a breakpoint at a software breakpoint location: PC - 2064 // breakpoint size. 2065 const lldb::addr_t initial_pc_addr = 2066 context_sp->GetPCfromBreakpointLocation(); 2067 lldb::addr_t breakpoint_addr = initial_pc_addr; 2068 if (breakpoint_size > 0) { 2069 // Do not allow breakpoint probe to wrap around. 2070 if (breakpoint_addr >= breakpoint_size) 2071 breakpoint_addr -= breakpoint_size; 2072 } 2073 2074 // Check if we stopped because of a breakpoint. 2075 NativeBreakpointSP breakpoint_sp; 2076 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp); 2077 if (!error.Success() || !breakpoint_sp) { 2078 // We didn't find one at a software probe location. Nothing to do. 2079 LLDB_LOG(log, 2080 "pid {0} no lldb breakpoint found at current pc with " 2081 "adjustment: {1}", 2082 GetID(), breakpoint_addr); 2083 return Status(); 2084 } 2085 2086 // If the breakpoint is not a software breakpoint, nothing to do. 2087 if (!breakpoint_sp->IsSoftwareBreakpoint()) { 2088 LLDB_LOG( 2089 log, 2090 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust", 2091 GetID(), breakpoint_addr); 2092 return Status(); 2093 } 2094 2095 // 2096 // We have a software breakpoint and need to adjust the PC. 2097 // 2098 2099 // Sanity check. 2100 if (breakpoint_size == 0) { 2101 // Nothing to do! How did we get here? 2102 LLDB_LOG(log, 2103 "pid {0} breakpoint found at {1:x}, it is software, but the " 2104 "size is zero, nothing to do (unexpected)", 2105 GetID(), breakpoint_addr); 2106 return Status(); 2107 } 2108 2109 // Change the program counter. 2110 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), 2111 thread.GetID(), initial_pc_addr, breakpoint_addr); 2112 2113 error = context_sp->SetPC(breakpoint_addr); 2114 if (error.Fail()) { 2115 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(), 2116 thread.GetID(), error); 2117 return error; 2118 } 2119 2120 return error; 2121 } 2122 2123 Status NativeProcessLinux::GetLoadedModuleFileSpec(const char *module_path, 2124 FileSpec &file_spec) { 2125 Status error = PopulateMemoryRegionCache(); 2126 if (error.Fail()) 2127 return error; 2128 2129 FileSpec module_file_spec(module_path, true); 2130 2131 file_spec.Clear(); 2132 for (const auto &it : m_mem_region_cache) { 2133 if (it.second.GetFilename() == module_file_spec.GetFilename()) { 2134 file_spec = it.second; 2135 return Status(); 2136 } 2137 } 2138 return Status("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 2139 module_file_spec.GetFilename().AsCString(), GetID()); 2140 } 2141 2142 Status NativeProcessLinux::GetFileLoadAddress(const llvm::StringRef &file_name, 2143 lldb::addr_t &load_addr) { 2144 load_addr = LLDB_INVALID_ADDRESS; 2145 Status error = PopulateMemoryRegionCache(); 2146 if (error.Fail()) 2147 return error; 2148 2149 FileSpec file(file_name, false); 2150 for (const auto &it : m_mem_region_cache) { 2151 if (it.second == file) { 2152 load_addr = it.first.GetRange().GetRangeBase(); 2153 return Status(); 2154 } 2155 } 2156 return Status("No load address found for specified file."); 2157 } 2158 2159 NativeThreadLinuxSP NativeProcessLinux::GetThreadByID(lldb::tid_t tid) { 2160 return std::static_pointer_cast<NativeThreadLinux>( 2161 NativeProcessProtocol::GetThreadByID(tid)); 2162 } 2163 2164 Status NativeProcessLinux::ResumeThread(NativeThreadLinux &thread, 2165 lldb::StateType state, int signo) { 2166 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 2167 LLDB_LOG(log, "tid: {0}", thread.GetID()); 2168 2169 // Before we do the resume below, first check if we have a pending 2170 // stop notification that is currently waiting for 2171 // all threads to stop. This is potentially a buggy situation since 2172 // we're ostensibly waiting for threads to stop before we send out the 2173 // pending notification, and here we are resuming one before we send 2174 // out the pending stop notification. 2175 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID) { 2176 LLDB_LOG(log, 2177 "about to resume tid {0} per explicit request but we have a " 2178 "pending stop notification (tid {1}) that is actively " 2179 "waiting for this thread to stop. Valid sequence of events?", 2180 thread.GetID(), m_pending_notification_tid); 2181 } 2182 2183 // Request a resume. We expect this to be synchronous and the system 2184 // to reflect it is running after this completes. 2185 switch (state) { 2186 case eStateRunning: { 2187 const auto resume_result = thread.Resume(signo); 2188 if (resume_result.Success()) 2189 SetState(eStateRunning, true); 2190 return resume_result; 2191 } 2192 case eStateStepping: { 2193 const auto step_result = thread.SingleStep(signo); 2194 if (step_result.Success()) 2195 SetState(eStateRunning, true); 2196 return step_result; 2197 } 2198 default: 2199 LLDB_LOG(log, "Unhandled state {0}.", state); 2200 llvm_unreachable("Unhandled state for resume"); 2201 } 2202 } 2203 2204 //===----------------------------------------------------------------------===// 2205 2206 void NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) { 2207 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 2208 LLDB_LOG(log, "about to process event: (triggering_tid: {0})", 2209 triggering_tid); 2210 2211 m_pending_notification_tid = triggering_tid; 2212 2213 // Request a stop for all the thread stops that need to be stopped 2214 // and are not already known to be stopped. 2215 for (const auto &thread_sp : m_threads) { 2216 if (StateIsRunningState(thread_sp->GetState())) 2217 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop(); 2218 } 2219 2220 SignalIfAllThreadsStopped(); 2221 LLDB_LOG(log, "event processing done"); 2222 } 2223 2224 void NativeProcessLinux::SignalIfAllThreadsStopped() { 2225 if (m_pending_notification_tid == LLDB_INVALID_THREAD_ID) 2226 return; // No pending notification. Nothing to do. 2227 2228 for (const auto &thread_sp : m_threads) { 2229 if (StateIsRunningState(thread_sp->GetState())) 2230 return; // Some threads are still running. Don't signal yet. 2231 } 2232 2233 // We have a pending notification and all threads have stopped. 2234 Log *log( 2235 GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 2236 2237 // Clear any temporary breakpoints we used to implement software single 2238 // stepping. 2239 for (const auto &thread_info : m_threads_stepping_with_breakpoint) { 2240 Status error = RemoveBreakpoint(thread_info.second); 2241 if (error.Fail()) 2242 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}", 2243 thread_info.first, error); 2244 } 2245 m_threads_stepping_with_breakpoint.clear(); 2246 2247 // Notify the delegate about the stop 2248 SetCurrentThreadID(m_pending_notification_tid); 2249 SetState(StateType::eStateStopped, true); 2250 m_pending_notification_tid = LLDB_INVALID_THREAD_ID; 2251 } 2252 2253 void NativeProcessLinux::ThreadWasCreated(NativeThreadLinux &thread) { 2254 Log *const log = ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD); 2255 LLDB_LOG(log, "tid: {0}", thread.GetID()); 2256 2257 if (m_pending_notification_tid != LLDB_INVALID_THREAD_ID && 2258 StateIsRunningState(thread.GetState())) { 2259 // We will need to wait for this new thread to stop as well before firing 2260 // the 2261 // notification. 2262 thread.RequestStop(); 2263 } 2264 } 2265 2266 void NativeProcessLinux::SigchldHandler() { 2267 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 2268 // Process all pending waitpid notifications. 2269 while (true) { 2270 int status = -1; 2271 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, ::waitpid, -1, &status, 2272 __WALL | __WNOTHREAD | WNOHANG); 2273 2274 if (wait_pid == 0) 2275 break; // We are done. 2276 2277 if (wait_pid == -1) { 2278 Status error(errno, eErrorTypePOSIX); 2279 LLDB_LOG(log, "waitpid (-1, &status, _) failed: {0}", error); 2280 break; 2281 } 2282 2283 WaitStatus wait_status = WaitStatus::Decode(status); 2284 bool exited = wait_status.type == WaitStatus::Exit || 2285 (wait_status.type == WaitStatus::Signal && 2286 wait_pid == static_cast<::pid_t>(GetID())); 2287 2288 LLDB_LOG( 2289 log, 2290 "waitpid (-1, &status, _) => pid = {0}, status = {1}, exited = {2}", 2291 wait_pid, wait_status, exited); 2292 2293 MonitorCallback(wait_pid, exited, wait_status); 2294 } 2295 } 2296 2297 // Wrapper for ptrace to catch errors and log calls. 2298 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. 2299 // for PTRACE_PEEK*) 2300 Status NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 2301 void *data, size_t data_size, 2302 long *result) { 2303 Status error; 2304 long int ret; 2305 2306 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2307 2308 PtraceDisplayBytes(req, data, data_size); 2309 2310 errno = 0; 2311 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 2312 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 2313 *(unsigned int *)addr, data); 2314 else 2315 ret = ptrace(static_cast<__ptrace_request>(req), static_cast<::pid_t>(pid), 2316 addr, data); 2317 2318 if (ret == -1) 2319 error.SetErrorToErrno(); 2320 2321 if (result) 2322 *result = ret; 2323 2324 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3}, {4})={5:x}", req, pid, addr, data, 2325 data_size, ret); 2326 2327 PtraceDisplayBytes(req, data, data_size); 2328 2329 if (error.Fail()) 2330 LLDB_LOG(log, "ptrace() failed: {0}", error); 2331 2332 return error; 2333 } 2334 2335 llvm::Expected<ProcessorTraceMonitor &> 2336 NativeProcessLinux::LookupProcessorTraceInstance(lldb::user_id_t traceid, 2337 lldb::tid_t thread) { 2338 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2339 if (thread == LLDB_INVALID_THREAD_ID && traceid == m_pt_proces_trace_id) { 2340 LLDB_LOG(log, "thread not specified: {0}", traceid); 2341 return Status("tracing not active thread not specified").ToError(); 2342 } 2343 2344 for (auto& iter : m_processor_trace_monitor) { 2345 if (traceid == iter.second->GetTraceID() && 2346 (thread == iter.first || thread == LLDB_INVALID_THREAD_ID)) 2347 return *(iter.second); 2348 } 2349 2350 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 2351 return Status("tracing not active for this thread").ToError(); 2352 } 2353 2354 Status NativeProcessLinux::GetMetaData(lldb::user_id_t traceid, 2355 lldb::tid_t thread, 2356 llvm::MutableArrayRef<uint8_t> &buffer, 2357 size_t offset) { 2358 TraceOptions trace_options; 2359 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2360 Status error; 2361 2362 LLDB_LOG(log, "traceid {0}", traceid); 2363 2364 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 2365 if (!perf_monitor) { 2366 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 2367 buffer = buffer.slice(buffer.size()); 2368 error = perf_monitor.takeError(); 2369 return error; 2370 } 2371 return (*perf_monitor).ReadPerfTraceData(buffer, offset); 2372 } 2373 2374 Status NativeProcessLinux::GetData(lldb::user_id_t traceid, lldb::tid_t thread, 2375 llvm::MutableArrayRef<uint8_t> &buffer, 2376 size_t offset) { 2377 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2378 Status error; 2379 2380 LLDB_LOG(log, "traceid {0}", traceid); 2381 2382 auto perf_monitor = LookupProcessorTraceInstance(traceid, thread); 2383 if (!perf_monitor) { 2384 LLDB_LOG(log, "traceid not being traced: {0}", traceid); 2385 buffer = buffer.slice(buffer.size()); 2386 error = perf_monitor.takeError(); 2387 return error; 2388 } 2389 return (*perf_monitor).ReadPerfTraceAux(buffer, offset); 2390 } 2391 2392 Status NativeProcessLinux::GetTraceConfig(lldb::user_id_t traceid, 2393 TraceOptions &config) { 2394 Status error; 2395 if (config.getThreadID() == LLDB_INVALID_THREAD_ID && 2396 m_pt_proces_trace_id == traceid) { 2397 if (m_pt_proces_trace_id == LLDB_INVALID_UID) { 2398 error.SetErrorString("tracing not active for this process"); 2399 return error; 2400 } 2401 config = m_pt_process_trace_config; 2402 } else { 2403 auto perf_monitor = 2404 LookupProcessorTraceInstance(traceid, config.getThreadID()); 2405 if (!perf_monitor) { 2406 error = perf_monitor.takeError(); 2407 return error; 2408 } 2409 error = (*perf_monitor).GetTraceConfig(config); 2410 } 2411 return error; 2412 } 2413 2414 lldb::user_id_t 2415 NativeProcessLinux::StartTraceGroup(const TraceOptions &config, 2416 Status &error) { 2417 2418 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2419 if (config.getType() != TraceType::eTraceTypeProcessorTrace) 2420 return LLDB_INVALID_UID; 2421 2422 if (m_pt_proces_trace_id != LLDB_INVALID_UID) { 2423 error.SetErrorString("tracing already active on this process"); 2424 return m_pt_proces_trace_id; 2425 } 2426 2427 for (const auto &thread_sp : m_threads) { 2428 if (auto traceInstance = ProcessorTraceMonitor::Create( 2429 GetID(), thread_sp->GetID(), config, true)) { 2430 m_pt_traced_thread_group.insert(thread_sp->GetID()); 2431 m_processor_trace_monitor.insert( 2432 std::make_pair(thread_sp->GetID(), std::move(*traceInstance))); 2433 } 2434 } 2435 2436 m_pt_process_trace_config = config; 2437 error = ProcessorTraceMonitor::GetCPUType(m_pt_process_trace_config); 2438 2439 // Trace on Complete process will have traceid of 0 2440 m_pt_proces_trace_id = 0; 2441 2442 LLDB_LOG(log, "Process Trace ID {0}", m_pt_proces_trace_id); 2443 return m_pt_proces_trace_id; 2444 } 2445 2446 lldb::user_id_t NativeProcessLinux::StartTrace(const TraceOptions &config, 2447 Status &error) { 2448 if (config.getType() != TraceType::eTraceTypeProcessorTrace) 2449 return NativeProcessProtocol::StartTrace(config, error); 2450 2451 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2452 2453 lldb::tid_t threadid = config.getThreadID(); 2454 2455 if (threadid == LLDB_INVALID_THREAD_ID) 2456 return StartTraceGroup(config, error); 2457 2458 auto thread_sp = GetThreadByID(threadid); 2459 if (!thread_sp) { 2460 // Thread not tracked by lldb so don't trace. 2461 error.SetErrorString("invalid thread id"); 2462 return LLDB_INVALID_UID; 2463 } 2464 2465 const auto &iter = m_processor_trace_monitor.find(threadid); 2466 if (iter != m_processor_trace_monitor.end()) { 2467 LLDB_LOG(log, "Thread already being traced"); 2468 error.SetErrorString("tracing already active on this thread"); 2469 return LLDB_INVALID_UID; 2470 } 2471 2472 auto traceMonitor = 2473 ProcessorTraceMonitor::Create(GetID(), threadid, config, false); 2474 if (!traceMonitor) { 2475 error = traceMonitor.takeError(); 2476 LLDB_LOG(log, "error {0}", error); 2477 return LLDB_INVALID_UID; 2478 } 2479 lldb::user_id_t ret_trace_id = (*traceMonitor)->GetTraceID(); 2480 m_processor_trace_monitor.insert( 2481 std::make_pair(threadid, std::move(*traceMonitor))); 2482 return ret_trace_id; 2483 } 2484 2485 Status NativeProcessLinux::StopTracingForThread(lldb::tid_t thread) { 2486 Status error; 2487 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2488 LLDB_LOG(log, "Thread {0}", thread); 2489 2490 const auto& iter = m_processor_trace_monitor.find(thread); 2491 if (iter == m_processor_trace_monitor.end()) { 2492 error.SetErrorString("tracing not active for this thread"); 2493 return error; 2494 } 2495 2496 if (iter->second->GetTraceID() == m_pt_proces_trace_id) { 2497 // traceid maps to the whole process so we have to erase it from the 2498 // thread group. 2499 LLDB_LOG(log, "traceid maps to process"); 2500 m_pt_traced_thread_group.erase(thread); 2501 } 2502 m_processor_trace_monitor.erase(iter); 2503 2504 return error; 2505 } 2506 2507 Status NativeProcessLinux::StopTrace(lldb::user_id_t traceid, 2508 lldb::tid_t thread) { 2509 Status error; 2510 2511 TraceOptions trace_options; 2512 trace_options.setThreadID(thread); 2513 error = NativeProcessLinux::GetTraceConfig(traceid, trace_options); 2514 2515 if (error.Fail()) 2516 return error; 2517 2518 switch (trace_options.getType()) { 2519 case lldb::TraceType::eTraceTypeProcessorTrace: 2520 if (traceid == m_pt_proces_trace_id && 2521 thread == LLDB_INVALID_THREAD_ID) 2522 StopProcessorTracingOnProcess(); 2523 else 2524 error = StopProcessorTracingOnThread(traceid, thread); 2525 break; 2526 default: 2527 error.SetErrorString("trace not supported"); 2528 break; 2529 } 2530 2531 return error; 2532 } 2533 2534 void NativeProcessLinux::StopProcessorTracingOnProcess() { 2535 for (auto thread_id_iter : m_pt_traced_thread_group) 2536 m_processor_trace_monitor.erase(thread_id_iter); 2537 m_pt_traced_thread_group.clear(); 2538 m_pt_proces_trace_id = LLDB_INVALID_UID; 2539 } 2540 2541 Status NativeProcessLinux::StopProcessorTracingOnThread(lldb::user_id_t traceid, 2542 lldb::tid_t thread) { 2543 Status error; 2544 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 2545 2546 if (thread == LLDB_INVALID_THREAD_ID) { 2547 for (auto& iter : m_processor_trace_monitor) { 2548 if (iter.second->GetTraceID() == traceid) { 2549 // Stopping a trace instance for an individual thread 2550 // hence there will only be one traceid that can match. 2551 m_processor_trace_monitor.erase(iter.first); 2552 return error; 2553 } 2554 LLDB_LOG(log, "Trace ID {0}", iter.second->GetTraceID()); 2555 } 2556 2557 LLDB_LOG(log, "Invalid TraceID"); 2558 error.SetErrorString("invalid trace id"); 2559 return error; 2560 } 2561 2562 // thread is specified so we can use find function on the map. 2563 const auto& iter = m_processor_trace_monitor.find(thread); 2564 if (iter == m_processor_trace_monitor.end()) { 2565 // thread not found in our map. 2566 LLDB_LOG(log, "thread not being traced"); 2567 error.SetErrorString("tracing not active for this thread"); 2568 return error; 2569 } 2570 if (iter->second->GetTraceID() != traceid) { 2571 // traceid did not match so it has to be invalid. 2572 LLDB_LOG(log, "Invalid TraceID"); 2573 error.SetErrorString("invalid trace id"); 2574 return error; 2575 } 2576 2577 LLDB_LOG(log, "UID - {0} , Thread -{1}", traceid, thread); 2578 2579 if (traceid == m_pt_proces_trace_id) { 2580 // traceid maps to the whole process so we have to erase it from the 2581 // thread group. 2582 LLDB_LOG(log, "traceid maps to process"); 2583 m_pt_traced_thread_group.erase(thread); 2584 } 2585 m_processor_trace_monitor.erase(iter); 2586 2587 return error; 2588 } 2589