1 //===-- NativeProcessLinux.cpp -------------------------------- -*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "lldb/lldb-python.h" 11 12 #include "NativeProcessLinux.h" 13 14 // C Includes 15 #include <errno.h> 16 #include <poll.h> 17 #include <string.h> 18 #include <stdint.h> 19 #include <unistd.h> 20 21 // C++ Includes 22 #include <fstream> 23 #include <sstream> 24 #include <string> 25 26 // Other libraries and framework includes 27 #include "lldb/Core/Debugger.h" 28 #include "lldb/Core/EmulateInstruction.h" 29 #include "lldb/Core/Error.h" 30 #include "lldb/Core/Module.h" 31 #include "lldb/Core/ModuleSpec.h" 32 #include "lldb/Core/RegisterValue.h" 33 #include "lldb/Core/Scalar.h" 34 #include "lldb/Core/State.h" 35 #include "lldb/Host/common/NativeBreakpoint.h" 36 #include "lldb/Host/common/NativeRegisterContext.h" 37 #include "lldb/Host/Host.h" 38 #include "lldb/Host/HostInfo.h" 39 #include "lldb/Host/HostNativeThread.h" 40 #include "lldb/Host/ThreadLauncher.h" 41 #include "lldb/Symbol/ObjectFile.h" 42 #include "lldb/Target/Process.h" 43 #include "lldb/Target/ProcessLaunchInfo.h" 44 #include "lldb/Utility/LLDBAssert.h" 45 #include "lldb/Utility/PseudoTerminal.h" 46 47 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 48 #include "Plugins/Process/Utility/LinuxSignals.h" 49 #include "Utility/StringExtractor.h" 50 #include "NativeThreadLinux.h" 51 #include "ProcFileReader.h" 52 #include "Procfs.h" 53 54 // System includes - They have to be included after framework includes because they define some 55 // macros which collide with variable names in other modules 56 #include <linux/unistd.h> 57 #include <sys/personality.h> 58 #include <sys/ptrace.h> 59 #include <sys/socket.h> 60 #include <sys/signalfd.h> 61 #include <sys/syscall.h> 62 #include <sys/types.h> 63 #include <sys/uio.h> 64 #include <sys/user.h> 65 #include <sys/wait.h> 66 67 #if defined (__arm64__) || defined (__aarch64__) 68 // NT_PRSTATUS and NT_FPREGSET definition 69 #include <elf.h> 70 #endif 71 72 #ifdef __ANDROID__ 73 #define __ptrace_request int 74 #define PT_DETACH PTRACE_DETACH 75 #endif 76 77 #define DEBUG_PTRACE_MAXBYTES 20 78 79 // Support ptrace extensions even when compiled without required kernel support 80 #ifndef PT_GETREGS 81 #ifndef PTRACE_GETREGS 82 #define PTRACE_GETREGS 12 83 #endif 84 #endif 85 #ifndef PT_SETREGS 86 #ifndef PTRACE_SETREGS 87 #define PTRACE_SETREGS 13 88 #endif 89 #endif 90 #ifndef PT_GETFPREGS 91 #ifndef PTRACE_GETFPREGS 92 #define PTRACE_GETFPREGS 14 93 #endif 94 #endif 95 #ifndef PT_SETFPREGS 96 #ifndef PTRACE_SETFPREGS 97 #define PTRACE_SETFPREGS 15 98 #endif 99 #endif 100 #ifndef PTRACE_GETREGSET 101 #define PTRACE_GETREGSET 0x4204 102 #endif 103 #ifndef PTRACE_SETREGSET 104 #define PTRACE_SETREGSET 0x4205 105 #endif 106 #ifndef PTRACE_GET_THREAD_AREA 107 #define PTRACE_GET_THREAD_AREA 25 108 #endif 109 #ifndef PTRACE_ARCH_PRCTL 110 #define PTRACE_ARCH_PRCTL 30 111 #endif 112 #ifndef ARCH_GET_FS 113 #define ARCH_SET_GS 0x1001 114 #define ARCH_SET_FS 0x1002 115 #define ARCH_GET_FS 0x1003 116 #define ARCH_GET_GS 0x1004 117 #endif 118 119 #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff 120 121 // Support hardware breakpoints in case it has not been defined 122 #ifndef TRAP_HWBKPT 123 #define TRAP_HWBKPT 4 124 #endif 125 126 // Try to define a macro to encapsulate the tgkill syscall 127 // fall back on kill() if tgkill isn't available 128 #define tgkill(pid, tid, sig) \ 129 syscall(SYS_tgkill, static_cast<::pid_t>(pid), static_cast<::pid_t>(tid), sig) 130 131 // We disable the tracing of ptrace calls for integration builds to 132 // avoid the additional indirection and checks. 133 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION 134 #define PTRACE(req, pid, addr, data, data_size, error) \ 135 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__) 136 #else 137 #define PTRACE(req, pid, addr, data, data_size, error) \ 138 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error)) 139 #endif 140 141 using namespace lldb; 142 using namespace lldb_private; 143 using namespace lldb_private::process_linux; 144 using namespace llvm; 145 146 // Private bits we only need internally. 147 namespace 148 { 149 const UnixSignals& 150 GetUnixSignals () 151 { 152 static process_linux::LinuxSignals signals; 153 return signals; 154 } 155 156 Error 157 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch) 158 { 159 // Grab process info for the running process. 160 ProcessInstanceInfo process_info; 161 if (!platform.GetProcessInfo (pid, process_info)) 162 return Error("failed to get process info"); 163 164 // Resolve the executable module. 165 ModuleSP exe_module_sp; 166 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture()); 167 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ()); 168 Error error = platform.ResolveExecutable( 169 exe_module_spec, 170 exe_module_sp, 171 executable_search_paths.GetSize () ? &executable_search_paths : NULL); 172 173 if (!error.Success ()) 174 return error; 175 176 // Check if we've got our architecture from the exe_module. 177 arch = exe_module_sp->GetArchitecture (); 178 if (arch.IsValid ()) 179 return Error(); 180 else 181 return Error("failed to retrieve a valid architecture from the exe module"); 182 } 183 184 void 185 DisplayBytes (StreamString &s, void *bytes, uint32_t count) 186 { 187 uint8_t *ptr = (uint8_t *)bytes; 188 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 189 for(uint32_t i=0; i<loop_count; i++) 190 { 191 s.Printf ("[%x]", *ptr); 192 ptr++; 193 } 194 } 195 196 void 197 PtraceDisplayBytes(int &req, void *data, size_t data_size) 198 { 199 StreamString buf; 200 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet ( 201 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE)); 202 203 if (verbose_log) 204 { 205 switch(req) 206 { 207 case PTRACE_POKETEXT: 208 { 209 DisplayBytes(buf, &data, 8); 210 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData()); 211 break; 212 } 213 case PTRACE_POKEDATA: 214 { 215 DisplayBytes(buf, &data, 8); 216 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData()); 217 break; 218 } 219 case PTRACE_POKEUSER: 220 { 221 DisplayBytes(buf, &data, 8); 222 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData()); 223 break; 224 } 225 case PTRACE_SETREGS: 226 { 227 DisplayBytes(buf, data, data_size); 228 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData()); 229 break; 230 } 231 case PTRACE_SETFPREGS: 232 { 233 DisplayBytes(buf, data, data_size); 234 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData()); 235 break; 236 } 237 case PTRACE_SETSIGINFO: 238 { 239 DisplayBytes(buf, data, sizeof(siginfo_t)); 240 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData()); 241 break; 242 } 243 case PTRACE_SETREGSET: 244 { 245 // Extract iov_base from data, which is a pointer to the struct IOVEC 246 DisplayBytes(buf, *(void **)data, data_size); 247 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData()); 248 break; 249 } 250 default: 251 { 252 } 253 } 254 } 255 } 256 257 // Wrapper for ptrace to catch errors and log calls. 258 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 259 long 260 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error, 261 const char* reqName, const char* file, int line) 262 { 263 long int result; 264 265 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE)); 266 267 PtraceDisplayBytes(req, data, data_size); 268 269 error.Clear(); 270 errno = 0; 271 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 272 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data); 273 else 274 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data); 275 276 if (result == -1) 277 error.SetErrorToErrno(); 278 279 if (log) 280 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d", 281 reqName, pid, addr, data, data_size, result, file, line); 282 283 PtraceDisplayBytes(req, data, data_size); 284 285 if (log && error.GetError() != 0) 286 { 287 const char* str; 288 switch (error.GetError()) 289 { 290 case ESRCH: str = "ESRCH"; break; 291 case EINVAL: str = "EINVAL"; break; 292 case EBUSY: str = "EBUSY"; break; 293 case EPERM: str = "EPERM"; break; 294 default: str = error.AsCString(); 295 } 296 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str); 297 } 298 299 return result; 300 } 301 302 #ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION 303 // Wrapper for ptrace when logging is not required. 304 // Sets errno to 0 prior to calling ptrace. 305 long 306 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error) 307 { 308 long result = 0; 309 310 error.Clear(); 311 errno = 0; 312 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 313 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data); 314 else 315 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data); 316 317 if (result == -1) 318 error.SetErrorToErrno(); 319 return result; 320 } 321 #endif 322 323 //------------------------------------------------------------------------------ 324 // Static implementations of NativeProcessLinux::ReadMemory and 325 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these 326 // functions without needed to go thru the thread funnel. 327 328 size_t 329 DoReadMemory( 330 lldb::pid_t pid, 331 lldb::addr_t vm_addr, 332 void *buf, 333 size_t size, 334 Error &error) 335 { 336 // ptrace word size is determined by the host, not the child 337 static const unsigned word_size = sizeof(void*); 338 unsigned char *dst = static_cast<unsigned char*>(buf); 339 size_t bytes_read; 340 size_t remainder; 341 long data; 342 343 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 344 if (log) 345 ProcessPOSIXLog::IncNestLevel(); 346 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 347 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__, 348 pid, word_size, (void*)vm_addr, buf, size); 349 350 assert(sizeof(data) >= word_size); 351 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) 352 { 353 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error); 354 if (error.Fail()) 355 { 356 if (log) 357 ProcessPOSIXLog::DecNestLevel(); 358 return bytes_read; 359 } 360 361 remainder = size - bytes_read; 362 remainder = remainder > word_size ? word_size : remainder; 363 364 // Copy the data into our buffer 365 for (unsigned i = 0; i < remainder; ++i) 366 dst[i] = ((data >> i*8) & 0xFF); 367 368 if (log && ProcessPOSIXLog::AtTopNestLevel() && 369 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 370 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 371 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 372 { 373 uintptr_t print_dst = 0; 374 // Format bytes from data by moving into print_dst for log output 375 for (unsigned i = 0; i < remainder; ++i) 376 print_dst |= (((data >> i*8) & 0xFF) << i*8); 377 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 378 (void*)vm_addr, print_dst, (unsigned long)data); 379 } 380 381 vm_addr += word_size; 382 dst += word_size; 383 } 384 385 if (log) 386 ProcessPOSIXLog::DecNestLevel(); 387 return bytes_read; 388 } 389 390 size_t 391 DoWriteMemory( 392 lldb::pid_t pid, 393 lldb::addr_t vm_addr, 394 const void *buf, 395 size_t size, 396 Error &error) 397 { 398 // ptrace word size is determined by the host, not the child 399 static const unsigned word_size = sizeof(void*); 400 const unsigned char *src = static_cast<const unsigned char*>(buf); 401 size_t bytes_written = 0; 402 size_t remainder; 403 404 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 405 if (log) 406 ProcessPOSIXLog::IncNestLevel(); 407 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 408 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__, 409 pid, word_size, (void*)vm_addr, buf, size); 410 411 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) 412 { 413 remainder = size - bytes_written; 414 remainder = remainder > word_size ? word_size : remainder; 415 416 if (remainder == word_size) 417 { 418 unsigned long data = 0; 419 assert(sizeof(data) >= word_size); 420 for (unsigned i = 0; i < word_size; ++i) 421 data |= (unsigned long)src[i] << i*8; 422 423 if (log && ProcessPOSIXLog::AtTopNestLevel() && 424 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 425 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 426 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 427 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 428 (void*)vm_addr, *(const unsigned long*)src, data); 429 430 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error)) 431 { 432 if (log) 433 ProcessPOSIXLog::DecNestLevel(); 434 return bytes_written; 435 } 436 } 437 else 438 { 439 unsigned char buff[8]; 440 if (DoReadMemory(pid, vm_addr, 441 buff, word_size, error) != word_size) 442 { 443 if (log) 444 ProcessPOSIXLog::DecNestLevel(); 445 return bytes_written; 446 } 447 448 memcpy(buff, src, remainder); 449 450 if (DoWriteMemory(pid, vm_addr, 451 buff, word_size, error) != word_size) 452 { 453 if (log) 454 ProcessPOSIXLog::DecNestLevel(); 455 return bytes_written; 456 } 457 458 if (log && ProcessPOSIXLog::AtTopNestLevel() && 459 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 460 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 461 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 462 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 463 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff); 464 } 465 466 vm_addr += word_size; 467 src += word_size; 468 } 469 if (log) 470 ProcessPOSIXLog::DecNestLevel(); 471 return bytes_written; 472 } 473 474 //------------------------------------------------------------------------------ 475 /// @class Operation 476 /// @brief Represents a NativeProcessLinux operation. 477 /// 478 /// Under Linux, it is not possible to ptrace() from any other thread but the 479 /// one that spawned or attached to the process from the start. Therefore, when 480 /// a NativeProcessLinux is asked to deliver or change the state of an inferior 481 /// process the operation must be "funneled" to a specific thread to perform the 482 /// task. The Operation class provides an abstract base for all services the 483 /// NativeProcessLinux must perform via the single virtual function Execute, thus 484 /// encapsulating the code that needs to run in the privileged context. 485 class Operation 486 { 487 public: 488 Operation () : m_error() { } 489 490 virtual 491 ~Operation() {} 492 493 virtual void 494 Execute (NativeProcessLinux *process) = 0; 495 496 const Error & 497 GetError () const { return m_error; } 498 499 protected: 500 Error m_error; 501 }; 502 503 //------------------------------------------------------------------------------ 504 /// @class ReadOperation 505 /// @brief Implements NativeProcessLinux::ReadMemory. 506 class ReadOperation : public Operation 507 { 508 public: 509 ReadOperation( 510 lldb::addr_t addr, 511 void *buff, 512 size_t size, 513 size_t &result) : 514 Operation (), 515 m_addr (addr), 516 m_buff (buff), 517 m_size (size), 518 m_result (result) 519 { 520 } 521 522 void Execute (NativeProcessLinux *process) override; 523 524 private: 525 lldb::addr_t m_addr; 526 void *m_buff; 527 size_t m_size; 528 size_t &m_result; 529 }; 530 531 void 532 ReadOperation::Execute (NativeProcessLinux *process) 533 { 534 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error); 535 } 536 537 //------------------------------------------------------------------------------ 538 /// @class WriteOperation 539 /// @brief Implements NativeProcessLinux::WriteMemory. 540 class WriteOperation : public Operation 541 { 542 public: 543 WriteOperation( 544 lldb::addr_t addr, 545 const void *buff, 546 size_t size, 547 size_t &result) : 548 Operation (), 549 m_addr (addr), 550 m_buff (buff), 551 m_size (size), 552 m_result (result) 553 { 554 } 555 556 void Execute (NativeProcessLinux *process) override; 557 558 private: 559 lldb::addr_t m_addr; 560 const void *m_buff; 561 size_t m_size; 562 size_t &m_result; 563 }; 564 565 void 566 WriteOperation::Execute(NativeProcessLinux *process) 567 { 568 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error); 569 } 570 571 //------------------------------------------------------------------------------ 572 /// @class ReadRegOperation 573 /// @brief Implements NativeProcessLinux::ReadRegisterValue. 574 class ReadRegOperation : public Operation 575 { 576 public: 577 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name, 578 RegisterValue &value) 579 : m_tid(tid), 580 m_offset(static_cast<uintptr_t> (offset)), 581 m_reg_name(reg_name), 582 m_value(value) 583 { } 584 585 void Execute(NativeProcessLinux *monitor) override; 586 587 private: 588 lldb::tid_t m_tid; 589 uintptr_t m_offset; 590 const char *m_reg_name; 591 RegisterValue &m_value; 592 }; 593 594 void 595 ReadRegOperation::Execute(NativeProcessLinux *monitor) 596 { 597 #if defined (__arm64__) || defined (__aarch64__) 598 if (m_offset > sizeof(struct user_pt_regs)) 599 { 600 uintptr_t offset = m_offset - sizeof(struct user_pt_regs); 601 if (offset > sizeof(struct user_fpsimd_state)) 602 { 603 m_error.SetErrorString("invalid offset value"); 604 return; 605 } 606 elf_fpregset_t regs; 607 int regset = NT_FPREGSET; 608 struct iovec ioVec; 609 610 ioVec.iov_base = ®s; 611 ioVec.iov_len = sizeof regs; 612 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 613 if (m_error.Success()) 614 { 615 ArchSpec arch; 616 if (monitor->GetArchitecture(arch)) 617 m_value.SetBytes((void *)(((unsigned char *)(®s)) + offset), 16, arch.GetByteOrder()); 618 else 619 m_error.SetErrorString("failed to get architecture"); 620 } 621 } 622 else 623 { 624 elf_gregset_t regs; 625 int regset = NT_PRSTATUS; 626 struct iovec ioVec; 627 628 ioVec.iov_base = ®s; 629 ioVec.iov_len = sizeof regs; 630 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 631 if (m_error.Success()) 632 { 633 ArchSpec arch; 634 if (monitor->GetArchitecture(arch)) 635 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder()); 636 else 637 m_error.SetErrorString("failed to get architecture"); 638 } 639 } 640 #elif defined (__mips__) 641 elf_gregset_t regs; 642 PTRACE(PTRACE_GETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 643 if (m_error.Success()) 644 { 645 lldb_private::ArchSpec arch; 646 if (monitor->GetArchitecture(arch)) 647 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder()); 648 else 649 m_error.SetErrorString("failed to get architecture"); 650 } 651 #else 652 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 653 654 lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error)); 655 if (m_error.Success()) 656 m_value = data; 657 658 if (log) 659 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__, 660 m_reg_name, data); 661 #endif 662 } 663 664 //------------------------------------------------------------------------------ 665 /// @class WriteRegOperation 666 /// @brief Implements NativeProcessLinux::WriteRegisterValue. 667 class WriteRegOperation : public Operation 668 { 669 public: 670 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name, 671 const RegisterValue &value) 672 : m_tid(tid), 673 m_offset(offset), 674 m_reg_name(reg_name), 675 m_value(value) 676 { } 677 678 void Execute(NativeProcessLinux *monitor) override; 679 680 private: 681 lldb::tid_t m_tid; 682 uintptr_t m_offset; 683 const char *m_reg_name; 684 const RegisterValue &m_value; 685 }; 686 687 void 688 WriteRegOperation::Execute(NativeProcessLinux *monitor) 689 { 690 #if defined (__arm64__) || defined (__aarch64__) 691 if (m_offset > sizeof(struct user_pt_regs)) 692 { 693 uintptr_t offset = m_offset - sizeof(struct user_pt_regs); 694 if (offset > sizeof(struct user_fpsimd_state)) 695 { 696 m_error.SetErrorString("invalid offset value"); 697 return; 698 } 699 elf_fpregset_t regs; 700 int regset = NT_FPREGSET; 701 struct iovec ioVec; 702 703 ioVec.iov_base = ®s; 704 ioVec.iov_len = sizeof regs; 705 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 706 if (m_error.Success()) 707 { 708 ::memcpy((void *)(((unsigned char *)(®s)) + offset), m_value.GetBytes(), 16); 709 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 710 } 711 } 712 else 713 { 714 elf_gregset_t regs; 715 int regset = NT_PRSTATUS; 716 struct iovec ioVec; 717 718 ioVec.iov_base = ®s; 719 ioVec.iov_len = sizeof regs; 720 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 721 if (m_error.Success()) 722 { 723 ::memcpy((void *)(((unsigned char *)(®s)) + m_offset), m_value.GetBytes(), 8); 724 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 725 } 726 } 727 #elif defined (__mips__) 728 elf_gregset_t regs; 729 PTRACE(PTRACE_GETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 730 if (m_error.Success()) 731 { 732 ::memcpy((void *)(((unsigned char *)(®s)) + m_offset), m_value.GetBytes(), 8); 733 PTRACE(PTRACE_SETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 734 } 735 #else 736 void* buf; 737 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 738 739 buf = (void*) m_value.GetAsUInt64(); 740 741 if (log) 742 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf); 743 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error); 744 #endif 745 } 746 747 //------------------------------------------------------------------------------ 748 /// @class ReadGPROperation 749 /// @brief Implements NativeProcessLinux::ReadGPR. 750 class ReadGPROperation : public Operation 751 { 752 public: 753 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 754 : m_tid(tid), m_buf(buf), m_buf_size(buf_size) 755 { } 756 757 void Execute(NativeProcessLinux *monitor) override; 758 759 private: 760 lldb::tid_t m_tid; 761 void *m_buf; 762 size_t m_buf_size; 763 }; 764 765 void 766 ReadGPROperation::Execute(NativeProcessLinux *monitor) 767 { 768 #if defined (__arm64__) || defined (__aarch64__) 769 int regset = NT_PRSTATUS; 770 struct iovec ioVec; 771 772 ioVec.iov_base = m_buf; 773 ioVec.iov_len = m_buf_size; 774 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 775 #else 776 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error); 777 #endif 778 } 779 780 //------------------------------------------------------------------------------ 781 /// @class ReadFPROperation 782 /// @brief Implements NativeProcessLinux::ReadFPR. 783 class ReadFPROperation : public Operation 784 { 785 public: 786 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 787 : m_tid(tid), 788 m_buf(buf), 789 m_buf_size(buf_size) 790 { } 791 792 void Execute(NativeProcessLinux *monitor) override; 793 794 private: 795 lldb::tid_t m_tid; 796 void *m_buf; 797 size_t m_buf_size; 798 }; 799 800 void 801 ReadFPROperation::Execute(NativeProcessLinux *monitor) 802 { 803 #if defined (__arm64__) || defined (__aarch64__) 804 int regset = NT_FPREGSET; 805 struct iovec ioVec; 806 807 ioVec.iov_base = m_buf; 808 ioVec.iov_len = m_buf_size; 809 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 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) override; 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) override; 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) override; 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) override; 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) override; 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) override; 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) override; 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) override; 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) override; 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 } // end of anonymous namespace 1053 1054 // Simple helper function to ensure flags are enabled on the given file 1055 // descriptor. 1056 static Error 1057 EnsureFDFlags(int fd, int flags) 1058 { 1059 Error error; 1060 1061 int status = fcntl(fd, F_GETFL); 1062 if (status == -1) 1063 { 1064 error.SetErrorToErrno(); 1065 return error; 1066 } 1067 1068 if (fcntl(fd, F_SETFL, status | flags) == -1) 1069 { 1070 error.SetErrorToErrno(); 1071 return error; 1072 } 1073 1074 return error; 1075 } 1076 1077 // This class encapsulates the privileged thread which performs all ptrace and wait operations on 1078 // the inferior. The thread consists of a main loop which waits for events and processes them 1079 // - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in 1080 // the inferior process. Upon receiving this signal we do a waitpid to get more information 1081 // and dispatch to NativeProcessLinux::MonitorCallback. 1082 // - requests for ptrace operations: These initiated via the DoOperation method, which funnels 1083 // them to the Monitor thread via m_operation member. The Monitor thread is signaled over a 1084 // pipe, and the completion of the operation is signalled over the semaphore. 1085 // - thread exit event: this is signaled from the Monitor destructor by closing the write end 1086 // of the command pipe. 1087 class NativeProcessLinux::Monitor 1088 { 1089 private: 1090 // The initial monitor operation (launch or attach). It returns a inferior process id. 1091 std::unique_ptr<InitialOperation> m_initial_operation_up; 1092 1093 ::pid_t m_child_pid = -1; 1094 NativeProcessLinux * m_native_process; 1095 1096 enum { READ, WRITE }; 1097 int m_pipefd[2] = {-1, -1}; 1098 int m_signal_fd = -1; 1099 HostThread m_thread; 1100 1101 // current operation which must be executed on the priviliged thread 1102 Mutex m_operation_mutex; 1103 Operation *m_operation = nullptr; 1104 sem_t m_operation_sem; 1105 Error m_operation_error; 1106 1107 unsigned m_operation_nesting_level = 0; 1108 1109 static constexpr char operation_command = 'o'; 1110 static constexpr char begin_block_command = '{'; 1111 static constexpr char end_block_command = '}'; 1112 1113 void 1114 HandleSignals(); 1115 1116 void 1117 HandleWait(); 1118 1119 // Returns true if the thread should exit. 1120 bool 1121 HandleCommands(); 1122 1123 void 1124 MainLoop(); 1125 1126 static void * 1127 RunMonitor(void *arg); 1128 1129 Error 1130 WaitForAck(); 1131 1132 void 1133 BeginOperationBlock() 1134 { 1135 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command); 1136 WaitForAck(); 1137 } 1138 1139 void 1140 EndOperationBlock() 1141 { 1142 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command); 1143 WaitForAck(); 1144 } 1145 1146 public: 1147 Monitor(const InitialOperation &initial_operation, 1148 NativeProcessLinux *native_process) 1149 : m_initial_operation_up(new InitialOperation(initial_operation)), 1150 m_native_process(native_process) 1151 { 1152 sem_init(&m_operation_sem, 0, 0); 1153 } 1154 1155 ~Monitor(); 1156 1157 Error 1158 Initialize(); 1159 1160 void 1161 Terminate(); 1162 1163 void 1164 DoOperation(Operation *op); 1165 1166 class ScopedOperationLock { 1167 Monitor &m_monitor; 1168 1169 public: 1170 ScopedOperationLock(Monitor &monitor) 1171 : m_monitor(monitor) 1172 { m_monitor.BeginOperationBlock(); } 1173 1174 ~ScopedOperationLock() 1175 { m_monitor.EndOperationBlock(); } 1176 }; 1177 }; 1178 constexpr char NativeProcessLinux::Monitor::operation_command; 1179 constexpr char NativeProcessLinux::Monitor::begin_block_command; 1180 constexpr char NativeProcessLinux::Monitor::end_block_command; 1181 1182 Error 1183 NativeProcessLinux::Monitor::Initialize() 1184 { 1185 Error error; 1186 1187 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be 1188 // listening for these signals over a signalfd file descriptors. This allows us to wait for 1189 // multiple kinds of events with select. 1190 sigset_t signals; 1191 sigemptyset(&signals); 1192 sigaddset(&signals, SIGCHLD); 1193 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC); 1194 if (m_signal_fd < 0) 1195 { 1196 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s", 1197 __FUNCTION__, strerror(errno)); 1198 1199 } 1200 1201 if (pipe2(m_pipefd, O_CLOEXEC) == -1) 1202 { 1203 error.SetErrorToErrno(); 1204 return error; 1205 } 1206 1207 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) { 1208 return error; 1209 } 1210 1211 static const char g_thread_name[] = "lldb.process.nativelinux.monitor"; 1212 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr); 1213 if (!m_thread.IsJoinable()) 1214 return Error("Failed to create monitor thread for NativeProcessLinux."); 1215 1216 // Wait for initial operation to complete. 1217 return WaitForAck(); 1218 } 1219 1220 void 1221 NativeProcessLinux::Monitor::DoOperation(Operation *op) 1222 { 1223 if (m_thread.EqualsThread(pthread_self())) { 1224 // If we're on the Monitor thread, we can simply execute the operation. 1225 op->Execute(m_native_process); 1226 return; 1227 } 1228 1229 // Otherwise we need to pass the operation to the Monitor thread so it can handle it. 1230 Mutex::Locker lock(m_operation_mutex); 1231 1232 m_operation = op; 1233 1234 // notify the thread that an operation is ready to be processed 1235 write(m_pipefd[WRITE], &operation_command, sizeof operation_command); 1236 1237 WaitForAck(); 1238 } 1239 1240 void 1241 NativeProcessLinux::Monitor::Terminate() 1242 { 1243 if (m_pipefd[WRITE] >= 0) 1244 { 1245 close(m_pipefd[WRITE]); 1246 m_pipefd[WRITE] = -1; 1247 } 1248 if (m_thread.IsJoinable()) 1249 m_thread.Join(nullptr); 1250 } 1251 1252 NativeProcessLinux::Monitor::~Monitor() 1253 { 1254 Terminate(); 1255 if (m_pipefd[READ] >= 0) 1256 close(m_pipefd[READ]); 1257 if (m_signal_fd >= 0) 1258 close(m_signal_fd); 1259 sem_destroy(&m_operation_sem); 1260 } 1261 1262 void 1263 NativeProcessLinux::Monitor::HandleSignals() 1264 { 1265 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1266 1267 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get 1268 // all the information from waitpid(). We just need to read all the signals so that we can 1269 // sleep next time we reach select(). 1270 while (true) 1271 { 1272 signalfd_siginfo info; 1273 ssize_t size = read(m_signal_fd, &info, sizeof info); 1274 if (size == -1) 1275 { 1276 if (errno == EAGAIN || errno == EWOULDBLOCK) 1277 break; // We are done. 1278 if (errno == EINTR) 1279 continue; 1280 if (log) 1281 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s", 1282 __FUNCTION__, strerror(errno)); 1283 break; 1284 } 1285 if (size != sizeof info) 1286 { 1287 // We got incomplete information structure. This should not happen, let's just log 1288 // that. 1289 if (log) 1290 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: " 1291 "structure size is %zd, read returned %zd bytes", 1292 __FUNCTION__, sizeof info, size); 1293 break; 1294 } 1295 if (log) 1296 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__, 1297 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo); 1298 } 1299 } 1300 1301 void 1302 NativeProcessLinux::Monitor::HandleWait() 1303 { 1304 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1305 // Process all pending waitpid notifications. 1306 while (true) 1307 { 1308 int status = -1; 1309 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG); 1310 1311 if (wait_pid == 0) 1312 break; // We are done. 1313 1314 if (wait_pid == -1) 1315 { 1316 if (errno == EINTR) 1317 continue; 1318 1319 if (log) 1320 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s", 1321 __FUNCTION__, m_child_pid, strerror(errno)); 1322 break; 1323 } 1324 1325 bool exited = false; 1326 int signal = 0; 1327 int exit_status = 0; 1328 const char *status_cstr = NULL; 1329 if (WIFSTOPPED(status)) 1330 { 1331 signal = WSTOPSIG(status); 1332 status_cstr = "STOPPED"; 1333 } 1334 else if (WIFEXITED(status)) 1335 { 1336 exit_status = WEXITSTATUS(status); 1337 status_cstr = "EXITED"; 1338 exited = true; 1339 } 1340 else if (WIFSIGNALED(status)) 1341 { 1342 signal = WTERMSIG(status); 1343 status_cstr = "SIGNALED"; 1344 if (wait_pid == abs(m_child_pid)) { 1345 exited = true; 1346 exit_status = -1; 1347 } 1348 } 1349 else 1350 status_cstr = "(\?\?\?)"; 1351 1352 if (log) 1353 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)" 1354 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i", 1355 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status); 1356 1357 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status); 1358 } 1359 } 1360 1361 bool 1362 NativeProcessLinux::Monitor::HandleCommands() 1363 { 1364 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1365 1366 while (true) 1367 { 1368 char command = 0; 1369 ssize_t size = read(m_pipefd[READ], &command, sizeof command); 1370 if (size == -1) 1371 { 1372 if (errno == EAGAIN || errno == EWOULDBLOCK) 1373 return false; 1374 if (errno == EINTR) 1375 continue; 1376 if (log) 1377 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno)); 1378 return true; 1379 } 1380 if (size == 0) // end of file - write end closed 1381 { 1382 if (log) 1383 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__); 1384 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected"); 1385 return true; // We are done. 1386 } 1387 1388 switch (command) 1389 { 1390 case operation_command: 1391 m_operation->Execute(m_native_process); 1392 break; 1393 case begin_block_command: 1394 ++m_operation_nesting_level; 1395 break; 1396 case end_block_command: 1397 assert(m_operation_nesting_level > 0); 1398 --m_operation_nesting_level; 1399 break; 1400 default: 1401 if (log) 1402 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'", 1403 __FUNCTION__, command); 1404 } 1405 1406 // notify calling thread that the command has been processed 1407 sem_post(&m_operation_sem); 1408 } 1409 } 1410 1411 void 1412 NativeProcessLinux::Monitor::MainLoop() 1413 { 1414 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error); 1415 m_initial_operation_up.reset(); 1416 m_child_pid = -getpgid(child_pid), 1417 sem_post(&m_operation_sem); 1418 1419 while (true) 1420 { 1421 fd_set fds; 1422 FD_ZERO(&fds); 1423 // Only process waitpid events if we are outside of an operation block. Any pending 1424 // events will be processed after we leave the block. 1425 if (m_operation_nesting_level == 0) 1426 FD_SET(m_signal_fd, &fds); 1427 FD_SET(m_pipefd[READ], &fds); 1428 1429 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1; 1430 int r = select(max_fd, &fds, nullptr, nullptr, nullptr); 1431 if (r < 0) 1432 { 1433 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1434 if (log) 1435 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s", 1436 __FUNCTION__, strerror(errno)); 1437 return; 1438 } 1439 1440 if (FD_ISSET(m_pipefd[READ], &fds)) 1441 { 1442 if (HandleCommands()) 1443 return; 1444 } 1445 1446 if (FD_ISSET(m_signal_fd, &fds)) 1447 { 1448 HandleSignals(); 1449 HandleWait(); 1450 } 1451 } 1452 } 1453 1454 Error 1455 NativeProcessLinux::Monitor::WaitForAck() 1456 { 1457 Error error; 1458 while (sem_wait(&m_operation_sem) != 0) 1459 { 1460 if (errno == EINTR) 1461 continue; 1462 1463 error.SetErrorToErrno(); 1464 return error; 1465 } 1466 1467 return m_operation_error; 1468 } 1469 1470 void * 1471 NativeProcessLinux::Monitor::RunMonitor(void *arg) 1472 { 1473 static_cast<Monitor *>(arg)->MainLoop(); 1474 return nullptr; 1475 } 1476 1477 1478 NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module, 1479 char const **argv, 1480 char const **envp, 1481 const std::string &stdin_path, 1482 const std::string &stdout_path, 1483 const std::string &stderr_path, 1484 const char *working_dir, 1485 const ProcessLaunchInfo &launch_info) 1486 : m_module(module), 1487 m_argv(argv), 1488 m_envp(envp), 1489 m_stdin_path(stdin_path), 1490 m_stdout_path(stdout_path), 1491 m_stderr_path(stderr_path), 1492 m_working_dir(working_dir), 1493 m_launch_info(launch_info) 1494 { 1495 } 1496 1497 NativeProcessLinux::LaunchArgs::~LaunchArgs() 1498 { } 1499 1500 // ----------------------------------------------------------------------------- 1501 // Public Static Methods 1502 // ----------------------------------------------------------------------------- 1503 1504 Error 1505 NativeProcessLinux::LaunchProcess ( 1506 Module *exe_module, 1507 ProcessLaunchInfo &launch_info, 1508 NativeProcessProtocol::NativeDelegate &native_delegate, 1509 NativeProcessProtocolSP &native_process_sp) 1510 { 1511 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1512 1513 Error error; 1514 1515 // Verify the working directory is valid if one was specified. 1516 const char* working_dir = launch_info.GetWorkingDirectory (); 1517 if (working_dir) 1518 { 1519 FileSpec working_dir_fs (working_dir, true); 1520 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory) 1521 { 1522 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir); 1523 return error; 1524 } 1525 } 1526 1527 const FileAction *file_action; 1528 1529 // Default of NULL will mean to use existing open file descriptors. 1530 std::string stdin_path; 1531 std::string stdout_path; 1532 std::string stderr_path; 1533 1534 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 1535 if (file_action) 1536 stdin_path = file_action->GetPath (); 1537 1538 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 1539 if (file_action) 1540 stdout_path = file_action->GetPath (); 1541 1542 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 1543 if (file_action) 1544 stderr_path = file_action->GetPath (); 1545 1546 if (log) 1547 { 1548 if (!stdin_path.empty ()) 1549 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ()); 1550 else 1551 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__); 1552 1553 if (!stdout_path.empty ()) 1554 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ()); 1555 else 1556 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__); 1557 1558 if (!stderr_path.empty ()) 1559 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ()); 1560 else 1561 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__); 1562 } 1563 1564 // Create the NativeProcessLinux in launch mode. 1565 native_process_sp.reset (new NativeProcessLinux ()); 1566 1567 if (log) 1568 { 1569 int i = 0; 1570 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i) 1571 { 1572 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr"); 1573 ++i; 1574 } 1575 } 1576 1577 if (!native_process_sp->RegisterNativeDelegate (native_delegate)) 1578 { 1579 native_process_sp.reset (); 1580 error.SetErrorStringWithFormat ("failed to register the native delegate"); 1581 return error; 1582 } 1583 1584 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior ( 1585 exe_module, 1586 launch_info.GetArguments ().GetConstArgumentVector (), 1587 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (), 1588 stdin_path, 1589 stdout_path, 1590 stderr_path, 1591 working_dir, 1592 launch_info, 1593 error); 1594 1595 if (error.Fail ()) 1596 { 1597 native_process_sp.reset (); 1598 if (log) 1599 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ()); 1600 return error; 1601 } 1602 1603 launch_info.SetProcessID (native_process_sp->GetID ()); 1604 1605 return error; 1606 } 1607 1608 Error 1609 NativeProcessLinux::AttachToProcess ( 1610 lldb::pid_t pid, 1611 NativeProcessProtocol::NativeDelegate &native_delegate, 1612 NativeProcessProtocolSP &native_process_sp) 1613 { 1614 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1615 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE)) 1616 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid); 1617 1618 // Grab the current platform architecture. This should be Linux, 1619 // since this code is only intended to run on a Linux host. 1620 PlatformSP platform_sp (Platform::GetHostPlatform ()); 1621 if (!platform_sp) 1622 return Error("failed to get a valid default platform"); 1623 1624 // Retrieve the architecture for the running process. 1625 ArchSpec process_arch; 1626 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch); 1627 if (!error.Success ()) 1628 return error; 1629 1630 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ()); 1631 1632 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate)) 1633 { 1634 error.SetErrorStringWithFormat ("failed to register the native delegate"); 1635 return error; 1636 } 1637 1638 native_process_linux_sp->AttachToInferior (pid, error); 1639 if (!error.Success ()) 1640 return error; 1641 1642 native_process_sp = native_process_linux_sp; 1643 return error; 1644 } 1645 1646 // ----------------------------------------------------------------------------- 1647 // Public Instance Methods 1648 // ----------------------------------------------------------------------------- 1649 1650 NativeProcessLinux::NativeProcessLinux () : 1651 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID), 1652 m_arch (), 1653 m_supports_mem_region (eLazyBoolCalculate), 1654 m_mem_region_cache (), 1655 m_mem_region_cache_mutex (), 1656 m_tid_map () 1657 { 1658 } 1659 1660 //------------------------------------------------------------------------------ 1661 // NativeProcessLinux spawns a new thread which performs all operations on the inferior process. 1662 // Refer to Monitor and Operation classes to see why this is necessary. 1663 //------------------------------------------------------------------------------ 1664 void 1665 NativeProcessLinux::LaunchInferior ( 1666 Module *module, 1667 const char *argv[], 1668 const char *envp[], 1669 const std::string &stdin_path, 1670 const std::string &stdout_path, 1671 const std::string &stderr_path, 1672 const char *working_dir, 1673 const ProcessLaunchInfo &launch_info, 1674 Error &error) 1675 { 1676 if (module) 1677 m_arch = module->GetArchitecture (); 1678 1679 SetState (eStateLaunching); 1680 1681 std::unique_ptr<LaunchArgs> args( 1682 new LaunchArgs( 1683 module, argv, envp, 1684 stdin_path, stdout_path, stderr_path, 1685 working_dir, launch_info)); 1686 1687 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error); 1688 if (!error.Success ()) 1689 return; 1690 } 1691 1692 void 1693 NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error) 1694 { 1695 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1696 if (log) 1697 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid); 1698 1699 // We can use the Host for everything except the ResolveExecutable portion. 1700 PlatformSP platform_sp = Platform::GetHostPlatform (); 1701 if (!platform_sp) 1702 { 1703 if (log) 1704 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid); 1705 error.SetErrorString ("no default platform available"); 1706 return; 1707 } 1708 1709 // Gather info about the process. 1710 ProcessInstanceInfo process_info; 1711 if (!platform_sp->GetProcessInfo (pid, process_info)) 1712 { 1713 if (log) 1714 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid); 1715 error.SetErrorString ("failed to get process info"); 1716 return; 1717 } 1718 1719 // Resolve the executable module 1720 ModuleSP exe_module_sp; 1721 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths()); 1722 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture()); 1723 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp, 1724 executable_search_paths.GetSize() ? &executable_search_paths : NULL); 1725 if (!error.Success()) 1726 return; 1727 1728 // Set the architecture to the exe architecture. 1729 m_arch = exe_module_sp->GetArchitecture(); 1730 if (log) 1731 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ()); 1732 1733 m_pid = pid; 1734 SetState(eStateAttaching); 1735 1736 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error); 1737 if (!error.Success ()) 1738 return; 1739 } 1740 1741 void 1742 NativeProcessLinux::Terminate () 1743 { 1744 m_monitor_up->Terminate(); 1745 } 1746 1747 ::pid_t 1748 NativeProcessLinux::Launch(LaunchArgs *args, Error &error) 1749 { 1750 assert (args && "null args"); 1751 1752 const char **argv = args->m_argv; 1753 const char **envp = args->m_envp; 1754 const char *working_dir = args->m_working_dir; 1755 1756 lldb_utility::PseudoTerminal terminal; 1757 const size_t err_len = 1024; 1758 char err_str[err_len]; 1759 lldb::pid_t pid; 1760 NativeThreadProtocolSP thread_sp; 1761 1762 lldb::ThreadSP inferior; 1763 1764 // Propagate the environment if one is not supplied. 1765 if (envp == NULL || envp[0] == NULL) 1766 envp = const_cast<const char **>(environ); 1767 1768 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1)) 1769 { 1770 error.SetErrorToGenericError(); 1771 error.SetErrorStringWithFormat("Process fork failed: %s", err_str); 1772 return -1; 1773 } 1774 1775 // Recognized child exit status codes. 1776 enum { 1777 ePtraceFailed = 1, 1778 eDupStdinFailed, 1779 eDupStdoutFailed, 1780 eDupStderrFailed, 1781 eChdirFailed, 1782 eExecFailed, 1783 eSetGidFailed 1784 }; 1785 1786 // Child process. 1787 if (pid == 0) 1788 { 1789 // FIXME consider opening a pipe between parent/child and have this forked child 1790 // send log info to parent re: launch status, in place of the log lines removed here. 1791 1792 // Start tracing this child that is about to exec. 1793 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error); 1794 if (error.Fail()) 1795 exit(ePtraceFailed); 1796 1797 // terminal has already dupped the tty descriptors to stdin/out/err. 1798 // This closes original fd from which they were copied (and avoids 1799 // leaking descriptors to the debugged process. 1800 terminal.CloseSlaveFileDescriptor(); 1801 1802 // Do not inherit setgid powers. 1803 if (setgid(getgid()) != 0) 1804 exit(eSetGidFailed); 1805 1806 // Attempt to have our own process group. 1807 if (setpgid(0, 0) != 0) 1808 { 1809 // FIXME log that this failed. This is common. 1810 // Don't allow this to prevent an inferior exec. 1811 } 1812 1813 // Dup file descriptors if needed. 1814 if (!args->m_stdin_path.empty ()) 1815 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY)) 1816 exit(eDupStdinFailed); 1817 1818 if (!args->m_stdout_path.empty ()) 1819 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC)) 1820 exit(eDupStdoutFailed); 1821 1822 if (!args->m_stderr_path.empty ()) 1823 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC)) 1824 exit(eDupStderrFailed); 1825 1826 // Close everything besides stdin, stdout, and stderr that has no file 1827 // action to avoid leaking 1828 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd) 1829 if (!args->m_launch_info.GetFileActionForFD(fd)) 1830 close(fd); 1831 1832 // Change working directory 1833 if (working_dir != NULL && working_dir[0]) 1834 if (0 != ::chdir(working_dir)) 1835 exit(eChdirFailed); 1836 1837 // Disable ASLR if requested. 1838 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR)) 1839 { 1840 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS); 1841 if (old_personality == -1) 1842 { 1843 // Can't retrieve Linux personality. Cannot disable ASLR. 1844 } 1845 else 1846 { 1847 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality); 1848 if (new_personality == -1) 1849 { 1850 // Disabling ASLR failed. 1851 } 1852 else 1853 { 1854 // Disabling ASLR succeeded. 1855 } 1856 } 1857 } 1858 1859 // Execute. We should never return... 1860 execve(argv[0], 1861 const_cast<char *const *>(argv), 1862 const_cast<char *const *>(envp)); 1863 1864 // ...unless exec fails. In which case we definitely need to end the child here. 1865 exit(eExecFailed); 1866 } 1867 1868 // 1869 // This is the parent code here. 1870 // 1871 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1872 1873 // Wait for the child process to trap on its call to execve. 1874 ::pid_t wpid; 1875 int status; 1876 if ((wpid = waitpid(pid, &status, 0)) < 0) 1877 { 1878 error.SetErrorToErrno(); 1879 if (log) 1880 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", 1881 __FUNCTION__, error.AsCString ()); 1882 1883 // Mark the inferior as invalid. 1884 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1885 SetState (StateType::eStateInvalid); 1886 1887 return -1; 1888 } 1889 else if (WIFEXITED(status)) 1890 { 1891 // open, dup or execve likely failed for some reason. 1892 error.SetErrorToGenericError(); 1893 switch (WEXITSTATUS(status)) 1894 { 1895 case ePtraceFailed: 1896 error.SetErrorString("Child ptrace failed."); 1897 break; 1898 case eDupStdinFailed: 1899 error.SetErrorString("Child open stdin failed."); 1900 break; 1901 case eDupStdoutFailed: 1902 error.SetErrorString("Child open stdout failed."); 1903 break; 1904 case eDupStderrFailed: 1905 error.SetErrorString("Child open stderr failed."); 1906 break; 1907 case eChdirFailed: 1908 error.SetErrorString("Child failed to set working directory."); 1909 break; 1910 case eExecFailed: 1911 error.SetErrorString("Child exec failed."); 1912 break; 1913 case eSetGidFailed: 1914 error.SetErrorString("Child setgid failed."); 1915 break; 1916 default: 1917 error.SetErrorString("Child returned unknown exit status."); 1918 break; 1919 } 1920 1921 if (log) 1922 { 1923 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP", 1924 __FUNCTION__, 1925 WEXITSTATUS(status)); 1926 } 1927 1928 // Mark the inferior as invalid. 1929 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1930 SetState (StateType::eStateInvalid); 1931 1932 return -1; 1933 } 1934 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) && 1935 "Could not sync with inferior process."); 1936 1937 if (log) 1938 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__); 1939 1940 error = SetDefaultPtraceOpts(pid); 1941 if (error.Fail()) 1942 { 1943 if (log) 1944 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s", 1945 __FUNCTION__, error.AsCString ()); 1946 1947 // Mark the inferior as invalid. 1948 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1949 SetState (StateType::eStateInvalid); 1950 1951 return -1; 1952 } 1953 1954 // Release the master terminal descriptor and pass it off to the 1955 // NativeProcessLinux instance. Similarly stash the inferior pid. 1956 m_terminal_fd = terminal.ReleaseMasterFileDescriptor(); 1957 m_pid = pid; 1958 1959 // Set the terminal fd to be in non blocking mode (it simplifies the 1960 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking 1961 // descriptor to read from). 1962 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 1963 if (error.Fail()) 1964 { 1965 if (log) 1966 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s", 1967 __FUNCTION__, error.AsCString ()); 1968 1969 // Mark the inferior as invalid. 1970 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1971 SetState (StateType::eStateInvalid); 1972 1973 return -1; 1974 } 1975 1976 if (log) 1977 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid); 1978 1979 thread_sp = AddThread (pid); 1980 assert (thread_sp && "AddThread() returned a nullptr thread"); 1981 NotifyThreadCreateStopped (pid); 1982 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP); 1983 1984 // Let our process instance know the thread has stopped. 1985 SetCurrentThreadID (thread_sp->GetID ()); 1986 SetState (StateType::eStateStopped); 1987 1988 if (log) 1989 { 1990 if (error.Success ()) 1991 { 1992 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__); 1993 } 1994 else 1995 { 1996 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s", 1997 __FUNCTION__, error.AsCString ()); 1998 return -1; 1999 } 2000 } 2001 return pid; 2002 } 2003 2004 ::pid_t 2005 NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) 2006 { 2007 lldb::ThreadSP inferior; 2008 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2009 2010 // Use a map to keep track of the threads which we have attached/need to attach. 2011 Host::TidMap tids_to_attach; 2012 if (pid <= 1) 2013 { 2014 error.SetErrorToGenericError(); 2015 error.SetErrorString("Attaching to process 1 is not allowed."); 2016 return -1; 2017 } 2018 2019 while (Host::FindProcessThreads(pid, tids_to_attach)) 2020 { 2021 for (Host::TidMap::iterator it = tids_to_attach.begin(); 2022 it != tids_to_attach.end();) 2023 { 2024 if (it->second == false) 2025 { 2026 lldb::tid_t tid = it->first; 2027 2028 // Attach to the requested process. 2029 // An attach will cause the thread to stop with a SIGSTOP. 2030 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error); 2031 if (error.Fail()) 2032 { 2033 // No such thread. The thread may have exited. 2034 // More error handling may be needed. 2035 if (error.GetError() == ESRCH) 2036 { 2037 it = tids_to_attach.erase(it); 2038 continue; 2039 } 2040 else 2041 return -1; 2042 } 2043 2044 int status; 2045 // Need to use __WALL otherwise we receive an error with errno=ECHLD 2046 // At this point we should have a thread stopped if waitpid succeeds. 2047 if ((status = waitpid(tid, NULL, __WALL)) < 0) 2048 { 2049 // No such thread. The thread may have exited. 2050 // More error handling may be needed. 2051 if (errno == ESRCH) 2052 { 2053 it = tids_to_attach.erase(it); 2054 continue; 2055 } 2056 else 2057 { 2058 error.SetErrorToErrno(); 2059 return -1; 2060 } 2061 } 2062 2063 error = SetDefaultPtraceOpts(tid); 2064 if (error.Fail()) 2065 return -1; 2066 2067 if (log) 2068 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid); 2069 2070 it->second = true; 2071 2072 // Create the thread, mark it as stopped. 2073 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid))); 2074 assert (thread_sp && "AddThread() returned a nullptr"); 2075 2076 // This will notify this is a new thread and tell the system it is stopped. 2077 NotifyThreadCreateStopped (tid); 2078 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP); 2079 SetCurrentThreadID (thread_sp->GetID ()); 2080 } 2081 2082 // move the loop forward 2083 ++it; 2084 } 2085 } 2086 2087 if (tids_to_attach.size() > 0) 2088 { 2089 m_pid = pid; 2090 // Let our process instance know the thread has stopped. 2091 SetState (StateType::eStateStopped); 2092 } 2093 else 2094 { 2095 error.SetErrorToGenericError(); 2096 error.SetErrorString("No such process."); 2097 return -1; 2098 } 2099 2100 return pid; 2101 } 2102 2103 Error 2104 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) 2105 { 2106 long ptrace_opts = 0; 2107 2108 // Have the child raise an event on exit. This is used to keep the child in 2109 // limbo until it is destroyed. 2110 ptrace_opts |= PTRACE_O_TRACEEXIT; 2111 2112 // Have the tracer trace threads which spawn in the inferior process. 2113 // TODO: if we want to support tracing the inferiors' child, add the 2114 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 2115 ptrace_opts |= PTRACE_O_TRACECLONE; 2116 2117 // Have the tracer notify us before execve returns 2118 // (needed to disable legacy SIGTRAP generation) 2119 ptrace_opts |= PTRACE_O_TRACEEXEC; 2120 2121 Error error; 2122 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error); 2123 return error; 2124 } 2125 2126 static ExitType convert_pid_status_to_exit_type (int status) 2127 { 2128 if (WIFEXITED (status)) 2129 return ExitType::eExitTypeExit; 2130 else if (WIFSIGNALED (status)) 2131 return ExitType::eExitTypeSignal; 2132 else if (WIFSTOPPED (status)) 2133 return ExitType::eExitTypeStop; 2134 else 2135 { 2136 // We don't know what this is. 2137 return ExitType::eExitTypeInvalid; 2138 } 2139 } 2140 2141 static int convert_pid_status_to_return_code (int status) 2142 { 2143 if (WIFEXITED (status)) 2144 return WEXITSTATUS (status); 2145 else if (WIFSIGNALED (status)) 2146 return WTERMSIG (status); 2147 else if (WIFSTOPPED (status)) 2148 return WSTOPSIG (status); 2149 else 2150 { 2151 // We don't know what this is. 2152 return ExitType::eExitTypeInvalid; 2153 } 2154 } 2155 2156 // Handles all waitpid events from the inferior process. 2157 void 2158 NativeProcessLinux::MonitorCallback(lldb::pid_t pid, 2159 bool exited, 2160 int signal, 2161 int status) 2162 { 2163 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 2164 2165 // Certain activities differ based on whether the pid is the tid of the main thread. 2166 const bool is_main_thread = (pid == GetID ()); 2167 2168 // Handle when the thread exits. 2169 if (exited) 2170 { 2171 if (log) 2172 log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not"); 2173 2174 // This is a thread that exited. Ensure we're not tracking it anymore. 2175 const bool thread_found = StopTrackingThread (pid); 2176 2177 // Make sure the thread state coordinator knows about this. 2178 NotifyThreadDeath (pid); 2179 2180 if (is_main_thread) 2181 { 2182 // We only set the exit status and notify the delegate if we haven't already set the process 2183 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8) 2184 // for the main thread. 2185 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed); 2186 if (!already_notified) 2187 { 2188 if (log) 2189 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling main thread exit (%s), expected exit state already set but state was %s instead, setting exit state now", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found", StateAsCString (GetState ())); 2190 // The main thread exited. We're done monitoring. Report to delegate. 2191 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true); 2192 2193 // Notify delegate that our process has exited. 2194 SetState (StateType::eStateExited, true); 2195 } 2196 else 2197 { 2198 if (log) 2199 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found"); 2200 } 2201 } 2202 else 2203 { 2204 // Do we want to report to the delegate in this case? I think not. If this was an orderly 2205 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, 2206 // and we would have done an all-stop then. 2207 if (log) 2208 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found"); 2209 } 2210 return; 2211 } 2212 2213 // Get details on the signal raised. 2214 siginfo_t info; 2215 const auto err = GetSignalInfo(pid, &info); 2216 if (err.Success()) 2217 { 2218 // We have retrieved the signal info. Dispatch appropriately. 2219 if (info.si_signo == SIGTRAP) 2220 MonitorSIGTRAP(&info, pid); 2221 else 2222 MonitorSignal(&info, pid, exited); 2223 } 2224 else 2225 { 2226 if (err.GetError() == EINVAL) 2227 { 2228 // This is a group stop reception for this tid. 2229 if (log) 2230 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid); 2231 NotifyThreadStop (pid, false); 2232 } 2233 else 2234 { 2235 // ptrace(GETSIGINFO) failed (but not due to group-stop). 2236 2237 // A return value of ESRCH means the thread/process is no longer on the system, 2238 // so it was killed somehow outside of our control. Either way, we can't do anything 2239 // with it anymore. 2240 2241 // Stop tracking the metadata for the thread since it's entirely off the system now. 2242 const bool thread_found = StopTrackingThread (pid); 2243 2244 // Make sure the thread state coordinator knows about this. 2245 NotifyThreadDeath (pid); 2246 2247 if (log) 2248 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)", 2249 __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"); 2250 2251 if (is_main_thread) 2252 { 2253 // Notify the delegate - our process is not available but appears to have been killed outside 2254 // our control. Is eStateExited the right exit state in this case? 2255 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true); 2256 SetState (StateType::eStateExited, true); 2257 } 2258 else 2259 { 2260 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop? 2261 if (log) 2262 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " non-main thread exit occurred, didn't tell delegate anything since thread disappeared out from underneath us", __FUNCTION__, GetID (), pid); 2263 } 2264 } 2265 } 2266 } 2267 2268 void 2269 NativeProcessLinux::WaitForNewThread(::pid_t tid) 2270 { 2271 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2272 2273 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid); 2274 2275 if (new_thread_sp) 2276 { 2277 // We are already tracking the thread - we got the event on the new thread (see 2278 // MonitorSignal) before this one. We are done. 2279 return; 2280 } 2281 2282 // The thread is not tracked yet, let's wait for it to appear. 2283 int status = -1; 2284 ::pid_t wait_pid; 2285 do 2286 { 2287 if (log) 2288 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid); 2289 wait_pid = waitpid(tid, &status, __WALL); 2290 } 2291 while (wait_pid == -1 && errno == EINTR); 2292 // Since we are waiting on a specific tid, this must be the creation event. But let's do 2293 // some checks just in case. 2294 if (wait_pid != tid) { 2295 if (log) 2296 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid); 2297 // The only way I know of this could happen is if the whole process was 2298 // SIGKILLed in the mean time. In any case, we can't do anything about that now. 2299 return; 2300 } 2301 if (WIFEXITED(status)) 2302 { 2303 if (log) 2304 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid); 2305 // Also a very improbable event. 2306 return; 2307 } 2308 2309 siginfo_t info; 2310 Error error = GetSignalInfo(tid, &info); 2311 if (error.Fail()) 2312 { 2313 if (log) 2314 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid); 2315 return; 2316 } 2317 2318 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) 2319 { 2320 // We should be getting a thread creation signal here, but we received something 2321 // else. There isn't much we can do about it now, so we will just log that. Since the 2322 // thread is alive and we are receiving events from it, we shall pretend that it was 2323 // created properly. 2324 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid); 2325 } 2326 2327 if (log) 2328 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32, 2329 __FUNCTION__, GetID (), tid); 2330 2331 new_thread_sp = AddThread(tid); 2332 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning (); 2333 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER); 2334 NotifyThreadCreate (tid, false); 2335 } 2336 2337 void 2338 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid) 2339 { 2340 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2341 const bool is_main_thread = (pid == GetID ()); 2342 2343 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!"); 2344 if (!info) 2345 return; 2346 2347 Mutex::Locker locker (m_threads_mutex); 2348 2349 // See if we can find a thread for this signal. 2350 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2351 if (!thread_sp) 2352 { 2353 if (log) 2354 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2355 } 2356 2357 switch (info->si_code) 2358 { 2359 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor. 2360 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)): 2361 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 2362 2363 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): 2364 { 2365 // This is the notification on the parent thread which informs us of new thread 2366 // creation. 2367 // We don't want to do anything with the parent thread so we just resume it. In case we 2368 // want to implement "break on thread creation" functionality, we would need to stop 2369 // here. 2370 2371 unsigned long event_message = 0; 2372 if (GetEventMessage (pid, &event_message).Fail()) 2373 { 2374 if (log) 2375 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid); 2376 } else 2377 WaitForNewThread(event_message); 2378 2379 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2380 break; 2381 } 2382 2383 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): 2384 { 2385 NativeThreadProtocolSP main_thread_sp; 2386 if (log) 2387 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP); 2388 2389 // The thread state coordinator needs to reset due to the exec. 2390 ResetForExec (); 2391 2392 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state. 2393 if (log) 2394 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__); 2395 2396 for (auto thread_sp : m_threads) 2397 { 2398 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID (); 2399 if (is_main_thread) 2400 { 2401 main_thread_sp = thread_sp; 2402 if (log) 2403 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ()); 2404 } 2405 else 2406 { 2407 // Tell thread coordinator this thread is dead. 2408 if (log) 2409 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ()); 2410 } 2411 } 2412 2413 m_threads.clear (); 2414 2415 if (main_thread_sp) 2416 { 2417 m_threads.push_back (main_thread_sp); 2418 SetCurrentThreadID (main_thread_sp->GetID ()); 2419 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec (); 2420 } 2421 else 2422 { 2423 SetCurrentThreadID (LLDB_INVALID_THREAD_ID); 2424 if (log) 2425 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ()); 2426 } 2427 2428 // Tell coordinator about about the "new" (since exec) stopped main thread. 2429 const lldb::tid_t main_thread_tid = GetID (); 2430 NotifyThreadCreateStopped (main_thread_tid); 2431 2432 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed. 2433 // Consider a handler that can execute when that happens. 2434 // Let our delegate know we have just exec'd. 2435 NotifyDidExec (); 2436 2437 // If we have a main thread, indicate we are stopped. 2438 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked"); 2439 2440 // Let the process know we're stopped. 2441 StopRunningThreads (pid); 2442 2443 break; 2444 } 2445 2446 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): 2447 { 2448 // The inferior process or one of its threads is about to exit. 2449 2450 // This thread is currently stopped. It's not actually dead yet, just about to be. 2451 NotifyThreadStop (pid, false); 2452 2453 unsigned long data = 0; 2454 if (GetEventMessage(pid, &data).Fail()) 2455 data = -1; 2456 2457 if (log) 2458 { 2459 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)", 2460 __FUNCTION__, 2461 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false", 2462 pid, 2463 is_main_thread ? "is main thread" : "not main thread"); 2464 } 2465 2466 if (is_main_thread) 2467 { 2468 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true); 2469 } 2470 2471 const int signo = static_cast<int> (data); 2472 RequestThreadResume (pid, 2473 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2474 { 2475 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2476 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo); 2477 }); 2478 2479 break; 2480 } 2481 2482 case 0: 2483 case TRAP_TRACE: // We receive this on single stepping. 2484 case TRAP_HWBKPT: // We receive this on watchpoint hit 2485 if (thread_sp) 2486 { 2487 // If a watchpoint was hit, report it 2488 uint32_t wp_index; 2489 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index); 2490 if (error.Fail() && log) 2491 log->Printf("NativeProcessLinux::%s() " 2492 "received error while checking for watchpoint hits, " 2493 "pid = %" PRIu64 " error = %s", 2494 __FUNCTION__, pid, error.AsCString()); 2495 if (wp_index != LLDB_INVALID_INDEX32) 2496 { 2497 MonitorWatchpoint(pid, thread_sp, wp_index); 2498 break; 2499 } 2500 } 2501 // Otherwise, report step over 2502 MonitorTrace(pid, thread_sp); 2503 break; 2504 2505 case SI_KERNEL: 2506 case TRAP_BRKPT: 2507 MonitorBreakpoint(pid, thread_sp); 2508 break; 2509 2510 case SIGTRAP: 2511 case (SIGTRAP | 0x80): 2512 if (log) 2513 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid); 2514 2515 // This thread is currently stopped. 2516 NotifyThreadStop (pid, false); 2517 if (thread_sp) 2518 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP); 2519 2520 2521 // Ignore these signals until we know more about them. 2522 RequestThreadResume (pid, 2523 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2524 { 2525 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2526 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER); 2527 }); 2528 break; 2529 2530 default: 2531 assert(false && "Unexpected SIGTRAP code!"); 2532 if (log) 2533 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))); 2534 break; 2535 2536 } 2537 } 2538 2539 void 2540 NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp) 2541 { 2542 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2543 if (log) 2544 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", 2545 __FUNCTION__, pid); 2546 2547 if (thread_sp) 2548 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace(); 2549 2550 // This thread is currently stopped. 2551 NotifyThreadStop(pid, false); 2552 2553 // Here we don't have to request the rest of the threads to stop or request a deferred stop. 2554 // This would have already happened at the time the Resume() with step operation was signaled. 2555 // At this point, we just need to say we stopped, and the deferred notifcation will fire off 2556 // once all running threads have checked in as stopped. 2557 SetCurrentThreadID(pid); 2558 // Tell the process we have a stop (from software breakpoint). 2559 StopRunningThreads(pid); 2560 } 2561 2562 void 2563 NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp) 2564 { 2565 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 2566 if (log) 2567 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, 2568 __FUNCTION__, pid); 2569 2570 // This thread is currently stopped. 2571 NotifyThreadStop(pid, false); 2572 2573 // Mark the thread as stopped at breakpoint. 2574 if (thread_sp) 2575 { 2576 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint(); 2577 Error error = FixupBreakpointPCAsNeeded(thread_sp); 2578 if (error.Fail()) 2579 if (log) 2580 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", 2581 __FUNCTION__, pid, error.AsCString()); 2582 2583 auto it = m_threads_stepping_with_breakpoint.find(pid); 2584 if (it != m_threads_stepping_with_breakpoint.end()) 2585 { 2586 Error error = RemoveBreakpoint (it->second); 2587 if (error.Fail()) 2588 if (log) 2589 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s", 2590 __FUNCTION__, pid, error.AsCString()); 2591 2592 m_threads_stepping_with_breakpoint.erase(it); 2593 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace(); 2594 } 2595 } 2596 else 2597 if (log) 2598 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": " 2599 "warning, cannot process software breakpoint since no thread metadata", 2600 __FUNCTION__, pid); 2601 2602 2603 // We need to tell all other running threads before we notify the delegate about this stop. 2604 StopRunningThreads(pid); 2605 } 2606 2607 void 2608 NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index) 2609 { 2610 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 2611 if (log) 2612 log->Printf("NativeProcessLinux::%s() received watchpoint event, " 2613 "pid = %" PRIu64 ", wp_index = %" PRIu32, 2614 __FUNCTION__, pid, wp_index); 2615 2616 // This thread is currently stopped. 2617 NotifyThreadStop(pid, false); 2618 2619 // Mark the thread as stopped at watchpoint. 2620 // The address is at (lldb::addr_t)info->si_addr if we need it. 2621 lldbassert(thread_sp && "thread_sp cannot be NULL"); 2622 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index); 2623 2624 // We need to tell all other running threads before we notify the delegate about this stop. 2625 StopRunningThreads(pid); 2626 } 2627 2628 void 2629 NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited) 2630 { 2631 assert (info && "null info"); 2632 if (!info) 2633 return; 2634 2635 const int signo = info->si_signo; 2636 const bool is_from_llgs = info->si_pid == getpid (); 2637 2638 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2639 2640 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 2641 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a 2642 // kill(2) or raise(3). Similarly for tgkill(2) on Linux. 2643 // 2644 // IOW, user generated signals never generate what we consider to be a 2645 // "crash". 2646 // 2647 // Similarly, ACK signals generated by this monitor. 2648 2649 Mutex::Locker locker (m_threads_mutex); 2650 2651 // See if we can find a thread for this signal. 2652 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2653 if (!thread_sp) 2654 { 2655 if (log) 2656 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2657 } 2658 2659 // Handle the signal. 2660 if (info->si_code == SI_TKILL || info->si_code == SI_USER) 2661 { 2662 if (log) 2663 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")", 2664 __FUNCTION__, 2665 GetUnixSignals ().GetSignalAsCString (signo), 2666 signo, 2667 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"), 2668 info->si_pid, 2669 is_from_llgs ? "from llgs" : "not from llgs", 2670 pid); 2671 } 2672 2673 // Check for new thread notification. 2674 if ((info->si_pid == 0) && (info->si_code == SI_USER)) 2675 { 2676 // A new thread creation is being signaled. This is one of two parts that come in 2677 // a non-deterministic order. This code handles the case where the new thread event comes 2678 // before the event on the parent thread. For the opposite case see code in 2679 // MonitorSIGTRAP. 2680 if (log) 2681 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification", 2682 __FUNCTION__, GetID (), pid); 2683 2684 thread_sp = AddThread(pid); 2685 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread"); 2686 // We can now resume the newly created thread. 2687 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2688 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2689 NotifyThreadCreate (pid, false); 2690 // Done handling. 2691 return; 2692 } 2693 2694 // Check for thread stop notification. 2695 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP)) 2696 { 2697 // This is a tgkill()-based stop. 2698 if (thread_sp) 2699 { 2700 if (log) 2701 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped", 2702 __FUNCTION__, 2703 GetID (), 2704 pid); 2705 2706 // Check that we're not already marked with a stop reason. 2707 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that 2708 // the kernel signaled us with the thread stopping which we handled and marked as stopped, 2709 // and that, without an intervening resume, we received another stop. It is more likely 2710 // that we are missing the marking of a run state somewhere if we find that the thread was 2711 // marked as stopped. 2712 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp); 2713 assert (linux_thread_sp && "linux_thread_sp is null!"); 2714 2715 const StateType thread_state = linux_thread_sp->GetState (); 2716 if (!StateIsStoppedState (thread_state, false)) 2717 { 2718 // An inferior thread has stopped because of a SIGSTOP we have sent it. 2719 // Generally, these are not important stops and we don't want to report them as 2720 // they are just used to stop other threads when one thread (the one with the 2721 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the 2722 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we 2723 // leave the signal intact if this is the thread that was chosen as the 2724 // triggering thread. 2725 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid) 2726 linux_thread_sp->SetStoppedBySignal(SIGSTOP); 2727 else 2728 linux_thread_sp->SetStoppedBySignal(0); 2729 2730 SetCurrentThreadID (thread_sp->GetID ()); 2731 NotifyThreadStop (thread_sp->GetID (), true); 2732 } 2733 else 2734 { 2735 if (log) 2736 { 2737 // Retrieve the signal name if the thread was stopped by a signal. 2738 int stop_signo = 0; 2739 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo); 2740 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>"; 2741 if (!signal_name) 2742 signal_name = "<no-signal-name>"; 2743 2744 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", 2745 __FUNCTION__, 2746 GetID (), 2747 linux_thread_sp->GetID (), 2748 StateAsCString (thread_state), 2749 stop_signo, 2750 signal_name); 2751 } 2752 // Tell the thread state coordinator about the stop. 2753 NotifyThreadStop (thread_sp->GetID (), false); 2754 } 2755 } 2756 2757 // Done handling. 2758 return; 2759 } 2760 2761 if (log) 2762 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo)); 2763 2764 // This thread is stopped. 2765 NotifyThreadStop (pid, false); 2766 2767 switch (signo) 2768 { 2769 case SIGSTOP: 2770 { 2771 if (log) 2772 { 2773 if (is_from_llgs) 2774 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid); 2775 else 2776 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid); 2777 } 2778 2779 // Resume this thread to get the group-stop mechanism to fire off the true group stops. 2780 // This thread will get stopped again as part of the group-stop completion. 2781 RequestThreadResume (pid, 2782 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2783 { 2784 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2785 // Pass this signal number on to the inferior to handle. 2786 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo); 2787 }); 2788 } 2789 break; 2790 case SIGSEGV: 2791 case SIGILL: 2792 case SIGFPE: 2793 case SIGBUS: 2794 if (thread_sp) 2795 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info); 2796 break; 2797 default: 2798 // This is just a pre-signal-delivery notification of the incoming signal. 2799 if (thread_sp) 2800 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo); 2801 2802 break; 2803 } 2804 2805 // Send a stop to the debugger after we get all other threads to stop. 2806 StopRunningThreads (pid); 2807 } 2808 2809 namespace { 2810 2811 struct EmulatorBaton 2812 { 2813 NativeProcessLinux* m_process; 2814 NativeRegisterContext* m_reg_context; 2815 2816 // eRegisterKindDWARF -> RegsiterValue 2817 std::unordered_map<uint32_t, RegisterValue> m_register_values; 2818 2819 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) : 2820 m_process(process), m_reg_context(reg_context) {} 2821 }; 2822 2823 } // anonymous namespace 2824 2825 static size_t 2826 ReadMemoryCallback (EmulateInstruction *instruction, 2827 void *baton, 2828 const EmulateInstruction::Context &context, 2829 lldb::addr_t addr, 2830 void *dst, 2831 size_t length) 2832 { 2833 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2834 2835 size_t bytes_read; 2836 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read); 2837 return bytes_read; 2838 } 2839 2840 static bool 2841 ReadRegisterCallback (EmulateInstruction *instruction, 2842 void *baton, 2843 const RegisterInfo *reg_info, 2844 RegisterValue ®_value) 2845 { 2846 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2847 2848 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]); 2849 if (it != emulator_baton->m_register_values.end()) 2850 { 2851 reg_value = it->second; 2852 return true; 2853 } 2854 2855 // The emulator only fill in the dwarf regsiter numbers (and in some case 2856 // the generic register numbers). Get the full register info from the 2857 // register context based on the dwarf register numbers. 2858 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo( 2859 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 2860 2861 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value); 2862 if (error.Success()) 2863 return true; 2864 2865 return false; 2866 } 2867 2868 static bool 2869 WriteRegisterCallback (EmulateInstruction *instruction, 2870 void *baton, 2871 const EmulateInstruction::Context &context, 2872 const RegisterInfo *reg_info, 2873 const RegisterValue ®_value) 2874 { 2875 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2876 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value; 2877 return true; 2878 } 2879 2880 static size_t 2881 WriteMemoryCallback (EmulateInstruction *instruction, 2882 void *baton, 2883 const EmulateInstruction::Context &context, 2884 lldb::addr_t addr, 2885 const void *dst, 2886 size_t length) 2887 { 2888 return length; 2889 } 2890 2891 static lldb::addr_t 2892 ReadFlags (NativeRegisterContext* regsiter_context) 2893 { 2894 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo( 2895 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2896 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS); 2897 } 2898 2899 Error 2900 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp) 2901 { 2902 Error error; 2903 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext(); 2904 2905 std::unique_ptr<EmulateInstruction> emulator_ap( 2906 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr)); 2907 2908 if (emulator_ap == nullptr) 2909 return Error("Instruction emulator not found!"); 2910 2911 EmulatorBaton baton(this, register_context_sp.get()); 2912 emulator_ap->SetBaton(&baton); 2913 emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 2914 emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 2915 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 2916 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 2917 2918 if (!emulator_ap->ReadInstruction()) 2919 return Error("Read instruction failed!"); 2920 2921 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 2922 2923 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 2924 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2925 2926 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 2927 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 2928 2929 lldb::addr_t next_pc; 2930 lldb::addr_t next_flags; 2931 if (emulation_result) 2932 { 2933 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated"); 2934 next_pc = pc_it->second.GetAsUInt64(); 2935 2936 if (flags_it != baton.m_register_values.end()) 2937 next_flags = flags_it->second.GetAsUInt64(); 2938 else 2939 next_flags = ReadFlags (register_context_sp.get()); 2940 } 2941 else if (pc_it == baton.m_register_values.end()) 2942 { 2943 // Emulate instruction failed and it haven't changed PC. Advance PC 2944 // with the size of the current opcode because the emulation of all 2945 // PC modifying instruction should be successful. The failure most 2946 // likely caused by a not supported instruction which don't modify PC. 2947 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize(); 2948 next_flags = ReadFlags (register_context_sp.get()); 2949 } 2950 else 2951 { 2952 // The instruction emulation failed after it modified the PC. It is an 2953 // unknown error where we can't continue because the next instruction is 2954 // modifying the PC but we don't know how. 2955 return Error ("Instruction emulation failed unexpectedly."); 2956 } 2957 2958 if (m_arch.GetMachine() == llvm::Triple::arm) 2959 { 2960 if (next_flags & 0x20) 2961 { 2962 // Thumb mode 2963 error = SetSoftwareBreakpoint(next_pc, 2); 2964 } 2965 else 2966 { 2967 // Arm mode 2968 error = SetSoftwareBreakpoint(next_pc, 4); 2969 } 2970 } 2971 else if (m_arch.GetMachine() == llvm::Triple::mips64 2972 || m_arch.GetMachine() == llvm::Triple::mips64el) 2973 error = SetSoftwareBreakpoint(next_pc, 4); 2974 else 2975 { 2976 // No size hint is given for the next breakpoint 2977 error = SetSoftwareBreakpoint(next_pc, 0); 2978 } 2979 2980 if (error.Fail()) 2981 return error; 2982 2983 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc}); 2984 2985 return Error(); 2986 } 2987 2988 bool 2989 NativeProcessLinux::SupportHardwareSingleStepping() const 2990 { 2991 if (m_arch.GetMachine() == llvm::Triple::arm 2992 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el) 2993 return false; 2994 return true; 2995 } 2996 2997 Error 2998 NativeProcessLinux::Resume (const ResumeActionList &resume_actions) 2999 { 3000 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3001 if (log) 3002 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ()); 3003 3004 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID; 3005 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID; 3006 int deferred_signo = 0; 3007 NativeThreadProtocolSP deferred_signal_thread_sp; 3008 bool stepping = false; 3009 bool software_single_step = !SupportHardwareSingleStepping(); 3010 3011 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3012 Mutex::Locker locker (m_threads_mutex); 3013 3014 if (software_single_step) 3015 { 3016 for (auto thread_sp : m_threads) 3017 { 3018 assert (thread_sp && "thread list should not contain NULL threads"); 3019 3020 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 3021 if (action == nullptr) 3022 continue; 3023 3024 if (action->state == eStateStepping) 3025 { 3026 Error error = SetupSoftwareSingleStepping(thread_sp); 3027 if (error.Fail()) 3028 return error; 3029 } 3030 } 3031 } 3032 3033 for (auto thread_sp : m_threads) 3034 { 3035 assert (thread_sp && "thread list should not contain NULL threads"); 3036 3037 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 3038 3039 if (action == nullptr) 3040 { 3041 if (log) 3042 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64, 3043 __FUNCTION__, GetID (), thread_sp->GetID ()); 3044 continue; 3045 } 3046 3047 if (log) 3048 { 3049 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64, 3050 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 3051 } 3052 3053 switch (action->state) 3054 { 3055 case eStateRunning: 3056 { 3057 // Run the thread, possibly feeding it the signal. 3058 const int signo = action->signal; 3059 RequestThreadResumeAsNeeded (thread_sp->GetID (), 3060 [=](lldb::tid_t tid_to_resume, bool supress_signal) 3061 { 3062 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 3063 // Pass this signal number on to the inferior to handle. 3064 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3065 if (resume_result.Success()) 3066 SetState(eStateRunning, true); 3067 return resume_result; 3068 }); 3069 break; 3070 } 3071 3072 case eStateStepping: 3073 { 3074 // Request the step. 3075 const int signo = action->signal; 3076 RequestThreadResume (thread_sp->GetID (), 3077 [=](lldb::tid_t tid_to_step, bool supress_signal) 3078 { 3079 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping (); 3080 3081 Error step_result; 3082 if (software_single_step) 3083 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3084 else 3085 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3086 3087 assert (step_result.Success() && "SingleStep() failed"); 3088 if (step_result.Success()) 3089 SetState(eStateStepping, true); 3090 return step_result; 3091 }); 3092 stepping = true; 3093 break; 3094 } 3095 3096 case eStateSuspended: 3097 case eStateStopped: 3098 // if we haven't chosen a deferred signal tid yet, use this one. 3099 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID) 3100 { 3101 deferred_signal_tid = thread_sp->GetID (); 3102 deferred_signal_thread_sp = thread_sp; 3103 deferred_signo = SIGSTOP; 3104 } 3105 break; 3106 3107 default: 3108 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64, 3109 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 3110 } 3111 } 3112 3113 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal 3114 // after all other running threads have stopped. 3115 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal. 3116 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping) 3117 StopRunningThreadsWithSkipTID(deferred_signal_tid, deferred_signal_skip_tid); 3118 3119 return Error(); 3120 } 3121 3122 Error 3123 NativeProcessLinux::Halt () 3124 { 3125 Error error; 3126 3127 if (kill (GetID (), SIGSTOP) != 0) 3128 error.SetErrorToErrno (); 3129 3130 return error; 3131 } 3132 3133 Error 3134 NativeProcessLinux::Detach () 3135 { 3136 Error error; 3137 3138 // Tell ptrace to detach from the process. 3139 if (GetID () != LLDB_INVALID_PROCESS_ID) 3140 error = Detach (GetID ()); 3141 3142 // Stop monitoring the inferior. 3143 m_monitor_up->Terminate(); 3144 3145 // No error. 3146 return error; 3147 } 3148 3149 Error 3150 NativeProcessLinux::Signal (int signo) 3151 { 3152 Error error; 3153 3154 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3155 if (log) 3156 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64, 3157 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ()); 3158 3159 if (kill(GetID(), signo)) 3160 error.SetErrorToErrno(); 3161 3162 return error; 3163 } 3164 3165 Error 3166 NativeProcessLinux::Interrupt () 3167 { 3168 // Pick a running thread (or if none, a not-dead stopped thread) as 3169 // the chosen thread that will be the stop-reason thread. 3170 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3171 3172 NativeThreadProtocolSP running_thread_sp; 3173 NativeThreadProtocolSP stopped_thread_sp; 3174 3175 if (log) 3176 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__); 3177 3178 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3179 Mutex::Locker locker (m_threads_mutex); 3180 3181 for (auto thread_sp : m_threads) 3182 { 3183 // The thread shouldn't be null but lets just cover that here. 3184 if (!thread_sp) 3185 continue; 3186 3187 // If we have a running or stepping thread, we'll call that the 3188 // target of the interrupt. 3189 const auto thread_state = thread_sp->GetState (); 3190 if (thread_state == eStateRunning || 3191 thread_state == eStateStepping) 3192 { 3193 running_thread_sp = thread_sp; 3194 break; 3195 } 3196 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true)) 3197 { 3198 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads. 3199 stopped_thread_sp = thread_sp; 3200 } 3201 } 3202 3203 if (!running_thread_sp && !stopped_thread_sp) 3204 { 3205 Error error("found no running/stepping or live stopped threads as target for interrupt"); 3206 if (log) 3207 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ()); 3208 3209 return error; 3210 } 3211 3212 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp; 3213 3214 if (log) 3215 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target", 3216 __FUNCTION__, 3217 GetID (), 3218 running_thread_sp ? "running" : "stopped", 3219 deferred_signal_thread_sp->GetID ()); 3220 3221 StopRunningThreads(deferred_signal_thread_sp->GetID()); 3222 3223 return Error(); 3224 } 3225 3226 Error 3227 NativeProcessLinux::Kill () 3228 { 3229 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3230 if (log) 3231 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ()); 3232 3233 Error error; 3234 3235 switch (m_state) 3236 { 3237 case StateType::eStateInvalid: 3238 case StateType::eStateExited: 3239 case StateType::eStateCrashed: 3240 case StateType::eStateDetached: 3241 case StateType::eStateUnloaded: 3242 // Nothing to do - the process is already dead. 3243 if (log) 3244 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state)); 3245 return error; 3246 3247 case StateType::eStateConnected: 3248 case StateType::eStateAttaching: 3249 case StateType::eStateLaunching: 3250 case StateType::eStateStopped: 3251 case StateType::eStateRunning: 3252 case StateType::eStateStepping: 3253 case StateType::eStateSuspended: 3254 // We can try to kill a process in these states. 3255 break; 3256 } 3257 3258 if (kill (GetID (), SIGKILL) != 0) 3259 { 3260 error.SetErrorToErrno (); 3261 return error; 3262 } 3263 3264 return error; 3265 } 3266 3267 static Error 3268 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info) 3269 { 3270 memory_region_info.Clear(); 3271 3272 StringExtractor line_extractor (maps_line.c_str ()); 3273 3274 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname 3275 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared). 3276 3277 // Parse out the starting address 3278 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0); 3279 3280 // Parse out hyphen separating start and end address from range. 3281 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-')) 3282 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range"); 3283 3284 // Parse out the ending address 3285 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address); 3286 3287 // Parse out the space after the address. 3288 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' ')) 3289 return Error ("malformed /proc/{pid}/maps entry, missing space after range"); 3290 3291 // Save the range. 3292 memory_region_info.GetRange ().SetRangeBase (start_address); 3293 memory_region_info.GetRange ().SetRangeEnd (end_address); 3294 3295 // Parse out each permission entry. 3296 if (line_extractor.GetBytesLeft () < 4) 3297 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions"); 3298 3299 // Handle read permission. 3300 const char read_perm_char = line_extractor.GetChar (); 3301 if (read_perm_char == 'r') 3302 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes); 3303 else 3304 { 3305 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" ); 3306 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 3307 } 3308 3309 // Handle write permission. 3310 const char write_perm_char = line_extractor.GetChar (); 3311 if (write_perm_char == 'w') 3312 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes); 3313 else 3314 { 3315 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" ); 3316 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 3317 } 3318 3319 // Handle execute permission. 3320 const char exec_perm_char = line_extractor.GetChar (); 3321 if (exec_perm_char == 'x') 3322 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes); 3323 else 3324 { 3325 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" ); 3326 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 3327 } 3328 3329 return Error (); 3330 } 3331 3332 Error 3333 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) 3334 { 3335 // FIXME review that the final memory region returned extends to the end of the virtual address space, 3336 // with no perms if it is not mapped. 3337 3338 // Use an approach that reads memory regions from /proc/{pid}/maps. 3339 // Assume proc maps entries are in ascending order. 3340 // FIXME assert if we find differently. 3341 Mutex::Locker locker (m_mem_region_cache_mutex); 3342 3343 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3344 Error error; 3345 3346 if (m_supports_mem_region == LazyBool::eLazyBoolNo) 3347 { 3348 // We're done. 3349 error.SetErrorString ("unsupported"); 3350 return error; 3351 } 3352 3353 // If our cache is empty, pull the latest. There should always be at least one memory region 3354 // if memory region handling is supported. 3355 if (m_mem_region_cache.empty ()) 3356 { 3357 error = ProcFileReader::ProcessLineByLine (GetID (), "maps", 3358 [&] (const std::string &line) -> bool 3359 { 3360 MemoryRegionInfo info; 3361 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info); 3362 if (parse_error.Success ()) 3363 { 3364 m_mem_region_cache.push_back (info); 3365 return true; 3366 } 3367 else 3368 { 3369 if (log) 3370 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ()); 3371 return false; 3372 } 3373 }); 3374 3375 // If we had an error, we'll mark unsupported. 3376 if (error.Fail ()) 3377 { 3378 m_supports_mem_region = LazyBool::eLazyBoolNo; 3379 return error; 3380 } 3381 else if (m_mem_region_cache.empty ()) 3382 { 3383 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps 3384 // is supported. Assume we don't support map entries via procfs. 3385 if (log) 3386 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__); 3387 m_supports_mem_region = LazyBool::eLazyBoolNo; 3388 error.SetErrorString ("not supported"); 3389 return error; 3390 } 3391 3392 if (log) 3393 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ()); 3394 3395 // We support memory retrieval, remember that. 3396 m_supports_mem_region = LazyBool::eLazyBoolYes; 3397 } 3398 else 3399 { 3400 if (log) 3401 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 3402 } 3403 3404 lldb::addr_t prev_base_address = 0; 3405 3406 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted. 3407 // There can be a ton of regions on pthreads apps with lots of threads. 3408 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it) 3409 { 3410 MemoryRegionInfo &proc_entry_info = *it; 3411 3412 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 3413 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"); 3414 prev_base_address = proc_entry_info.GetRange ().GetRangeBase (); 3415 3416 // If the target address comes before this entry, indicate distance to next region. 3417 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ()) 3418 { 3419 range_info.GetRange ().SetRangeBase (load_addr); 3420 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr); 3421 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 3422 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 3423 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 3424 3425 return error; 3426 } 3427 else if (proc_entry_info.GetRange ().Contains (load_addr)) 3428 { 3429 // The target address is within the memory region we're processing here. 3430 range_info = proc_entry_info; 3431 return error; 3432 } 3433 3434 // The target memory address comes somewhere after the region we just parsed. 3435 } 3436 3437 // If we made it here, we didn't find an entry that contained the given address. 3438 error.SetErrorString ("address comes after final region"); 3439 3440 if (log) 3441 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ()); 3442 3443 return error; 3444 } 3445 3446 void 3447 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId) 3448 { 3449 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3450 if (log) 3451 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId); 3452 3453 { 3454 Mutex::Locker locker (m_mem_region_cache_mutex); 3455 if (log) 3456 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 3457 m_mem_region_cache.clear (); 3458 } 3459 } 3460 3461 Error 3462 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr) 3463 { 3464 // FIXME implementing this requires the equivalent of 3465 // InferiorCallPOSIX::InferiorCallMmap, which depends on 3466 // functional ThreadPlans working with Native*Protocol. 3467 #if 1 3468 return Error ("not implemented yet"); 3469 #else 3470 addr = LLDB_INVALID_ADDRESS; 3471 3472 unsigned prot = 0; 3473 if (permissions & lldb::ePermissionsReadable) 3474 prot |= eMmapProtRead; 3475 if (permissions & lldb::ePermissionsWritable) 3476 prot |= eMmapProtWrite; 3477 if (permissions & lldb::ePermissionsExecutable) 3478 prot |= eMmapProtExec; 3479 3480 // TODO implement this directly in NativeProcessLinux 3481 // (and lift to NativeProcessPOSIX if/when that class is 3482 // refactored out). 3483 if (InferiorCallMmap(this, addr, 0, size, prot, 3484 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 3485 m_addr_to_mmap_size[addr] = size; 3486 return Error (); 3487 } else { 3488 addr = LLDB_INVALID_ADDRESS; 3489 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 3490 } 3491 #endif 3492 } 3493 3494 Error 3495 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr) 3496 { 3497 // FIXME see comments in AllocateMemory - required lower-level 3498 // bits not in place yet (ThreadPlans) 3499 return Error ("not implemented"); 3500 } 3501 3502 lldb::addr_t 3503 NativeProcessLinux::GetSharedLibraryInfoAddress () 3504 { 3505 #if 1 3506 // punt on this for now 3507 return LLDB_INVALID_ADDRESS; 3508 #else 3509 // Return the image info address for the exe module 3510 #if 1 3511 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3512 3513 ModuleSP module_sp; 3514 Error error = GetExeModuleSP (module_sp); 3515 if (error.Fail ()) 3516 { 3517 if (log) 3518 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ()); 3519 return LLDB_INVALID_ADDRESS; 3520 } 3521 3522 if (module_sp == nullptr) 3523 { 3524 if (log) 3525 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__); 3526 return LLDB_INVALID_ADDRESS; 3527 } 3528 3529 ObjectFileSP object_file_sp = module_sp->GetObjectFile (); 3530 if (object_file_sp == nullptr) 3531 { 3532 if (log) 3533 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__); 3534 return LLDB_INVALID_ADDRESS; 3535 } 3536 3537 return obj_file_sp->GetImageInfoAddress(); 3538 #else 3539 Target *target = &GetTarget(); 3540 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); 3541 Address addr = obj_file->GetImageInfoAddress(target); 3542 3543 if (addr.IsValid()) 3544 return addr.GetLoadAddress(target); 3545 return LLDB_INVALID_ADDRESS; 3546 #endif 3547 #endif // punt on this for now 3548 } 3549 3550 size_t 3551 NativeProcessLinux::UpdateThreads () 3552 { 3553 // The NativeProcessLinux monitoring threads are always up to date 3554 // with respect to thread state and they keep the thread list 3555 // populated properly. All this method needs to do is return the 3556 // thread count. 3557 Mutex::Locker locker (m_threads_mutex); 3558 return m_threads.size (); 3559 } 3560 3561 bool 3562 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const 3563 { 3564 arch = m_arch; 3565 return true; 3566 } 3567 3568 Error 3569 NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size) 3570 { 3571 // FIXME put this behind a breakpoint protocol class that can be 3572 // set per architecture. Need ARM, MIPS support here. 3573 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3574 static const uint8_t g_i386_opcode [] = { 0xCC }; 3575 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 3576 3577 switch (m_arch.GetMachine ()) 3578 { 3579 case llvm::Triple::aarch64: 3580 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode)); 3581 return Error (); 3582 3583 case llvm::Triple::arm: 3584 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits 3585 return Error (); 3586 3587 case llvm::Triple::x86: 3588 case llvm::Triple::x86_64: 3589 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode)); 3590 return Error (); 3591 3592 case llvm::Triple::mips64: 3593 case llvm::Triple::mips64el: 3594 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode)); 3595 return Error (); 3596 3597 default: 3598 assert(false && "CPU type not supported!"); 3599 return Error ("CPU type not supported"); 3600 } 3601 } 3602 3603 Error 3604 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) 3605 { 3606 if (hardware) 3607 return Error ("NativeProcessLinux does not support hardware breakpoints"); 3608 else 3609 return SetSoftwareBreakpoint (addr, size); 3610 } 3611 3612 Error 3613 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, 3614 size_t &actual_opcode_size, 3615 const uint8_t *&trap_opcode_bytes) 3616 { 3617 // FIXME put this behind a breakpoint protocol class that can be set per 3618 // architecture. Need MIPS support here. 3619 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3620 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 3621 // linux kernel does otherwise. 3622 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 }; 3623 static const uint8_t g_i386_opcode [] = { 0xCC }; 3624 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 3625 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 }; 3626 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde }; 3627 3628 switch (m_arch.GetMachine ()) 3629 { 3630 case llvm::Triple::aarch64: 3631 trap_opcode_bytes = g_aarch64_opcode; 3632 actual_opcode_size = sizeof(g_aarch64_opcode); 3633 return Error (); 3634 3635 case llvm::Triple::arm: 3636 switch (trap_opcode_size_hint) 3637 { 3638 case 2: 3639 trap_opcode_bytes = g_thumb_breakpoint_opcode; 3640 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode); 3641 return Error (); 3642 case 4: 3643 trap_opcode_bytes = g_arm_breakpoint_opcode; 3644 actual_opcode_size = sizeof(g_arm_breakpoint_opcode); 3645 return Error (); 3646 default: 3647 assert(false && "Unrecognised trap opcode size hint!"); 3648 return Error ("Unrecognised trap opcode size hint!"); 3649 } 3650 3651 case llvm::Triple::x86: 3652 case llvm::Triple::x86_64: 3653 trap_opcode_bytes = g_i386_opcode; 3654 actual_opcode_size = sizeof(g_i386_opcode); 3655 return Error (); 3656 3657 case llvm::Triple::mips64: 3658 trap_opcode_bytes = g_mips64_opcode; 3659 actual_opcode_size = sizeof(g_mips64_opcode); 3660 return Error (); 3661 3662 case llvm::Triple::mips64el: 3663 trap_opcode_bytes = g_mips64el_opcode; 3664 actual_opcode_size = sizeof(g_mips64el_opcode); 3665 return Error (); 3666 3667 default: 3668 assert(false && "CPU type not supported!"); 3669 return Error ("CPU type not supported"); 3670 } 3671 } 3672 3673 #if 0 3674 ProcessMessage::CrashReason 3675 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info) 3676 { 3677 ProcessMessage::CrashReason reason; 3678 assert(info->si_signo == SIGSEGV); 3679 3680 reason = ProcessMessage::eInvalidCrashReason; 3681 3682 switch (info->si_code) 3683 { 3684 default: 3685 assert(false && "unexpected si_code for SIGSEGV"); 3686 break; 3687 case SI_KERNEL: 3688 // Linux will occasionally send spurious SI_KERNEL codes. 3689 // (this is poorly documented in sigaction) 3690 // One way to get this is via unaligned SIMD loads. 3691 reason = ProcessMessage::eInvalidAddress; // for lack of anything better 3692 break; 3693 case SEGV_MAPERR: 3694 reason = ProcessMessage::eInvalidAddress; 3695 break; 3696 case SEGV_ACCERR: 3697 reason = ProcessMessage::ePrivilegedAddress; 3698 break; 3699 } 3700 3701 return reason; 3702 } 3703 #endif 3704 3705 3706 #if 0 3707 ProcessMessage::CrashReason 3708 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info) 3709 { 3710 ProcessMessage::CrashReason reason; 3711 assert(info->si_signo == SIGILL); 3712 3713 reason = ProcessMessage::eInvalidCrashReason; 3714 3715 switch (info->si_code) 3716 { 3717 default: 3718 assert(false && "unexpected si_code for SIGILL"); 3719 break; 3720 case ILL_ILLOPC: 3721 reason = ProcessMessage::eIllegalOpcode; 3722 break; 3723 case ILL_ILLOPN: 3724 reason = ProcessMessage::eIllegalOperand; 3725 break; 3726 case ILL_ILLADR: 3727 reason = ProcessMessage::eIllegalAddressingMode; 3728 break; 3729 case ILL_ILLTRP: 3730 reason = ProcessMessage::eIllegalTrap; 3731 break; 3732 case ILL_PRVOPC: 3733 reason = ProcessMessage::ePrivilegedOpcode; 3734 break; 3735 case ILL_PRVREG: 3736 reason = ProcessMessage::ePrivilegedRegister; 3737 break; 3738 case ILL_COPROC: 3739 reason = ProcessMessage::eCoprocessorError; 3740 break; 3741 case ILL_BADSTK: 3742 reason = ProcessMessage::eInternalStackError; 3743 break; 3744 } 3745 3746 return reason; 3747 } 3748 #endif 3749 3750 #if 0 3751 ProcessMessage::CrashReason 3752 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info) 3753 { 3754 ProcessMessage::CrashReason reason; 3755 assert(info->si_signo == SIGFPE); 3756 3757 reason = ProcessMessage::eInvalidCrashReason; 3758 3759 switch (info->si_code) 3760 { 3761 default: 3762 assert(false && "unexpected si_code for SIGFPE"); 3763 break; 3764 case FPE_INTDIV: 3765 reason = ProcessMessage::eIntegerDivideByZero; 3766 break; 3767 case FPE_INTOVF: 3768 reason = ProcessMessage::eIntegerOverflow; 3769 break; 3770 case FPE_FLTDIV: 3771 reason = ProcessMessage::eFloatDivideByZero; 3772 break; 3773 case FPE_FLTOVF: 3774 reason = ProcessMessage::eFloatOverflow; 3775 break; 3776 case FPE_FLTUND: 3777 reason = ProcessMessage::eFloatUnderflow; 3778 break; 3779 case FPE_FLTRES: 3780 reason = ProcessMessage::eFloatInexactResult; 3781 break; 3782 case FPE_FLTINV: 3783 reason = ProcessMessage::eFloatInvalidOperation; 3784 break; 3785 case FPE_FLTSUB: 3786 reason = ProcessMessage::eFloatSubscriptRange; 3787 break; 3788 } 3789 3790 return reason; 3791 } 3792 #endif 3793 3794 #if 0 3795 ProcessMessage::CrashReason 3796 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info) 3797 { 3798 ProcessMessage::CrashReason reason; 3799 assert(info->si_signo == SIGBUS); 3800 3801 reason = ProcessMessage::eInvalidCrashReason; 3802 3803 switch (info->si_code) 3804 { 3805 default: 3806 assert(false && "unexpected si_code for SIGBUS"); 3807 break; 3808 case BUS_ADRALN: 3809 reason = ProcessMessage::eIllegalAlignment; 3810 break; 3811 case BUS_ADRERR: 3812 reason = ProcessMessage::eIllegalAddress; 3813 break; 3814 case BUS_OBJERR: 3815 reason = ProcessMessage::eHardwareError; 3816 break; 3817 } 3818 3819 return reason; 3820 } 3821 #endif 3822 3823 Error 3824 NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) 3825 { 3826 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor 3827 // for it. 3828 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3829 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware); 3830 } 3831 3832 Error 3833 NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr) 3834 { 3835 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor 3836 // for it. 3837 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3838 return NativeProcessProtocol::RemoveWatchpoint(addr); 3839 } 3840 3841 Error 3842 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3843 { 3844 ReadOperation op(addr, buf, size, bytes_read); 3845 m_monitor_up->DoOperation(&op); 3846 return op.GetError (); 3847 } 3848 3849 Error 3850 NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3851 { 3852 Error error = ReadMemory(addr, buf, size, bytes_read); 3853 if (error.Fail()) return error; 3854 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); 3855 } 3856 3857 Error 3858 NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) 3859 { 3860 WriteOperation op(addr, buf, size, bytes_written); 3861 m_monitor_up->DoOperation(&op); 3862 return op.GetError (); 3863 } 3864 3865 Error 3866 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name, 3867 uint32_t size, RegisterValue &value) 3868 { 3869 ReadRegOperation op(tid, offset, reg_name, value); 3870 m_monitor_up->DoOperation(&op); 3871 return op.GetError(); 3872 } 3873 3874 Error 3875 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset, 3876 const char* reg_name, const RegisterValue &value) 3877 { 3878 WriteRegOperation op(tid, offset, reg_name, value); 3879 m_monitor_up->DoOperation(&op); 3880 return op.GetError(); 3881 } 3882 3883 Error 3884 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3885 { 3886 ReadGPROperation op(tid, buf, buf_size); 3887 m_monitor_up->DoOperation(&op); 3888 return op.GetError(); 3889 } 3890 3891 Error 3892 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3893 { 3894 ReadFPROperation op(tid, buf, buf_size); 3895 m_monitor_up->DoOperation(&op); 3896 return op.GetError(); 3897 } 3898 3899 Error 3900 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3901 { 3902 ReadRegisterSetOperation op(tid, buf, buf_size, regset); 3903 m_monitor_up->DoOperation(&op); 3904 return op.GetError(); 3905 } 3906 3907 Error 3908 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3909 { 3910 WriteGPROperation op(tid, buf, buf_size); 3911 m_monitor_up->DoOperation(&op); 3912 return op.GetError(); 3913 } 3914 3915 Error 3916 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3917 { 3918 WriteFPROperation op(tid, buf, buf_size); 3919 m_monitor_up->DoOperation(&op); 3920 return op.GetError(); 3921 } 3922 3923 Error 3924 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3925 { 3926 WriteRegisterSetOperation op(tid, buf, buf_size, regset); 3927 m_monitor_up->DoOperation(&op); 3928 return op.GetError(); 3929 } 3930 3931 Error 3932 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo) 3933 { 3934 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3935 3936 if (log) 3937 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid, 3938 GetUnixSignals().GetSignalAsCString (signo)); 3939 ResumeOperation op (tid, signo); 3940 m_monitor_up->DoOperation (&op); 3941 if (log) 3942 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false"); 3943 return op.GetError(); 3944 } 3945 3946 Error 3947 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo) 3948 { 3949 SingleStepOperation op(tid, signo); 3950 m_monitor_up->DoOperation(&op); 3951 return op.GetError(); 3952 } 3953 3954 Error 3955 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) 3956 { 3957 SiginfoOperation op(tid, siginfo); 3958 m_monitor_up->DoOperation(&op); 3959 return op.GetError(); 3960 } 3961 3962 Error 3963 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message) 3964 { 3965 EventMessageOperation op(tid, message); 3966 m_monitor_up->DoOperation(&op); 3967 return op.GetError(); 3968 } 3969 3970 Error 3971 NativeProcessLinux::Detach(lldb::tid_t tid) 3972 { 3973 if (tid == LLDB_INVALID_THREAD_ID) 3974 return Error(); 3975 3976 DetachOperation op(tid); 3977 m_monitor_up->DoOperation(&op); 3978 return op.GetError(); 3979 } 3980 3981 bool 3982 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags) 3983 { 3984 int target_fd = open(path, flags, 0666); 3985 3986 if (target_fd == -1) 3987 return false; 3988 3989 if (dup2(target_fd, fd) == -1) 3990 return false; 3991 3992 return (close(target_fd) == -1) ? false : true; 3993 } 3994 3995 void 3996 NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error) 3997 { 3998 m_monitor_up.reset(new Monitor(initial_operation, this)); 3999 error = m_monitor_up->Initialize(); 4000 if (error.Fail()) { 4001 m_monitor_up.reset(); 4002 } 4003 } 4004 4005 bool 4006 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id) 4007 { 4008 for (auto thread_sp : m_threads) 4009 { 4010 assert (thread_sp && "thread list should not contain NULL threads"); 4011 if (thread_sp->GetID () == thread_id) 4012 { 4013 // We have this thread. 4014 return true; 4015 } 4016 } 4017 4018 // We don't have this thread. 4019 return false; 4020 } 4021 4022 NativeThreadProtocolSP 4023 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id) 4024 { 4025 // CONSIDER organize threads by map - we can do better than linear. 4026 for (auto thread_sp : m_threads) 4027 { 4028 if (thread_sp->GetID () == thread_id) 4029 return thread_sp; 4030 } 4031 4032 // We don't have this thread. 4033 return NativeThreadProtocolSP (); 4034 } 4035 4036 bool 4037 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id) 4038 { 4039 Mutex::Locker locker (m_threads_mutex); 4040 for (auto it = m_threads.begin (); it != m_threads.end (); ++it) 4041 { 4042 if (*it && ((*it)->GetID () == thread_id)) 4043 { 4044 m_threads.erase (it); 4045 return true; 4046 } 4047 } 4048 4049 // Didn't find it. 4050 return false; 4051 } 4052 4053 NativeThreadProtocolSP 4054 NativeProcessLinux::AddThread (lldb::tid_t thread_id) 4055 { 4056 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 4057 4058 Mutex::Locker locker (m_threads_mutex); 4059 4060 if (log) 4061 { 4062 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64, 4063 __FUNCTION__, 4064 GetID (), 4065 thread_id); 4066 } 4067 4068 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists"); 4069 4070 // If this is the first thread, save it as the current thread 4071 if (m_threads.empty ()) 4072 SetCurrentThreadID (thread_id); 4073 4074 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id)); 4075 m_threads.push_back (thread_sp); 4076 4077 return thread_sp; 4078 } 4079 4080 Error 4081 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp) 4082 { 4083 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 4084 4085 Error error; 4086 4087 // Get a linux thread pointer. 4088 if (!thread_sp) 4089 { 4090 error.SetErrorString ("null thread_sp"); 4091 if (log) 4092 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 4093 return error; 4094 } 4095 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp); 4096 4097 // Find out the size of a breakpoint (might depend on where we are in the code). 4098 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext (); 4099 if (!context_sp) 4100 { 4101 error.SetErrorString ("cannot get a NativeRegisterContext for the thread"); 4102 if (log) 4103 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 4104 return error; 4105 } 4106 4107 uint32_t breakpoint_size = 0; 4108 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size); 4109 if (error.Fail ()) 4110 { 4111 if (log) 4112 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ()); 4113 return error; 4114 } 4115 else 4116 { 4117 if (log) 4118 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size); 4119 } 4120 4121 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size. 4122 const lldb::addr_t initial_pc_addr = context_sp->GetPC (); 4123 lldb::addr_t breakpoint_addr = initial_pc_addr; 4124 if (breakpoint_size > 0) 4125 { 4126 // Do not allow breakpoint probe to wrap around. 4127 if (breakpoint_addr >= breakpoint_size) 4128 breakpoint_addr -= breakpoint_size; 4129 } 4130 4131 // Check if we stopped because of a breakpoint. 4132 NativeBreakpointSP breakpoint_sp; 4133 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp); 4134 if (!error.Success () || !breakpoint_sp) 4135 { 4136 // We didn't find one at a software probe location. Nothing to do. 4137 if (log) 4138 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr); 4139 return Error (); 4140 } 4141 4142 // If the breakpoint is not a software breakpoint, nothing to do. 4143 if (!breakpoint_sp->IsSoftwareBreakpoint ()) 4144 { 4145 if (log) 4146 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr); 4147 return Error (); 4148 } 4149 4150 // 4151 // We have a software breakpoint and need to adjust the PC. 4152 // 4153 4154 // Sanity check. 4155 if (breakpoint_size == 0) 4156 { 4157 // Nothing to do! How did we get here? 4158 if (log) 4159 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); 4160 return Error (); 4161 } 4162 4163 // Change the program counter. 4164 if (log) 4165 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr); 4166 4167 error = context_sp->SetPC (breakpoint_addr); 4168 if (error.Fail ()) 4169 { 4170 if (log) 4171 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ()); 4172 return error; 4173 } 4174 4175 return error; 4176 } 4177 4178 void 4179 NativeProcessLinux::NotifyThreadCreateStopped (lldb::tid_t tid) 4180 { 4181 const bool is_stopped = true; 4182 NotifyThreadCreate (tid, is_stopped); 4183 } 4184 4185 void 4186 NativeProcessLinux::StopRunningThreads(lldb::tid_t trigerring_tid) 4187 { 4188 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 4189 if (log) 4190 log->Printf("NativeProcessLinux::%s tid %" PRIu64, __FUNCTION__, trigerring_tid); 4191 4192 const lldb::pid_t pid = GetID (); 4193 StopRunningThreads(trigerring_tid, 4194 [=](lldb::tid_t request_stop_tid) { return RequestThreadStop(pid, request_stop_tid); }); 4195 } 4196 4197 void 4198 NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t deferred_signal_tid, 4199 lldb::tid_t skip_stop_request_tid) 4200 { 4201 Log *const log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 4202 if (log) 4203 log->Printf("NativeProcessLinux::%s deferred_signal_tid %" PRIu64 ", skip_stop_request_tid %" PRIu64, __FUNCTION__, deferred_signal_tid, skip_stop_request_tid); 4204 4205 const lldb::pid_t pid = GetID (); 4206 StopRunningThreadsWithSkipTID(deferred_signal_tid, 4207 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : NativeProcessLinux::ThreadIDSet (), 4208 [=](lldb::tid_t request_stop_tid) { return RequestThreadStop(pid, request_stop_tid); }); 4209 } 4210 4211 Error 4212 NativeProcessLinux::RequestThreadStop (const lldb::pid_t pid, const lldb::tid_t tid) 4213 { 4214 Log* log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 4215 if (log) 4216 log->Printf ("NativeProcessLinux::%s requesting thread stop(pid: %" PRIu64 ", tid: %" PRIu64 ")", __FUNCTION__, pid, tid); 4217 4218 Error err; 4219 errno = 0; 4220 if (::tgkill (pid, tid, SIGSTOP) != 0) 4221 { 4222 err.SetErrorToErrno (); 4223 if (log) 4224 log->Printf ("NativeProcessLinux::%s tgkill(%" PRIu64 ", %" PRIu64 ", SIGSTOP) failed: %s", __FUNCTION__, pid, tid, err.AsCString ()); 4225 } 4226 4227 return err; 4228 } 4229 4230 Error 4231 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) 4232 { 4233 char maps_file_name[32]; 4234 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID()); 4235 4236 FileSpec maps_file_spec(maps_file_name, false); 4237 if (!maps_file_spec.Exists()) { 4238 file_spec.Clear(); 4239 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID()); 4240 } 4241 4242 FileSpec module_file_spec(module_path, true); 4243 4244 std::ifstream maps_file(maps_file_name); 4245 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>()); 4246 StringRef maps_data(maps_data_str.c_str()); 4247 4248 while (!maps_data.empty()) 4249 { 4250 StringRef maps_row; 4251 std::tie(maps_row, maps_data) = maps_data.split('\n'); 4252 4253 SmallVector<StringRef, 16> maps_columns; 4254 maps_row.split(maps_columns, StringRef(" "), -1, false); 4255 4256 if (maps_columns.size() >= 6) 4257 { 4258 file_spec.SetFile(maps_columns[5].str().c_str(), false); 4259 if (file_spec.GetFilename() == module_file_spec.GetFilename()) 4260 return Error(); 4261 } 4262 } 4263 4264 file_spec.Clear(); 4265 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 4266 module_file_spec.GetFilename().AsCString(), GetID()); 4267 } 4268 4269 Error 4270 NativeProcessLinux::DoResume( 4271 lldb::tid_t tid, 4272 ResumeThreadFunction request_thread_resume_function, 4273 bool error_when_already_running) 4274 { 4275 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4276 4277 auto find_it = m_tid_map.find (tid); 4278 lldbassert(find_it != m_tid_map.end ()); // Ensure we know about the thread. 4279 4280 auto& context = find_it->second; 4281 // Tell the thread to resume if we don't already think it is running. 4282 const bool is_stopped = context.m_state == ThreadState::Stopped; 4283 4284 lldbassert(!(error_when_already_running && !is_stopped)); 4285 4286 if (!is_stopped) 4287 { 4288 // It's not an error, just a log, if the error_when_already_running flag is not set. 4289 // This covers cases where, for instance, we're just trying to resume all threads 4290 // from the user side. 4291 if (log) 4292 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running", 4293 __FUNCTION__, 4294 tid); 4295 return Error(); 4296 } 4297 4298 // Before we do the resume below, first check if we have a pending 4299 // stop notification this is currently or was previously waiting for 4300 // this thread to stop. This is potentially a buggy situation since 4301 // we're ostensibly waiting for threads to stop before we send out the 4302 // pending notification, and here we are resuming one before we send 4303 // out the pending stop notification. 4304 if (m_pending_notification_up && log) 4305 { 4306 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0) 4307 { 4308 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid); 4309 } 4310 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0) 4311 { 4312 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that hasn't fired yet and this is one of the threads we had been waiting on (and already marked satisfied for this tid). Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid); 4313 for (auto tid : m_pending_notification_up->wait_for_stop_tids) 4314 { 4315 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64, 4316 __FUNCTION__, 4317 m_pending_notification_up->triggering_tid, 4318 tid); 4319 } 4320 } 4321 } 4322 4323 // Request a resume. We expect this to be synchronous and the system 4324 // to reflect it is running after this completes. 4325 const auto error = request_thread_resume_function (tid, false); 4326 if (error.Success ()) 4327 { 4328 // Now mark it is running. 4329 context.m_state = ThreadState::Running; 4330 context.m_request_resume_function = request_thread_resume_function; 4331 } 4332 else if (log) 4333 { 4334 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 4335 __FUNCTION__, tid, error.AsCString ()); 4336 } 4337 4338 return error; 4339 } 4340 4341 //===----------------------------------------------------------------------===// 4342 4343 void 4344 NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid, 4345 const ThreadIDSet &wait_for_stop_tids, 4346 const StopThreadFunction &request_thread_stop_function) 4347 { 4348 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4349 std::lock_guard<std::mutex> lock(m_event_mutex); 4350 4351 if (log) 4352 { 4353 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)", 4354 __FUNCTION__, triggering_tid, wait_for_stop_tids.size()); 4355 } 4356 4357 DoStopThreads(PendingNotificationUP(new PendingNotification( 4358 triggering_tid, wait_for_stop_tids, request_thread_stop_function))); 4359 4360 if (log) 4361 { 4362 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4363 } 4364 } 4365 4366 void 4367 NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid, 4368 const StopThreadFunction &request_thread_stop_function) 4369 { 4370 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4371 std::lock_guard<std::mutex> lock(m_event_mutex); 4372 4373 if (log) 4374 { 4375 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")", 4376 __FUNCTION__, triggering_tid); 4377 } 4378 4379 DoStopThreads(PendingNotificationUP(new PendingNotification( 4380 triggering_tid, 4381 request_thread_stop_function))); 4382 4383 if (log) 4384 { 4385 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4386 } 4387 } 4388 4389 void 4390 NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid, 4391 const ThreadIDSet &skip_stop_request_tids, 4392 const StopThreadFunction &request_thread_stop_function) 4393 { 4394 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4395 std::lock_guard<std::mutex> lock(m_event_mutex); 4396 4397 if (log) 4398 { 4399 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tids.size(): %zd)", 4400 __FUNCTION__, triggering_tid, skip_stop_request_tids.size()); 4401 } 4402 4403 DoStopThreads(PendingNotificationUP(new PendingNotification( 4404 triggering_tid, 4405 request_thread_stop_function, 4406 skip_stop_request_tids))); 4407 4408 if (log) 4409 { 4410 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4411 } 4412 } 4413 4414 void 4415 NativeProcessLinux::SignalIfRequirementsSatisfied() 4416 { 4417 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ()) 4418 { 4419 SetCurrentThreadID(m_pending_notification_up->triggering_tid); 4420 SetState(StateType::eStateStopped, true); 4421 m_pending_notification_up.reset(); 4422 } 4423 } 4424 4425 bool 4426 NativeProcessLinux::RequestStopOnAllSpecifiedThreads() 4427 { 4428 // Request a stop for all the thread stops that need to be stopped 4429 // and are not already known to be stopped. Keep a list of all the 4430 // threads from which we still need to hear a stop reply. 4431 4432 ThreadIDSet sent_tids; 4433 for (auto tid : m_pending_notification_up->wait_for_stop_tids) 4434 { 4435 // Validate we know about all tids for which we must first receive a stop before 4436 // triggering the deferred stop notification. 4437 auto find_it = m_tid_map.find (tid); 4438 lldbassert(find_it != m_tid_map.end()); 4439 4440 // If the pending stop thread is currently running, we need to send it a stop request. 4441 auto& context = find_it->second; 4442 if (context.m_state == ThreadState::Running) 4443 { 4444 RequestThreadStop (tid, context); 4445 sent_tids.insert (tid); 4446 } 4447 } 4448 // We only need to wait for the sent_tids - so swap our wait set 4449 // to the sent tids. The rest are already stopped and we won't 4450 // be receiving stop notifications for them. 4451 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids); 4452 4453 // Succeeded, keep running. 4454 return true; 4455 } 4456 4457 void 4458 NativeProcessLinux::RequestStopOnAllRunningThreads() 4459 { 4460 // Request a stop for all the thread stops that need to be stopped 4461 // and are not already known to be stopped. Keep a list of all the 4462 // threads from which we still need to hear a stop reply. 4463 4464 ThreadIDSet sent_tids; 4465 for (auto it = m_tid_map.begin(); it != m_tid_map.end(); ++it) 4466 { 4467 // We only care about threads not stopped. 4468 const bool running = it->second.m_state == ThreadState::Running; 4469 if (running) 4470 { 4471 const lldb::tid_t tid = it->first; 4472 4473 // Request this thread stop if the tid stop request is not explicitly ignored. 4474 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0; 4475 if (!skip_stop_request) 4476 RequestThreadStop (tid, it->second); 4477 4478 // Even if we skipped sending the stop request for other reasons (like stepping), 4479 // we still need to wait for that stepping thread to notify completion/stop. 4480 sent_tids.insert (tid); 4481 } 4482 } 4483 4484 // Set the wait list to the set of tids for which we requested stops. 4485 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids); 4486 } 4487 4488 void 4489 NativeProcessLinux::RequestThreadStop (lldb::tid_t tid, ThreadContext& context) 4490 { 4491 const auto error = m_pending_notification_up->request_thread_stop_function (tid); 4492 if (error.Success ()) 4493 context.m_stop_requested = true; 4494 else 4495 { 4496 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4497 if (log) 4498 log->Printf("NativeProcessLinux::%s failed to request thread stop tid %" PRIu64 ": %s", 4499 __FUNCTION__, tid, error.AsCString ()); 4500 } 4501 } 4502 4503 4504 Error 4505 NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs) 4506 { 4507 // Ensure we know about the thread. 4508 auto find_it = m_tid_map.find (tid); 4509 lldbassert(find_it != m_tid_map.end()); 4510 4511 // Update the global list of known thread states. This one is definitely stopped. 4512 auto& context = find_it->second; 4513 const auto stop_was_requested = context.m_stop_requested; 4514 context.m_state = ThreadState::Stopped; 4515 context.m_stop_requested = false; 4516 4517 // If we have a pending notification, remove this from the set. 4518 if (m_pending_notification_up) 4519 { 4520 m_pending_notification_up->wait_for_stop_tids.erase(tid); 4521 SignalIfRequirementsSatisfied(); 4522 } 4523 4524 if (initiated_by_llgs && context.m_request_resume_function && !stop_was_requested) 4525 { 4526 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4527 // We can end up here if stop was initiated by LLGS but by this time a 4528 // thread stop has occurred - maybe initiated by another event. 4529 if (log) 4530 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid); 4531 const auto error = context.m_request_resume_function (tid, true); 4532 if (error.Success ()) 4533 { 4534 context.m_state = ThreadState::Running; 4535 } 4536 else 4537 { 4538 if (log) 4539 { 4540 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 4541 __FUNCTION__, tid, error.AsCString ()); 4542 } 4543 return error; 4544 } 4545 } 4546 return Error(); 4547 } 4548 4549 void 4550 NativeProcessLinux::DoStopThreads(PendingNotificationUP &¬ification_up) 4551 { 4552 // Validate we know about the deferred trigger thread. 4553 lldbassert(IsKnownThread (notification_up->triggering_tid)); 4554 4555 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4556 if (m_pending_notification_up && log) 4557 { 4558 // Yikes - we've already got a pending signal notification in progress. 4559 // Log this info. We lose the pending notification here. 4560 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64, 4561 __FUNCTION__, 4562 m_pending_notification_up->triggering_tid, 4563 notification_up->triggering_tid); 4564 } 4565 m_pending_notification_up = std::move(notification_up); 4566 4567 if (m_pending_notification_up->request_stop_on_all_unstopped_threads) 4568 RequestStopOnAllRunningThreads(); 4569 else 4570 { 4571 if (!RequestStopOnAllSpecifiedThreads()) 4572 return; 4573 } 4574 4575 SignalIfRequirementsSatisfied(); 4576 } 4577 4578 void 4579 NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid, bool is_stopped) 4580 { 4581 // Ensure we don't already know about the thread. 4582 lldbassert(m_tid_map.find(tid) == m_tid_map.end()); 4583 4584 // Add the new thread to the stop map. 4585 ThreadContext ctx; 4586 ctx.m_state = (is_stopped) ? ThreadState::Stopped : ThreadState::Running; 4587 m_tid_map[tid] = std::move(ctx); 4588 4589 if (m_pending_notification_up && !is_stopped) 4590 { 4591 // We will need to wait for this new thread to stop as well before firing the 4592 // notification. 4593 m_pending_notification_up->wait_for_stop_tids.insert(tid); 4594 m_pending_notification_up->request_thread_stop_function(tid); 4595 } 4596 } 4597 4598 void 4599 NativeProcessLinux::ThreadDidDie (lldb::tid_t tid) 4600 { 4601 // Ensure we know about the thread. 4602 auto find_it = m_tid_map.find (tid); 4603 lldbassert(find_it != m_tid_map.end()); 4604 4605 // Update the global list of known thread states. While this one is stopped, it is also dead. 4606 // So stop tracking it. We assume the user of this coordinator will not keep trying to add 4607 // dependencies on a thread after it is known to be dead. 4608 m_tid_map.erase (find_it); 4609 4610 // If we have a pending notification, remove this from the set. 4611 if (m_pending_notification_up) 4612 { 4613 m_pending_notification_up->wait_for_stop_tids.erase(tid); 4614 SignalIfRequirementsSatisfied(); 4615 } 4616 } 4617 4618 Error 4619 NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs) 4620 { 4621 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4622 std::lock_guard<std::mutex> lock(m_event_mutex); 4623 4624 if (log) 4625 { 4626 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)", 4627 __FUNCTION__, tid, initiated_by_llgs?"":"not "); 4628 } 4629 4630 Error error = ThreadDidStop (tid, initiated_by_llgs); 4631 4632 if (log) 4633 { 4634 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4635 } 4636 4637 return error; 4638 } 4639 4640 Error 4641 NativeProcessLinux::RequestThreadResume (lldb::tid_t tid, 4642 const ResumeThreadFunction &request_thread_resume_function) 4643 { 4644 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4645 std::lock_guard<std::mutex> lock(m_event_mutex); 4646 4647 if (log) 4648 { 4649 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", 4650 __FUNCTION__, tid); 4651 } 4652 4653 Error error = DoResume(tid, request_thread_resume_function, true); 4654 4655 if (log) 4656 { 4657 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4658 } 4659 4660 return error; 4661 } 4662 4663 Error 4664 NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid, 4665 const ResumeThreadFunction &request_thread_resume_function) 4666 { 4667 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4668 std::lock_guard<std::mutex> lock(m_event_mutex); 4669 4670 if (log) 4671 { 4672 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", 4673 __FUNCTION__, tid); 4674 } 4675 4676 Error error = DoResume (tid, request_thread_resume_function, false); 4677 4678 if (log) 4679 { 4680 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4681 } 4682 4683 return error; 4684 } 4685 4686 void 4687 NativeProcessLinux::NotifyThreadCreate (lldb::tid_t tid, 4688 bool is_stopped) 4689 { 4690 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4691 std::lock_guard<std::mutex> lock(m_event_mutex); 4692 4693 if (log) 4694 { 4695 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", is %sstopped)", 4696 __FUNCTION__, tid, is_stopped?"":"not "); 4697 } 4698 4699 ThreadWasCreated (tid, is_stopped); 4700 4701 if (log) 4702 { 4703 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4704 } 4705 } 4706 4707 void 4708 NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid) 4709 { 4710 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4711 std::lock_guard<std::mutex> lock(m_event_mutex); 4712 4713 if (log) 4714 { 4715 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid); 4716 } 4717 4718 ThreadDidDie(tid); 4719 4720 if (log) 4721 { 4722 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4723 } 4724 } 4725 4726 void 4727 NativeProcessLinux::ResetForExec () 4728 { 4729 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4730 std::lock_guard<std::mutex> lock(m_event_mutex); 4731 4732 if (log) 4733 { 4734 log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__); 4735 } 4736 4737 // Clear the pending notification if there was one. 4738 m_pending_notification_up.reset (); 4739 4740 // Clear the stop map - we no longer know anything about any thread state. 4741 // The caller is expected to reset thread states for all threads, and we 4742 // will assume anything we haven't heard about is running and requires a 4743 // stop. 4744 m_tid_map.clear (); 4745 4746 if (log) 4747 { 4748 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4749 } 4750 } 4751 4752 bool 4753 NativeProcessLinux::IsKnownThread (lldb::tid_t tid) const 4754 { 4755 return m_tid_map.find (tid) != m_tid_map.end (); 4756 } 4757