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