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