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