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