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