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