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