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