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