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