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