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