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