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