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