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