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