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