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