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