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