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