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