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