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