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