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