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