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(m_child_pid, &status, __WALL | 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 (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s", 801 __FUNCTION__, m_child_pid, 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 == abs(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 (pid = %" PRIi32 ", &status, __WALL | WNOHANG)" 834 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i", 835 __FUNCTION__, m_child_pid, 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 = -getpgid(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); 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 switch (signo) 2221 { 2222 case SIGSEGV: 2223 case SIGILL: 2224 case SIGFPE: 2225 case SIGBUS: 2226 if (thread_sp) 2227 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info); 2228 break; 2229 default: 2230 // This is just a pre-signal-delivery notification of the incoming signal. 2231 if (thread_sp) 2232 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo); 2233 2234 break; 2235 } 2236 2237 // Send a stop to the debugger after we get all other threads to stop. 2238 StopRunningThreads (pid); 2239 } 2240 2241 namespace { 2242 2243 struct EmulatorBaton 2244 { 2245 NativeProcessLinux* m_process; 2246 NativeRegisterContext* m_reg_context; 2247 2248 // eRegisterKindDWARF -> RegsiterValue 2249 std::unordered_map<uint32_t, RegisterValue> m_register_values; 2250 2251 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) : 2252 m_process(process), m_reg_context(reg_context) {} 2253 }; 2254 2255 } // anonymous namespace 2256 2257 static size_t 2258 ReadMemoryCallback (EmulateInstruction *instruction, 2259 void *baton, 2260 const EmulateInstruction::Context &context, 2261 lldb::addr_t addr, 2262 void *dst, 2263 size_t length) 2264 { 2265 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2266 2267 size_t bytes_read; 2268 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read); 2269 return bytes_read; 2270 } 2271 2272 static bool 2273 ReadRegisterCallback (EmulateInstruction *instruction, 2274 void *baton, 2275 const RegisterInfo *reg_info, 2276 RegisterValue ®_value) 2277 { 2278 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2279 2280 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]); 2281 if (it != emulator_baton->m_register_values.end()) 2282 { 2283 reg_value = it->second; 2284 return true; 2285 } 2286 2287 // The emulator only fill in the dwarf regsiter numbers (and in some case 2288 // the generic register numbers). Get the full register info from the 2289 // register context based on the dwarf register numbers. 2290 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo( 2291 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 2292 2293 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value); 2294 if (error.Success()) 2295 return true; 2296 2297 return false; 2298 } 2299 2300 static bool 2301 WriteRegisterCallback (EmulateInstruction *instruction, 2302 void *baton, 2303 const EmulateInstruction::Context &context, 2304 const RegisterInfo *reg_info, 2305 const RegisterValue ®_value) 2306 { 2307 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2308 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value; 2309 return true; 2310 } 2311 2312 static size_t 2313 WriteMemoryCallback (EmulateInstruction *instruction, 2314 void *baton, 2315 const EmulateInstruction::Context &context, 2316 lldb::addr_t addr, 2317 const void *dst, 2318 size_t length) 2319 { 2320 return length; 2321 } 2322 2323 static lldb::addr_t 2324 ReadFlags (NativeRegisterContext* regsiter_context) 2325 { 2326 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo( 2327 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2328 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS); 2329 } 2330 2331 Error 2332 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp) 2333 { 2334 Error error; 2335 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext(); 2336 2337 std::unique_ptr<EmulateInstruction> emulator_ap( 2338 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr)); 2339 2340 if (emulator_ap == nullptr) 2341 return Error("Instruction emulator not found!"); 2342 2343 EmulatorBaton baton(this, register_context_sp.get()); 2344 emulator_ap->SetBaton(&baton); 2345 emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 2346 emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 2347 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 2348 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 2349 2350 if (!emulator_ap->ReadInstruction()) 2351 return Error("Read instruction failed!"); 2352 2353 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 2354 2355 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 2356 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2357 2358 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 2359 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 2360 2361 lldb::addr_t next_pc; 2362 lldb::addr_t next_flags; 2363 if (emulation_result) 2364 { 2365 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated"); 2366 next_pc = pc_it->second.GetAsUInt64(); 2367 2368 if (flags_it != baton.m_register_values.end()) 2369 next_flags = flags_it->second.GetAsUInt64(); 2370 else 2371 next_flags = ReadFlags (register_context_sp.get()); 2372 } 2373 else if (pc_it == baton.m_register_values.end()) 2374 { 2375 // Emulate instruction failed and it haven't changed PC. Advance PC 2376 // with the size of the current opcode because the emulation of all 2377 // PC modifying instruction should be successful. The failure most 2378 // likely caused by a not supported instruction which don't modify PC. 2379 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize(); 2380 next_flags = ReadFlags (register_context_sp.get()); 2381 } 2382 else 2383 { 2384 // The instruction emulation failed after it modified the PC. It is an 2385 // unknown error where we can't continue because the next instruction is 2386 // modifying the PC but we don't know how. 2387 return Error ("Instruction emulation failed unexpectedly."); 2388 } 2389 2390 if (m_arch.GetMachine() == llvm::Triple::arm) 2391 { 2392 if (next_flags & 0x20) 2393 { 2394 // Thumb mode 2395 error = SetSoftwareBreakpoint(next_pc, 2); 2396 } 2397 else 2398 { 2399 // Arm mode 2400 error = SetSoftwareBreakpoint(next_pc, 4); 2401 } 2402 } 2403 else if (m_arch.GetMachine() == llvm::Triple::mips64 2404 || m_arch.GetMachine() == llvm::Triple::mips64el) 2405 error = SetSoftwareBreakpoint(next_pc, 4); 2406 else 2407 { 2408 // No size hint is given for the next breakpoint 2409 error = SetSoftwareBreakpoint(next_pc, 0); 2410 } 2411 2412 if (error.Fail()) 2413 return error; 2414 2415 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc}); 2416 2417 return Error(); 2418 } 2419 2420 bool 2421 NativeProcessLinux::SupportHardwareSingleStepping() const 2422 { 2423 if (m_arch.GetMachine() == llvm::Triple::arm 2424 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el) 2425 return false; 2426 return true; 2427 } 2428 2429 Error 2430 NativeProcessLinux::Resume (const ResumeActionList &resume_actions) 2431 { 2432 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2433 if (log) 2434 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ()); 2435 2436 bool software_single_step = !SupportHardwareSingleStepping(); 2437 2438 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 2439 Mutex::Locker locker (m_threads_mutex); 2440 2441 if (software_single_step) 2442 { 2443 for (auto thread_sp : m_threads) 2444 { 2445 assert (thread_sp && "thread list should not contain NULL threads"); 2446 2447 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 2448 if (action == nullptr) 2449 continue; 2450 2451 if (action->state == eStateStepping) 2452 { 2453 Error error = SetupSoftwareSingleStepping(thread_sp); 2454 if (error.Fail()) 2455 return error; 2456 } 2457 } 2458 } 2459 2460 for (auto thread_sp : m_threads) 2461 { 2462 assert (thread_sp && "thread list should not contain NULL threads"); 2463 2464 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 2465 2466 if (action == nullptr) 2467 { 2468 if (log) 2469 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64, 2470 __FUNCTION__, GetID (), thread_sp->GetID ()); 2471 continue; 2472 } 2473 2474 if (log) 2475 { 2476 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64, 2477 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 2478 } 2479 2480 switch (action->state) 2481 { 2482 case eStateRunning: 2483 { 2484 // Run the thread, possibly feeding it the signal. 2485 const int signo = action->signal; 2486 ResumeThread(thread_sp->GetID (), 2487 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2488 { 2489 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2490 // Pass this signal number on to the inferior to handle. 2491 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 2492 if (resume_result.Success()) 2493 SetState(eStateRunning, true); 2494 return resume_result; 2495 }, 2496 false); 2497 break; 2498 } 2499 2500 case eStateStepping: 2501 { 2502 // Request the step. 2503 const int signo = action->signal; 2504 ResumeThread(thread_sp->GetID (), 2505 [=](lldb::tid_t tid_to_step, bool supress_signal) 2506 { 2507 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping (); 2508 2509 Error step_result; 2510 if (software_single_step) 2511 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 2512 else 2513 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 2514 2515 assert (step_result.Success() && "SingleStep() failed"); 2516 if (step_result.Success()) 2517 SetState(eStateStepping, true); 2518 return step_result; 2519 }, 2520 false); 2521 break; 2522 } 2523 2524 case eStateSuspended: 2525 case eStateStopped: 2526 lldbassert(0 && "Unexpected state"); 2527 2528 default: 2529 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64, 2530 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 2531 } 2532 } 2533 2534 return Error(); 2535 } 2536 2537 Error 2538 NativeProcessLinux::Halt () 2539 { 2540 Error error; 2541 2542 if (kill (GetID (), SIGSTOP) != 0) 2543 error.SetErrorToErrno (); 2544 2545 return error; 2546 } 2547 2548 Error 2549 NativeProcessLinux::Detach () 2550 { 2551 Error error; 2552 2553 // Tell ptrace to detach from the process. 2554 if (GetID () != LLDB_INVALID_PROCESS_ID) 2555 error = Detach (GetID ()); 2556 2557 // Stop monitoring the inferior. 2558 m_monitor_up->Terminate(); 2559 2560 // No error. 2561 return error; 2562 } 2563 2564 Error 2565 NativeProcessLinux::Signal (int signo) 2566 { 2567 Error error; 2568 2569 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2570 if (log) 2571 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64, 2572 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ()); 2573 2574 if (kill(GetID(), signo)) 2575 error.SetErrorToErrno(); 2576 2577 return error; 2578 } 2579 2580 Error 2581 NativeProcessLinux::Interrupt () 2582 { 2583 // Pick a running thread (or if none, a not-dead stopped thread) as 2584 // the chosen thread that will be the stop-reason thread. 2585 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2586 2587 NativeThreadProtocolSP running_thread_sp; 2588 NativeThreadProtocolSP stopped_thread_sp; 2589 2590 if (log) 2591 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__); 2592 2593 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 2594 Mutex::Locker locker (m_threads_mutex); 2595 2596 for (auto thread_sp : m_threads) 2597 { 2598 // The thread shouldn't be null but lets just cover that here. 2599 if (!thread_sp) 2600 continue; 2601 2602 // If we have a running or stepping thread, we'll call that the 2603 // target of the interrupt. 2604 const auto thread_state = thread_sp->GetState (); 2605 if (thread_state == eStateRunning || 2606 thread_state == eStateStepping) 2607 { 2608 running_thread_sp = thread_sp; 2609 break; 2610 } 2611 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true)) 2612 { 2613 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads. 2614 stopped_thread_sp = thread_sp; 2615 } 2616 } 2617 2618 if (!running_thread_sp && !stopped_thread_sp) 2619 { 2620 Error error("found no running/stepping or live stopped threads as target for interrupt"); 2621 if (log) 2622 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ()); 2623 2624 return error; 2625 } 2626 2627 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp; 2628 2629 if (log) 2630 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target", 2631 __FUNCTION__, 2632 GetID (), 2633 running_thread_sp ? "running" : "stopped", 2634 deferred_signal_thread_sp->GetID ()); 2635 2636 StopRunningThreads(deferred_signal_thread_sp->GetID()); 2637 2638 return Error(); 2639 } 2640 2641 Error 2642 NativeProcessLinux::Kill () 2643 { 2644 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2645 if (log) 2646 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ()); 2647 2648 Error error; 2649 2650 switch (m_state) 2651 { 2652 case StateType::eStateInvalid: 2653 case StateType::eStateExited: 2654 case StateType::eStateCrashed: 2655 case StateType::eStateDetached: 2656 case StateType::eStateUnloaded: 2657 // Nothing to do - the process is already dead. 2658 if (log) 2659 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state)); 2660 return error; 2661 2662 case StateType::eStateConnected: 2663 case StateType::eStateAttaching: 2664 case StateType::eStateLaunching: 2665 case StateType::eStateStopped: 2666 case StateType::eStateRunning: 2667 case StateType::eStateStepping: 2668 case StateType::eStateSuspended: 2669 // We can try to kill a process in these states. 2670 break; 2671 } 2672 2673 if (kill (GetID (), SIGKILL) != 0) 2674 { 2675 error.SetErrorToErrno (); 2676 return error; 2677 } 2678 2679 return error; 2680 } 2681 2682 static Error 2683 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info) 2684 { 2685 memory_region_info.Clear(); 2686 2687 StringExtractor line_extractor (maps_line.c_str ()); 2688 2689 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname 2690 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared). 2691 2692 // Parse out the starting address 2693 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0); 2694 2695 // Parse out hyphen separating start and end address from range. 2696 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-')) 2697 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range"); 2698 2699 // Parse out the ending address 2700 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address); 2701 2702 // Parse out the space after the address. 2703 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' ')) 2704 return Error ("malformed /proc/{pid}/maps entry, missing space after range"); 2705 2706 // Save the range. 2707 memory_region_info.GetRange ().SetRangeBase (start_address); 2708 memory_region_info.GetRange ().SetRangeEnd (end_address); 2709 2710 // Parse out each permission entry. 2711 if (line_extractor.GetBytesLeft () < 4) 2712 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions"); 2713 2714 // Handle read permission. 2715 const char read_perm_char = line_extractor.GetChar (); 2716 if (read_perm_char == 'r') 2717 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes); 2718 else 2719 { 2720 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" ); 2721 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 2722 } 2723 2724 // Handle write permission. 2725 const char write_perm_char = line_extractor.GetChar (); 2726 if (write_perm_char == 'w') 2727 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes); 2728 else 2729 { 2730 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" ); 2731 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 2732 } 2733 2734 // Handle execute permission. 2735 const char exec_perm_char = line_extractor.GetChar (); 2736 if (exec_perm_char == 'x') 2737 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes); 2738 else 2739 { 2740 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" ); 2741 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 2742 } 2743 2744 return Error (); 2745 } 2746 2747 Error 2748 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) 2749 { 2750 // FIXME review that the final memory region returned extends to the end of the virtual address space, 2751 // with no perms if it is not mapped. 2752 2753 // Use an approach that reads memory regions from /proc/{pid}/maps. 2754 // Assume proc maps entries are in ascending order. 2755 // FIXME assert if we find differently. 2756 Mutex::Locker locker (m_mem_region_cache_mutex); 2757 2758 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2759 Error error; 2760 2761 if (m_supports_mem_region == LazyBool::eLazyBoolNo) 2762 { 2763 // We're done. 2764 error.SetErrorString ("unsupported"); 2765 return error; 2766 } 2767 2768 // If our cache is empty, pull the latest. There should always be at least one memory region 2769 // if memory region handling is supported. 2770 if (m_mem_region_cache.empty ()) 2771 { 2772 error = ProcFileReader::ProcessLineByLine (GetID (), "maps", 2773 [&] (const std::string &line) -> bool 2774 { 2775 MemoryRegionInfo info; 2776 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info); 2777 if (parse_error.Success ()) 2778 { 2779 m_mem_region_cache.push_back (info); 2780 return true; 2781 } 2782 else 2783 { 2784 if (log) 2785 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ()); 2786 return false; 2787 } 2788 }); 2789 2790 // If we had an error, we'll mark unsupported. 2791 if (error.Fail ()) 2792 { 2793 m_supports_mem_region = LazyBool::eLazyBoolNo; 2794 return error; 2795 } 2796 else if (m_mem_region_cache.empty ()) 2797 { 2798 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps 2799 // is supported. Assume we don't support map entries via procfs. 2800 if (log) 2801 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__); 2802 m_supports_mem_region = LazyBool::eLazyBoolNo; 2803 error.SetErrorString ("not supported"); 2804 return error; 2805 } 2806 2807 if (log) 2808 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ()); 2809 2810 // We support memory retrieval, remember that. 2811 m_supports_mem_region = LazyBool::eLazyBoolYes; 2812 } 2813 else 2814 { 2815 if (log) 2816 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 2817 } 2818 2819 lldb::addr_t prev_base_address = 0; 2820 2821 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted. 2822 // There can be a ton of regions on pthreads apps with lots of threads. 2823 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it) 2824 { 2825 MemoryRegionInfo &proc_entry_info = *it; 2826 2827 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 2828 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"); 2829 prev_base_address = proc_entry_info.GetRange ().GetRangeBase (); 2830 2831 // If the target address comes before this entry, indicate distance to next region. 2832 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ()) 2833 { 2834 range_info.GetRange ().SetRangeBase (load_addr); 2835 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr); 2836 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 2837 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 2838 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 2839 2840 return error; 2841 } 2842 else if (proc_entry_info.GetRange ().Contains (load_addr)) 2843 { 2844 // The target address is within the memory region we're processing here. 2845 range_info = proc_entry_info; 2846 return error; 2847 } 2848 2849 // The target memory address comes somewhere after the region we just parsed. 2850 } 2851 2852 // If we made it here, we didn't find an entry that contained the given address. 2853 error.SetErrorString ("address comes after final region"); 2854 2855 if (log) 2856 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ()); 2857 2858 return error; 2859 } 2860 2861 void 2862 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId) 2863 { 2864 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2865 if (log) 2866 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId); 2867 2868 { 2869 Mutex::Locker locker (m_mem_region_cache_mutex); 2870 if (log) 2871 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 2872 m_mem_region_cache.clear (); 2873 } 2874 } 2875 2876 Error 2877 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr) 2878 { 2879 // FIXME implementing this requires the equivalent of 2880 // InferiorCallPOSIX::InferiorCallMmap, which depends on 2881 // functional ThreadPlans working with Native*Protocol. 2882 #if 1 2883 return Error ("not implemented yet"); 2884 #else 2885 addr = LLDB_INVALID_ADDRESS; 2886 2887 unsigned prot = 0; 2888 if (permissions & lldb::ePermissionsReadable) 2889 prot |= eMmapProtRead; 2890 if (permissions & lldb::ePermissionsWritable) 2891 prot |= eMmapProtWrite; 2892 if (permissions & lldb::ePermissionsExecutable) 2893 prot |= eMmapProtExec; 2894 2895 // TODO implement this directly in NativeProcessLinux 2896 // (and lift to NativeProcessPOSIX if/when that class is 2897 // refactored out). 2898 if (InferiorCallMmap(this, addr, 0, size, prot, 2899 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 2900 m_addr_to_mmap_size[addr] = size; 2901 return Error (); 2902 } else { 2903 addr = LLDB_INVALID_ADDRESS; 2904 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 2905 } 2906 #endif 2907 } 2908 2909 Error 2910 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr) 2911 { 2912 // FIXME see comments in AllocateMemory - required lower-level 2913 // bits not in place yet (ThreadPlans) 2914 return Error ("not implemented"); 2915 } 2916 2917 lldb::addr_t 2918 NativeProcessLinux::GetSharedLibraryInfoAddress () 2919 { 2920 #if 1 2921 // punt on this for now 2922 return LLDB_INVALID_ADDRESS; 2923 #else 2924 // Return the image info address for the exe module 2925 #if 1 2926 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2927 2928 ModuleSP module_sp; 2929 Error error = GetExeModuleSP (module_sp); 2930 if (error.Fail ()) 2931 { 2932 if (log) 2933 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ()); 2934 return LLDB_INVALID_ADDRESS; 2935 } 2936 2937 if (module_sp == nullptr) 2938 { 2939 if (log) 2940 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__); 2941 return LLDB_INVALID_ADDRESS; 2942 } 2943 2944 ObjectFileSP object_file_sp = module_sp->GetObjectFile (); 2945 if (object_file_sp == nullptr) 2946 { 2947 if (log) 2948 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__); 2949 return LLDB_INVALID_ADDRESS; 2950 } 2951 2952 return obj_file_sp->GetImageInfoAddress(); 2953 #else 2954 Target *target = &GetTarget(); 2955 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); 2956 Address addr = obj_file->GetImageInfoAddress(target); 2957 2958 if (addr.IsValid()) 2959 return addr.GetLoadAddress(target); 2960 return LLDB_INVALID_ADDRESS; 2961 #endif 2962 #endif // punt on this for now 2963 } 2964 2965 size_t 2966 NativeProcessLinux::UpdateThreads () 2967 { 2968 // The NativeProcessLinux monitoring threads are always up to date 2969 // with respect to thread state and they keep the thread list 2970 // populated properly. All this method needs to do is return the 2971 // thread count. 2972 Mutex::Locker locker (m_threads_mutex); 2973 return m_threads.size (); 2974 } 2975 2976 bool 2977 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const 2978 { 2979 arch = m_arch; 2980 return true; 2981 } 2982 2983 Error 2984 NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size) 2985 { 2986 // FIXME put this behind a breakpoint protocol class that can be 2987 // set per architecture. Need ARM, MIPS support here. 2988 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 2989 static const uint8_t g_i386_opcode [] = { 0xCC }; 2990 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 2991 2992 switch (m_arch.GetMachine ()) 2993 { 2994 case llvm::Triple::aarch64: 2995 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode)); 2996 return Error (); 2997 2998 case llvm::Triple::arm: 2999 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits 3000 return Error (); 3001 3002 case llvm::Triple::x86: 3003 case llvm::Triple::x86_64: 3004 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode)); 3005 return Error (); 3006 3007 case llvm::Triple::mips64: 3008 case llvm::Triple::mips64el: 3009 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode)); 3010 return Error (); 3011 3012 default: 3013 assert(false && "CPU type not supported!"); 3014 return Error ("CPU type not supported"); 3015 } 3016 } 3017 3018 Error 3019 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) 3020 { 3021 if (hardware) 3022 return Error ("NativeProcessLinux does not support hardware breakpoints"); 3023 else 3024 return SetSoftwareBreakpoint (addr, size); 3025 } 3026 3027 Error 3028 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, 3029 size_t &actual_opcode_size, 3030 const uint8_t *&trap_opcode_bytes) 3031 { 3032 // FIXME put this behind a breakpoint protocol class that can be set per 3033 // architecture. Need MIPS support here. 3034 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3035 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 3036 // linux kernel does otherwise. 3037 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 }; 3038 static const uint8_t g_i386_opcode [] = { 0xCC }; 3039 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 3040 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 }; 3041 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde }; 3042 3043 switch (m_arch.GetMachine ()) 3044 { 3045 case llvm::Triple::aarch64: 3046 trap_opcode_bytes = g_aarch64_opcode; 3047 actual_opcode_size = sizeof(g_aarch64_opcode); 3048 return Error (); 3049 3050 case llvm::Triple::arm: 3051 switch (trap_opcode_size_hint) 3052 { 3053 case 2: 3054 trap_opcode_bytes = g_thumb_breakpoint_opcode; 3055 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode); 3056 return Error (); 3057 case 4: 3058 trap_opcode_bytes = g_arm_breakpoint_opcode; 3059 actual_opcode_size = sizeof(g_arm_breakpoint_opcode); 3060 return Error (); 3061 default: 3062 assert(false && "Unrecognised trap opcode size hint!"); 3063 return Error ("Unrecognised trap opcode size hint!"); 3064 } 3065 3066 case llvm::Triple::x86: 3067 case llvm::Triple::x86_64: 3068 trap_opcode_bytes = g_i386_opcode; 3069 actual_opcode_size = sizeof(g_i386_opcode); 3070 return Error (); 3071 3072 case llvm::Triple::mips64: 3073 trap_opcode_bytes = g_mips64_opcode; 3074 actual_opcode_size = sizeof(g_mips64_opcode); 3075 return Error (); 3076 3077 case llvm::Triple::mips64el: 3078 trap_opcode_bytes = g_mips64el_opcode; 3079 actual_opcode_size = sizeof(g_mips64el_opcode); 3080 return Error (); 3081 3082 default: 3083 assert(false && "CPU type not supported!"); 3084 return Error ("CPU type not supported"); 3085 } 3086 } 3087 3088 #if 0 3089 ProcessMessage::CrashReason 3090 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info) 3091 { 3092 ProcessMessage::CrashReason reason; 3093 assert(info->si_signo == SIGSEGV); 3094 3095 reason = ProcessMessage::eInvalidCrashReason; 3096 3097 switch (info->si_code) 3098 { 3099 default: 3100 assert(false && "unexpected si_code for SIGSEGV"); 3101 break; 3102 case SI_KERNEL: 3103 // Linux will occasionally send spurious SI_KERNEL codes. 3104 // (this is poorly documented in sigaction) 3105 // One way to get this is via unaligned SIMD loads. 3106 reason = ProcessMessage::eInvalidAddress; // for lack of anything better 3107 break; 3108 case SEGV_MAPERR: 3109 reason = ProcessMessage::eInvalidAddress; 3110 break; 3111 case SEGV_ACCERR: 3112 reason = ProcessMessage::ePrivilegedAddress; 3113 break; 3114 } 3115 3116 return reason; 3117 } 3118 #endif 3119 3120 3121 #if 0 3122 ProcessMessage::CrashReason 3123 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info) 3124 { 3125 ProcessMessage::CrashReason reason; 3126 assert(info->si_signo == SIGILL); 3127 3128 reason = ProcessMessage::eInvalidCrashReason; 3129 3130 switch (info->si_code) 3131 { 3132 default: 3133 assert(false && "unexpected si_code for SIGILL"); 3134 break; 3135 case ILL_ILLOPC: 3136 reason = ProcessMessage::eIllegalOpcode; 3137 break; 3138 case ILL_ILLOPN: 3139 reason = ProcessMessage::eIllegalOperand; 3140 break; 3141 case ILL_ILLADR: 3142 reason = ProcessMessage::eIllegalAddressingMode; 3143 break; 3144 case ILL_ILLTRP: 3145 reason = ProcessMessage::eIllegalTrap; 3146 break; 3147 case ILL_PRVOPC: 3148 reason = ProcessMessage::ePrivilegedOpcode; 3149 break; 3150 case ILL_PRVREG: 3151 reason = ProcessMessage::ePrivilegedRegister; 3152 break; 3153 case ILL_COPROC: 3154 reason = ProcessMessage::eCoprocessorError; 3155 break; 3156 case ILL_BADSTK: 3157 reason = ProcessMessage::eInternalStackError; 3158 break; 3159 } 3160 3161 return reason; 3162 } 3163 #endif 3164 3165 #if 0 3166 ProcessMessage::CrashReason 3167 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info) 3168 { 3169 ProcessMessage::CrashReason reason; 3170 assert(info->si_signo == SIGFPE); 3171 3172 reason = ProcessMessage::eInvalidCrashReason; 3173 3174 switch (info->si_code) 3175 { 3176 default: 3177 assert(false && "unexpected si_code for SIGFPE"); 3178 break; 3179 case FPE_INTDIV: 3180 reason = ProcessMessage::eIntegerDivideByZero; 3181 break; 3182 case FPE_INTOVF: 3183 reason = ProcessMessage::eIntegerOverflow; 3184 break; 3185 case FPE_FLTDIV: 3186 reason = ProcessMessage::eFloatDivideByZero; 3187 break; 3188 case FPE_FLTOVF: 3189 reason = ProcessMessage::eFloatOverflow; 3190 break; 3191 case FPE_FLTUND: 3192 reason = ProcessMessage::eFloatUnderflow; 3193 break; 3194 case FPE_FLTRES: 3195 reason = ProcessMessage::eFloatInexactResult; 3196 break; 3197 case FPE_FLTINV: 3198 reason = ProcessMessage::eFloatInvalidOperation; 3199 break; 3200 case FPE_FLTSUB: 3201 reason = ProcessMessage::eFloatSubscriptRange; 3202 break; 3203 } 3204 3205 return reason; 3206 } 3207 #endif 3208 3209 #if 0 3210 ProcessMessage::CrashReason 3211 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info) 3212 { 3213 ProcessMessage::CrashReason reason; 3214 assert(info->si_signo == SIGBUS); 3215 3216 reason = ProcessMessage::eInvalidCrashReason; 3217 3218 switch (info->si_code) 3219 { 3220 default: 3221 assert(false && "unexpected si_code for SIGBUS"); 3222 break; 3223 case BUS_ADRALN: 3224 reason = ProcessMessage::eIllegalAlignment; 3225 break; 3226 case BUS_ADRERR: 3227 reason = ProcessMessage::eIllegalAddress; 3228 break; 3229 case BUS_OBJERR: 3230 reason = ProcessMessage::eHardwareError; 3231 break; 3232 } 3233 3234 return reason; 3235 } 3236 #endif 3237 3238 Error 3239 NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) 3240 { 3241 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor 3242 // for it. 3243 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3244 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware); 3245 } 3246 3247 Error 3248 NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr) 3249 { 3250 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor 3251 // for it. 3252 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3253 return NativeProcessProtocol::RemoveWatchpoint(addr); 3254 } 3255 3256 Error 3257 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3258 { 3259 ReadOperation op(addr, buf, size, bytes_read); 3260 m_monitor_up->DoOperation(&op); 3261 return op.GetError (); 3262 } 3263 3264 Error 3265 NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3266 { 3267 Error error = ReadMemory(addr, buf, size, bytes_read); 3268 if (error.Fail()) return error; 3269 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); 3270 } 3271 3272 Error 3273 NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) 3274 { 3275 WriteOperation op(addr, buf, size, bytes_written); 3276 m_monitor_up->DoOperation(&op); 3277 return op.GetError (); 3278 } 3279 3280 Error 3281 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo) 3282 { 3283 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3284 3285 if (log) 3286 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid, 3287 GetUnixSignals().GetSignalAsCString (signo)); 3288 ResumeOperation op (tid, signo); 3289 m_monitor_up->DoOperation (&op); 3290 if (log) 3291 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false"); 3292 return op.GetError(); 3293 } 3294 3295 Error 3296 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo) 3297 { 3298 SingleStepOperation op(tid, signo); 3299 m_monitor_up->DoOperation(&op); 3300 return op.GetError(); 3301 } 3302 3303 Error 3304 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) 3305 { 3306 SiginfoOperation op(tid, siginfo); 3307 m_monitor_up->DoOperation(&op); 3308 return op.GetError(); 3309 } 3310 3311 Error 3312 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message) 3313 { 3314 EventMessageOperation op(tid, message); 3315 m_monitor_up->DoOperation(&op); 3316 return op.GetError(); 3317 } 3318 3319 Error 3320 NativeProcessLinux::Detach(lldb::tid_t tid) 3321 { 3322 if (tid == LLDB_INVALID_THREAD_ID) 3323 return Error(); 3324 3325 DetachOperation op(tid); 3326 m_monitor_up->DoOperation(&op); 3327 return op.GetError(); 3328 } 3329 3330 bool 3331 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags) 3332 { 3333 int target_fd = open(path, flags, 0666); 3334 3335 if (target_fd == -1) 3336 return false; 3337 3338 if (dup2(target_fd, fd) == -1) 3339 return false; 3340 3341 return (close(target_fd) == -1) ? false : true; 3342 } 3343 3344 void 3345 NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error) 3346 { 3347 m_monitor_up.reset(new Monitor(initial_operation, this)); 3348 error = m_monitor_up->Initialize(); 3349 if (error.Fail()) { 3350 m_monitor_up.reset(); 3351 } 3352 } 3353 3354 bool 3355 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id) 3356 { 3357 for (auto thread_sp : m_threads) 3358 { 3359 assert (thread_sp && "thread list should not contain NULL threads"); 3360 if (thread_sp->GetID () == thread_id) 3361 { 3362 // We have this thread. 3363 return true; 3364 } 3365 } 3366 3367 // We don't have this thread. 3368 return false; 3369 } 3370 3371 NativeThreadProtocolSP 3372 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id) 3373 { 3374 // CONSIDER organize threads by map - we can do better than linear. 3375 for (auto thread_sp : m_threads) 3376 { 3377 if (thread_sp->GetID () == thread_id) 3378 return thread_sp; 3379 } 3380 3381 // We don't have this thread. 3382 return NativeThreadProtocolSP (); 3383 } 3384 3385 bool 3386 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id) 3387 { 3388 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3389 3390 if (log) 3391 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, thread_id); 3392 3393 bool found = false; 3394 3395 Mutex::Locker locker (m_threads_mutex); 3396 for (auto it = m_threads.begin (); it != m_threads.end (); ++it) 3397 { 3398 if (*it && ((*it)->GetID () == thread_id)) 3399 { 3400 m_threads.erase (it); 3401 found = true; 3402 break; 3403 } 3404 } 3405 3406 // If we have a pending notification, remove this from the set. 3407 if (m_pending_notification_up) 3408 { 3409 m_pending_notification_up->wait_for_stop_tids.erase(thread_id); 3410 SignalIfAllThreadsStopped(); 3411 } 3412 3413 return found; 3414 } 3415 3416 NativeThreadProtocolSP 3417 NativeProcessLinux::AddThread (lldb::tid_t thread_id) 3418 { 3419 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 3420 3421 Mutex::Locker locker (m_threads_mutex); 3422 3423 if (log) 3424 { 3425 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64, 3426 __FUNCTION__, 3427 GetID (), 3428 thread_id); 3429 } 3430 3431 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists"); 3432 3433 // If this is the first thread, save it as the current thread 3434 if (m_threads.empty ()) 3435 SetCurrentThreadID (thread_id); 3436 3437 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id)); 3438 m_threads.push_back (thread_sp); 3439 3440 return thread_sp; 3441 } 3442 3443 Error 3444 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp) 3445 { 3446 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 3447 3448 Error error; 3449 3450 // Get a linux thread pointer. 3451 if (!thread_sp) 3452 { 3453 error.SetErrorString ("null thread_sp"); 3454 if (log) 3455 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 3456 return error; 3457 } 3458 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp); 3459 3460 // Find out the size of a breakpoint (might depend on where we are in the code). 3461 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext (); 3462 if (!context_sp) 3463 { 3464 error.SetErrorString ("cannot get a NativeRegisterContext for the thread"); 3465 if (log) 3466 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 3467 return error; 3468 } 3469 3470 uint32_t breakpoint_size = 0; 3471 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size); 3472 if (error.Fail ()) 3473 { 3474 if (log) 3475 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ()); 3476 return error; 3477 } 3478 else 3479 { 3480 if (log) 3481 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size); 3482 } 3483 3484 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size. 3485 const lldb::addr_t initial_pc_addr = context_sp->GetPC (); 3486 lldb::addr_t breakpoint_addr = initial_pc_addr; 3487 if (breakpoint_size > 0) 3488 { 3489 // Do not allow breakpoint probe to wrap around. 3490 if (breakpoint_addr >= breakpoint_size) 3491 breakpoint_addr -= breakpoint_size; 3492 } 3493 3494 // Check if we stopped because of a breakpoint. 3495 NativeBreakpointSP breakpoint_sp; 3496 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp); 3497 if (!error.Success () || !breakpoint_sp) 3498 { 3499 // We didn't find one at a software probe location. Nothing to do. 3500 if (log) 3501 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr); 3502 return Error (); 3503 } 3504 3505 // If the breakpoint is not a software breakpoint, nothing to do. 3506 if (!breakpoint_sp->IsSoftwareBreakpoint ()) 3507 { 3508 if (log) 3509 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr); 3510 return Error (); 3511 } 3512 3513 // 3514 // We have a software breakpoint and need to adjust the PC. 3515 // 3516 3517 // Sanity check. 3518 if (breakpoint_size == 0) 3519 { 3520 // Nothing to do! How did we get here? 3521 if (log) 3522 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); 3523 return Error (); 3524 } 3525 3526 // Change the program counter. 3527 if (log) 3528 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); 3529 3530 error = context_sp->SetPC (breakpoint_addr); 3531 if (error.Fail ()) 3532 { 3533 if (log) 3534 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ()); 3535 return error; 3536 } 3537 3538 return error; 3539 } 3540 3541 Error 3542 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) 3543 { 3544 char maps_file_name[32]; 3545 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID()); 3546 3547 FileSpec maps_file_spec(maps_file_name, false); 3548 if (!maps_file_spec.Exists()) { 3549 file_spec.Clear(); 3550 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID()); 3551 } 3552 3553 FileSpec module_file_spec(module_path, true); 3554 3555 std::ifstream maps_file(maps_file_name); 3556 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>()); 3557 StringRef maps_data(maps_data_str.c_str()); 3558 3559 while (!maps_data.empty()) 3560 { 3561 StringRef maps_row; 3562 std::tie(maps_row, maps_data) = maps_data.split('\n'); 3563 3564 SmallVector<StringRef, 16> maps_columns; 3565 maps_row.split(maps_columns, StringRef(" "), -1, false); 3566 3567 if (maps_columns.size() >= 6) 3568 { 3569 file_spec.SetFile(maps_columns[5].str().c_str(), false); 3570 if (file_spec.GetFilename() == module_file_spec.GetFilename()) 3571 return Error(); 3572 } 3573 } 3574 3575 file_spec.Clear(); 3576 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 3577 module_file_spec.GetFilename().AsCString(), GetID()); 3578 } 3579 3580 Error 3581 NativeProcessLinux::ResumeThread( 3582 lldb::tid_t tid, 3583 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function, 3584 bool error_when_already_running) 3585 { 3586 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3587 3588 if (log) 3589 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", error_when_already_running: %s)", 3590 __FUNCTION__, tid, error_when_already_running?"true":"false"); 3591 3592 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 3593 lldbassert(thread_sp != nullptr); 3594 3595 auto& context = thread_sp->GetThreadContext(); 3596 // Tell the thread to resume if we don't already think it is running. 3597 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true); 3598 3599 lldbassert(!(error_when_already_running && !is_stopped)); 3600 3601 if (!is_stopped) 3602 { 3603 // It's not an error, just a log, if the error_when_already_running flag is not set. 3604 // This covers cases where, for instance, we're just trying to resume all threads 3605 // from the user side. 3606 if (log) 3607 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running", 3608 __FUNCTION__, 3609 tid); 3610 return Error(); 3611 } 3612 3613 // Before we do the resume below, first check if we have a pending 3614 // stop notification that is currently waiting for 3615 // this thread to stop. This is potentially a buggy situation since 3616 // we're ostensibly waiting for threads to stop before we send out the 3617 // pending notification, and here we are resuming one before we send 3618 // out the pending stop notification. 3619 if (m_pending_notification_up && log && m_pending_notification_up->wait_for_stop_tids.count (tid) > 0) 3620 { 3621 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); 3622 } 3623 3624 // Request a resume. We expect this to be synchronous and the system 3625 // to reflect it is running after this completes. 3626 const auto error = request_thread_resume_function (tid, false); 3627 if (error.Success()) 3628 context.request_resume_function = request_thread_resume_function; 3629 else if (log) 3630 { 3631 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 3632 __FUNCTION__, tid, error.AsCString ()); 3633 } 3634 3635 return error; 3636 } 3637 3638 //===----------------------------------------------------------------------===// 3639 3640 void 3641 NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) 3642 { 3643 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3644 3645 if (log) 3646 { 3647 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")", 3648 __FUNCTION__, triggering_tid); 3649 } 3650 3651 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid))); 3652 3653 if (log) 3654 { 3655 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 3656 } 3657 } 3658 3659 void 3660 NativeProcessLinux::SignalIfAllThreadsStopped() 3661 { 3662 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ()) 3663 { 3664 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 3665 3666 // Clear any temporary breakpoints we used to implement software single stepping. 3667 for (const auto &thread_info: m_threads_stepping_with_breakpoint) 3668 { 3669 Error error = RemoveBreakpoint (thread_info.second); 3670 if (error.Fail()) 3671 if (log) 3672 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s", 3673 __FUNCTION__, thread_info.first, error.AsCString()); 3674 } 3675 m_threads_stepping_with_breakpoint.clear(); 3676 3677 // Notify the delegate about the stop 3678 SetCurrentThreadID(m_pending_notification_up->triggering_tid); 3679 SetState(StateType::eStateStopped, true); 3680 m_pending_notification_up.reset(); 3681 } 3682 } 3683 3684 void 3685 NativeProcessLinux::RequestStopOnAllRunningThreads() 3686 { 3687 // Request a stop for all the thread stops that need to be stopped 3688 // and are not already known to be stopped. Keep a list of all the 3689 // threads from which we still need to hear a stop reply. 3690 3691 ThreadIDSet sent_tids; 3692 for (const auto &thread_sp: m_threads) 3693 { 3694 // We only care about running threads 3695 if (StateIsStoppedState(thread_sp->GetState(), true)) 3696 continue; 3697 3698 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop(); 3699 sent_tids.insert (thread_sp->GetID()); 3700 } 3701 3702 // Set the wait list to the set of tids for which we requested stops. 3703 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids); 3704 } 3705 3706 3707 Error 3708 NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs) 3709 { 3710 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3711 3712 if (log) 3713 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ", %sinitiated by llgs)", 3714 __FUNCTION__, tid, initiated_by_llgs?"":"not "); 3715 3716 // Ensure we know about the thread. 3717 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 3718 lldbassert(thread_sp != nullptr); 3719 3720 // Update the global list of known thread states. This one is definitely stopped. 3721 auto& context = thread_sp->GetThreadContext(); 3722 const auto stop_was_requested = context.stop_requested; 3723 context.stop_requested = false; 3724 3725 // If we have a pending notification, remove this from the set. 3726 if (m_pending_notification_up) 3727 { 3728 m_pending_notification_up->wait_for_stop_tids.erase(tid); 3729 SignalIfAllThreadsStopped(); 3730 } 3731 3732 Error error; 3733 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested) 3734 { 3735 // We can end up here if stop was initiated by LLGS but by this time a 3736 // thread stop has occurred - maybe initiated by another event. 3737 if (log) 3738 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid); 3739 error = context.request_resume_function (tid, true); 3740 if (error.Fail() && log) 3741 { 3742 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 3743 __FUNCTION__, tid, error.AsCString ()); 3744 } 3745 } 3746 return error; 3747 } 3748 3749 void 3750 NativeProcessLinux::DoStopThreads(PendingNotificationUP &¬ification_up) 3751 { 3752 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3753 if (m_pending_notification_up && log) 3754 { 3755 // Yikes - we've already got a pending signal notification in progress. 3756 // Log this info. We lose the pending notification here. 3757 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64, 3758 __FUNCTION__, 3759 m_pending_notification_up->triggering_tid, 3760 notification_up->triggering_tid); 3761 } 3762 m_pending_notification_up = std::move(notification_up); 3763 3764 RequestStopOnAllRunningThreads(); 3765 3766 SignalIfAllThreadsStopped(); 3767 } 3768 3769 void 3770 NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid) 3771 { 3772 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 3773 3774 if (log) 3775 log->Printf("NativeProcessLinux::%s (tid: %" PRIu64 ")", __FUNCTION__, tid); 3776 3777 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 3778 lldbassert(thread_sp != nullptr); 3779 3780 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState())) 3781 { 3782 // We will need to wait for this new thread to stop as well before firing the 3783 // notification. 3784 m_pending_notification_up->wait_for_stop_tids.insert(tid); 3785 thread_sp->RequestStop(); 3786 } 3787 } 3788 3789 Error 3790 NativeProcessLinux::DoOperation(Operation* op) 3791 { 3792 m_monitor_up->DoOperation(op); 3793 return op->GetError(); 3794 } 3795 3796 // Wrapper for ptrace to catch errors and log calls. 3797 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 3798 long 3799 NativeProcessLinux::PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error) 3800 { 3801 long int result; 3802 3803 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE)); 3804 3805 PtraceDisplayBytes(req, data, data_size); 3806 3807 error.Clear(); 3808 errno = 0; 3809 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 3810 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data); 3811 else 3812 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data); 3813 3814 if (result == -1) 3815 error.SetErrorToErrno(); 3816 3817 if (log) 3818 log->Printf("ptrace(%d, %" PRIu64 ", %p, %p, %zu)=%lX", req, pid, addr, data, data_size, result); 3819 3820 PtraceDisplayBytes(req, data, data_size); 3821 3822 if (log && error.GetError() != 0) 3823 { 3824 const char* str; 3825 switch (error.GetError()) 3826 { 3827 case ESRCH: str = "ESRCH"; break; 3828 case EINVAL: str = "EINVAL"; break; 3829 case EBUSY: str = "EBUSY"; break; 3830 case EPERM: str = "EPERM"; break; 3831 default: str = error.AsCString(); 3832 } 3833 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str); 3834 } 3835 3836 return result; 3837 } 3838