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