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