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 other thing it can conceivably be is a call on a pid that no 1957 // longer exists for some reason). 1958 // The tracer (i.e. NativeProcessLinux) is expected to inject the signal 1959 // into the tracee (i.e. inferior) at this point. 1960 if (log) 1961 log->Printf ("NativeProcessLinux::%s resuming from group-stop", __FUNCTION__); 1962 1963 // The inferior process is in 'group-stop', so deliver the stopping signal. 1964 const bool signal_delivered = process->Resume (pid, info.si_signo); 1965 if (log) 1966 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"); 1967 1968 if (signal_delivered) 1969 { 1970 // All is well. 1971 stop_monitoring = false; 1972 } 1973 else 1974 { 1975 if (log) 1976 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " something looks horribly wrong - like the process we're monitoring died. Stop monitoring it.", __FUNCTION__, pid); 1977 1978 // Stop monitoring now. 1979 return true; 1980 } 1981 } 1982 else 1983 { 1984 // ptrace(GETSIGINFO) failed (but not due to group-stop). 1985 1986 // A return value of ESRCH means the thread/process is no longer on the system, 1987 // so it was killed somehow outside of our control. Either way, we can't do anything 1988 // with it anymore. 1989 1990 // We stop monitoring if it was the main thread. 1991 stop_monitoring = is_main_thread; 1992 1993 // Stop tracking the metadata for the thread since it's entirely off the system now. 1994 const bool thread_found = process->StopTrackingThread (pid); 1995 1996 if (log) 1997 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)", 1998 __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"); 1999 2000 if (is_main_thread) 2001 { 2002 // Notify the delegate - our process is not available but appears to have been killed outside 2003 // our control. Is eStateExited the right exit state in this case? 2004 process->SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true); 2005 process->SetState (StateType::eStateExited, true); 2006 } 2007 else 2008 { 2009 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop? 2010 if (log) 2011 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); 2012 } 2013 } 2014 } 2015 else 2016 { 2017 // We have retrieved the signal info. Dispatch appropriately. 2018 if (info.si_signo == SIGTRAP) 2019 process->MonitorSIGTRAP(&info, pid); 2020 else 2021 process->MonitorSignal(&info, pid, exited); 2022 2023 stop_monitoring = false; 2024 } 2025 2026 return stop_monitoring; 2027 } 2028 2029 void 2030 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid) 2031 { 2032 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2033 const bool is_main_thread = (pid == GetID ()); 2034 2035 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!"); 2036 if (!info) 2037 return; 2038 2039 // See if we can find a thread for this signal. 2040 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2041 if (!thread_sp) 2042 { 2043 if (log) 2044 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2045 } 2046 2047 switch (info->si_code) 2048 { 2049 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor. 2050 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)): 2051 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 2052 2053 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): 2054 { 2055 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2056 2057 unsigned long event_message = 0; 2058 if (GetEventMessage(pid, &event_message)) 2059 tid = static_cast<lldb::tid_t> (event_message); 2060 2061 if (log) 2062 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event for tid %" PRIu64, __FUNCTION__, pid, tid); 2063 2064 // If we don't track the thread yet: create it, mark as stopped. 2065 // If we do track it, this is the wait we needed. Now resume the new thread. 2066 // In all cases, resume the current (i.e. main process) thread. 2067 bool already_tracked = false; 2068 thread_sp = GetOrCreateThread (tid, already_tracked); 2069 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread"); 2070 2071 // If the thread was already tracked, it means the created thread already received its SI_USER notification of creation. 2072 if (already_tracked) 2073 { 2074 // FIXME loops like we want to stop all theads here. 2075 // StopAllThreads 2076 2077 // We can now resume the newly created thread since it is fully created. 2078 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning (); 2079 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER); 2080 } 2081 else 2082 { 2083 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before 2084 // this thread is ready to go. 2085 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching (); 2086 } 2087 2088 // In all cases, we can resume the main thread here. 2089 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2090 break; 2091 } 2092 2093 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): 2094 { 2095 NativeThreadProtocolSP main_thread_sp; 2096 2097 if (log) 2098 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP); 2099 2100 // Remove all but the main thread here. 2101 // FIXME check if we really need to do this - how does ptrace behave under exec when multiple threads were present 2102 // before the exec? If we get all the detach signals right, we don't need to do this. However, it makes it clearer 2103 // what we should really be tracking. 2104 { 2105 Mutex::Locker locker (m_threads_mutex); 2106 2107 if (log) 2108 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__); 2109 2110 for (auto thread_sp : m_threads) 2111 { 2112 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID (); 2113 if (is_main_thread) 2114 { 2115 main_thread_sp = thread_sp; 2116 if (log) 2117 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ()); 2118 } 2119 else 2120 { 2121 if (log) 2122 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ()); 2123 } 2124 } 2125 2126 m_threads.clear (); 2127 2128 if (main_thread_sp) 2129 { 2130 m_threads.push_back (main_thread_sp); 2131 SetCurrentThreadID (main_thread_sp->GetID ()); 2132 reinterpret_cast<NativeThreadLinux*>(main_thread_sp.get())->SetStoppedByExec (); 2133 } 2134 else 2135 { 2136 SetCurrentThreadID (LLDB_INVALID_THREAD_ID); 2137 if (log) 2138 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ()); 2139 } 2140 } 2141 2142 // Let our delegate know we have just exec'd. 2143 NotifyDidExec (); 2144 2145 // If we have a main thread, indicate we are stopped. 2146 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked"); 2147 SetState (StateType::eStateStopped); 2148 2149 break; 2150 } 2151 2152 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): 2153 { 2154 // The inferior process or one of its threads is about to exit. 2155 // Maintain the process or thread in a state of "limbo" until we are 2156 // explicitly commanded to detach, destroy, resume, etc. 2157 unsigned long data = 0; 2158 if (!GetEventMessage(pid, &data)) 2159 data = -1; 2160 2161 if (log) 2162 { 2163 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)", 2164 __FUNCTION__, 2165 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false", 2166 pid, 2167 is_main_thread ? "is main thread" : "not main thread"); 2168 } 2169 2170 // Set the thread to exited. 2171 if (thread_sp) 2172 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetExited (); 2173 else 2174 { 2175 if (log) 2176 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " failed to retrieve thread for tid %" PRIu64", cannot set thread state", __FUNCTION__, GetID (), pid); 2177 } 2178 2179 if (is_main_thread) 2180 { 2181 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true); 2182 // Resume the thread so it completely exits. 2183 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2184 } 2185 else 2186 { 2187 // FIXME figure out the path where we plan to reap the metadata for the thread. 2188 } 2189 2190 break; 2191 } 2192 2193 case 0: 2194 case TRAP_TRACE: 2195 // We receive this on single stepping. 2196 if (log) 2197 log->Printf ("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", __FUNCTION__, pid); 2198 2199 if (thread_sp) 2200 { 2201 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP); 2202 SetCurrentThreadID (thread_sp->GetID ()); 2203 } 2204 else 2205 { 2206 if (log) 2207 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 " single stepping received trace but thread not found", __FUNCTION__, GetID (), pid); 2208 } 2209 2210 // Tell the process we have a stop (from single stepping). 2211 SetState (StateType::eStateStopped, true); 2212 break; 2213 2214 case SI_KERNEL: 2215 case TRAP_BRKPT: 2216 if (log) 2217 log->Printf ("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, __FUNCTION__, pid); 2218 2219 // Mark the thread as stopped at breakpoint. 2220 if (thread_sp) 2221 { 2222 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP); 2223 Error error = FixupBreakpointPCAsNeeded (thread_sp); 2224 if (error.Fail ()) 2225 { 2226 if (log) 2227 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", __FUNCTION__, pid, error.AsCString ()); 2228 } 2229 } 2230 else 2231 { 2232 if (log) 2233 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": warning, cannot process software breakpoint since no thread metadata", __FUNCTION__, pid); 2234 } 2235 2236 2237 // Tell the process we have a stop from this thread. 2238 SetCurrentThreadID (pid); 2239 SetState (StateType::eStateStopped, true); 2240 break; 2241 2242 case TRAP_HWBKPT: 2243 if (log) 2244 log->Printf ("NativeProcessLinux::%s() received watchpoint event, pid = %" PRIu64, __FUNCTION__, pid); 2245 2246 // Mark the thread as stopped at watchpoint. 2247 // The address is at (lldb::addr_t)info->si_addr if we need it. 2248 if (thread_sp) 2249 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (SIGTRAP); 2250 else 2251 { 2252 if (log) 2253 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ": warning, cannot process hardware breakpoint since no thread metadata", __FUNCTION__, GetID (), pid); 2254 } 2255 2256 // Tell the process we have a stop from this thread. 2257 SetCurrentThreadID (pid); 2258 SetState (StateType::eStateStopped, true); 2259 break; 2260 2261 case SIGTRAP: 2262 case (SIGTRAP | 0x80): 2263 if (log) 2264 log->Printf ("NativeProcessLinux::%s() received system call stop event, pid %" PRIu64 "tid %" PRIu64, __FUNCTION__, GetID (), pid); 2265 // Ignore these signals until we know more about them. 2266 Resume(pid, 0); 2267 break; 2268 2269 default: 2270 assert(false && "Unexpected SIGTRAP code!"); 2271 if (log) 2272 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))); 2273 break; 2274 2275 } 2276 } 2277 2278 void 2279 NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited) 2280 { 2281 int signo = info->si_signo; 2282 2283 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2284 2285 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 2286 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a 2287 // kill(2) or raise(3). Similarly for tgkill(2) on Linux. 2288 // 2289 // IOW, user generated signals never generate what we consider to be a 2290 // "crash". 2291 // 2292 // Similarly, ACK signals generated by this monitor. 2293 2294 // See if we can find a thread for this signal. 2295 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2296 if (!thread_sp) 2297 { 2298 if (log) 2299 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2300 } 2301 2302 // Handle the signal. 2303 if (info->si_code == SI_TKILL || info->si_code == SI_USER) 2304 { 2305 if (log) 2306 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")", 2307 __FUNCTION__, 2308 GetUnixSignals ().GetSignalAsCString (signo), 2309 signo, 2310 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"), 2311 info->si_pid, 2312 (info->si_pid == getpid ()) ? "is monitor" : "is not monitor", 2313 pid); 2314 } 2315 2316 // Check for new thread notification. 2317 if ((info->si_pid == 0) && (info->si_code == SI_USER)) 2318 { 2319 // A new thread creation is being signaled. This is one of two parts that come in 2320 // a non-deterministic order. pid is the thread id. 2321 if (log) 2322 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification", 2323 __FUNCTION__, GetID (), pid); 2324 2325 // Did we already create the thread? 2326 bool already_tracked = false; 2327 thread_sp = GetOrCreateThread (pid, already_tracked); 2328 assert (thread_sp.get() && "failed to get or create the tracking data for newly created inferior thread"); 2329 2330 // If the thread was already tracked, it means the main thread already received its SIGTRAP for the create. 2331 if (already_tracked) 2332 { 2333 // We can now resume this thread up since it is fully created. 2334 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetRunning (); 2335 Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER); 2336 } 2337 else 2338 { 2339 // Mark the thread as currently launching. Need to wait for SIGTRAP clone on the main thread before 2340 // this thread is ready to go. 2341 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetLaunching (); 2342 } 2343 2344 // Done handling. 2345 return; 2346 } 2347 2348 // Check for thread stop notification. 2349 if ((info->si_pid == getpid ()) && (info->si_code == SI_TKILL) && (signo == SIGSTOP)) 2350 { 2351 // This is a tgkill()-based stop. 2352 if (thread_sp) 2353 { 2354 // An inferior thread just stopped. Mark it as such. 2355 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo); 2356 SetCurrentThreadID (thread_sp->GetID ()); 2357 2358 // Remove this tid from the wait-for-stop set. 2359 Mutex::Locker locker (m_wait_for_stop_tids_mutex); 2360 2361 auto removed_count = m_wait_for_stop_tids.erase (thread_sp->GetID ()); 2362 if (removed_count < 1) 2363 { 2364 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": tgkill()-stopped thread not in m_wait_for_stop_tids", 2365 __FUNCTION__, GetID (), thread_sp->GetID ()); 2366 2367 } 2368 2369 // If this is the last thread in the m_wait_for_stop_tids, we need to notify 2370 // the delegate that a stop has occurred now that every thread that was supposed 2371 // to stop has stopped. 2372 if (m_wait_for_stop_tids.empty ()) 2373 { 2374 if (log) 2375 { 2376 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", setting process state to stopped now that all tids marked for stop have completed", 2377 __FUNCTION__, 2378 GetID (), 2379 pid); 2380 } 2381 SetState (StateType::eStateStopped, true); 2382 } 2383 } 2384 2385 // Done handling. 2386 return; 2387 } 2388 2389 if (log) 2390 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo)); 2391 2392 switch (signo) 2393 { 2394 case SIGSEGV: 2395 { 2396 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 2397 2398 // FIXME figure out how to propagate this properly. Seems like it 2399 // should go in ThreadStopInfo. 2400 // We can get more details on the exact nature of the crash here. 2401 // ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info); 2402 if (!exited) 2403 { 2404 // This is just a pre-signal-delivery notification of the incoming signal. 2405 // Send a stop to the debugger. 2406 if (thread_sp) 2407 { 2408 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo); 2409 SetCurrentThreadID (thread_sp->GetID ()); 2410 } 2411 SetState (StateType::eStateStopped, true); 2412 } 2413 else 2414 { 2415 if (thread_sp) 2416 { 2417 // FIXME figure out what type this is. 2418 const uint64_t exception_type = static_cast<uint64_t> (SIGSEGV); 2419 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (exception_type, fault_addr); 2420 } 2421 SetState (StateType::eStateCrashed, true); 2422 } 2423 } 2424 break; 2425 2426 case SIGABRT: 2427 case SIGILL: 2428 case SIGFPE: 2429 case SIGBUS: 2430 { 2431 // Break these out into separate cases once I have more data for each type of signal. 2432 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 2433 if (!exited) 2434 { 2435 // This is just a pre-signal-delivery notification of the incoming signal. 2436 // Send a stop to the debugger. 2437 if (thread_sp) 2438 { 2439 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetStoppedBySignal (signo); 2440 SetCurrentThreadID (thread_sp->GetID ()); 2441 } 2442 SetState (StateType::eStateStopped, true); 2443 } 2444 else 2445 { 2446 if (thread_sp) 2447 { 2448 // FIXME figure out how to report exit by signal correctly. 2449 const uint64_t exception_type = static_cast<uint64_t> (SIGABRT); 2450 reinterpret_cast<NativeThreadLinux*> (thread_sp.get ())->SetCrashedWithException (exception_type, fault_addr); 2451 } 2452 SetState (StateType::eStateCrashed, true); 2453 } 2454 } 2455 break; 2456 2457 default: 2458 if (log) 2459 log->Printf ("NativeProcessLinux::%s unhandled signal %s (%d)", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo), signo); 2460 break; 2461 } 2462 } 2463 2464 Error 2465 NativeProcessLinux::Resume (const ResumeActionList &resume_actions) 2466 { 2467 Error error; 2468 2469 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 2470 if (log) 2471 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ()); 2472 2473 int run_thread_count = 0; 2474 int stop_thread_count = 0; 2475 int step_thread_count = 0; 2476 2477 std::vector<NativeThreadProtocolSP> new_stop_threads; 2478 2479 Mutex::Locker locker (m_threads_mutex); 2480 for (auto thread_sp : m_threads) 2481 { 2482 assert (thread_sp && "thread list should not contain NULL threads"); 2483 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get ()); 2484 2485 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 2486 assert (action && "NULL ResumeAction returned for thread during Resume ()"); 2487 2488 if (log) 2489 { 2490 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64, 2491 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 2492 } 2493 2494 switch (action->state) 2495 { 2496 case eStateRunning: 2497 // Run the thread, possibly feeding it the signal. 2498 linux_thread_p->SetRunning (); 2499 if (action->signal > 0) 2500 { 2501 // Resume the thread and deliver the given signal, 2502 // then mark as delivered. 2503 Resume (thread_sp->GetID (), action->signal); 2504 resume_actions.SetSignalHandledForThread (thread_sp->GetID ()); 2505 } 2506 else 2507 { 2508 // Just resume the thread with no signal. 2509 Resume (thread_sp->GetID (), LLDB_INVALID_SIGNAL_NUMBER); 2510 } 2511 ++run_thread_count; 2512 break; 2513 2514 case eStateStepping: 2515 // Note: if we have multiple threads, we may need to stop 2516 // the other threads first, then step this one. 2517 linux_thread_p->SetStepping (); 2518 if (SingleStep (thread_sp->GetID (), 0)) 2519 { 2520 if (log) 2521 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step succeeded", 2522 __FUNCTION__, GetID (), thread_sp->GetID ()); 2523 } 2524 else 2525 { 2526 if (log) 2527 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 " single step failed", 2528 __FUNCTION__, GetID (), thread_sp->GetID ()); 2529 } 2530 ++step_thread_count; 2531 break; 2532 2533 case eStateSuspended: 2534 case eStateStopped: 2535 if (!StateIsStoppedState (linux_thread_p->GetState (), false)) 2536 new_stop_threads.push_back (thread_sp); 2537 else 2538 { 2539 if (log) 2540 log->Printf ("NativeProcessLinux::%s no need to stop pid %" PRIu64 " tid %" PRIu64 ", thread state already %s", 2541 __FUNCTION__, GetID (), thread_sp->GetID (), StateAsCString (linux_thread_p->GetState ())); 2542 } 2543 2544 ++stop_thread_count; 2545 break; 2546 2547 default: 2548 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64, 2549 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 2550 } 2551 } 2552 2553 // If any thread was set to run, notify the process state as running. 2554 if (run_thread_count > 0) 2555 SetState (StateType::eStateRunning, true); 2556 2557 // Now do a tgkill SIGSTOP on each thread we want to stop. 2558 if (!new_stop_threads.empty ()) 2559 { 2560 // Lock the m_wait_for_stop_tids set so we can fill it with every thread we expect to have stopped. 2561 Mutex::Locker stop_thread_id_locker (m_wait_for_stop_tids_mutex); 2562 for (auto thread_sp : new_stop_threads) 2563 { 2564 // Send a stop signal to the thread. 2565 const int result = tgkill (GetID (), thread_sp->GetID (), SIGSTOP); 2566 if (result != 0) 2567 { 2568 // tgkill failed. 2569 if (log) 2570 log->Printf ("NativeProcessLinux::%s error: tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 "failed, retval %d", 2571 __FUNCTION__, GetID (), thread_sp->GetID (), result); 2572 } 2573 else 2574 { 2575 // tgkill succeeded. Don't mark the thread state, though. Let the signal 2576 // handling mark it. 2577 if (log) 2578 log->Printf ("NativeProcessLinux::%s tgkill SIGSTOP for pid %" PRIu64 " tid %" PRIu64 " succeeded", 2579 __FUNCTION__, GetID (), thread_sp->GetID ()); 2580 2581 // Add it to the set of threads we expect to signal a stop. 2582 // We won't tell the delegate about it until this list drains to empty. 2583 m_wait_for_stop_tids.insert (thread_sp->GetID ()); 2584 } 2585 } 2586 } 2587 2588 return error; 2589 } 2590 2591 Error 2592 NativeProcessLinux::Halt () 2593 { 2594 Error error; 2595 2596 // FIXME check if we're already stopped 2597 const bool is_stopped = false; 2598 if (is_stopped) 2599 return error; 2600 2601 if (kill (GetID (), SIGSTOP) != 0) 2602 error.SetErrorToErrno (); 2603 2604 return error; 2605 } 2606 2607 Error 2608 NativeProcessLinux::Detach () 2609 { 2610 Error error; 2611 2612 // Tell ptrace to detach from the process. 2613 if (GetID () != LLDB_INVALID_PROCESS_ID) 2614 error = Detach (GetID ()); 2615 2616 // Stop monitoring the inferior. 2617 StopMonitor (); 2618 2619 // No error. 2620 return error; 2621 } 2622 2623 Error 2624 NativeProcessLinux::Signal (int signo) 2625 { 2626 Error error; 2627 2628 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2629 if (log) 2630 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64, 2631 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ()); 2632 2633 if (kill(GetID(), signo)) 2634 error.SetErrorToErrno(); 2635 2636 return error; 2637 } 2638 2639 Error 2640 NativeProcessLinux::Kill () 2641 { 2642 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2643 if (log) 2644 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ()); 2645 2646 Error error; 2647 2648 switch (m_state) 2649 { 2650 case StateType::eStateInvalid: 2651 case StateType::eStateExited: 2652 case StateType::eStateCrashed: 2653 case StateType::eStateDetached: 2654 case StateType::eStateUnloaded: 2655 // Nothing to do - the process is already dead. 2656 if (log) 2657 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state)); 2658 return error; 2659 2660 case StateType::eStateConnected: 2661 case StateType::eStateAttaching: 2662 case StateType::eStateLaunching: 2663 case StateType::eStateStopped: 2664 case StateType::eStateRunning: 2665 case StateType::eStateStepping: 2666 case StateType::eStateSuspended: 2667 // We can try to kill a process in these states. 2668 break; 2669 } 2670 2671 if (kill (GetID (), SIGKILL) != 0) 2672 { 2673 error.SetErrorToErrno (); 2674 return error; 2675 } 2676 2677 return error; 2678 } 2679 2680 static Error 2681 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info) 2682 { 2683 memory_region_info.Clear(); 2684 2685 StringExtractor line_extractor (maps_line.c_str ()); 2686 2687 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname 2688 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared). 2689 2690 // Parse out the starting address 2691 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0); 2692 2693 // Parse out hyphen separating start and end address from range. 2694 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-')) 2695 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range"); 2696 2697 // Parse out the ending address 2698 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address); 2699 2700 // Parse out the space after the address. 2701 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' ')) 2702 return Error ("malformed /proc/{pid}/maps entry, missing space after range"); 2703 2704 // Save the range. 2705 memory_region_info.GetRange ().SetRangeBase (start_address); 2706 memory_region_info.GetRange ().SetRangeEnd (end_address); 2707 2708 // Parse out each permission entry. 2709 if (line_extractor.GetBytesLeft () < 4) 2710 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions"); 2711 2712 // Handle read permission. 2713 const char read_perm_char = line_extractor.GetChar (); 2714 if (read_perm_char == 'r') 2715 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes); 2716 else 2717 { 2718 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" ); 2719 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 2720 } 2721 2722 // Handle write permission. 2723 const char write_perm_char = line_extractor.GetChar (); 2724 if (write_perm_char == 'w') 2725 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes); 2726 else 2727 { 2728 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" ); 2729 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 2730 } 2731 2732 // Handle execute permission. 2733 const char exec_perm_char = line_extractor.GetChar (); 2734 if (exec_perm_char == 'x') 2735 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes); 2736 else 2737 { 2738 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" ); 2739 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 2740 } 2741 2742 return Error (); 2743 } 2744 2745 Error 2746 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) 2747 { 2748 // FIXME review that the final memory region returned extends to the end of the virtual address space, 2749 // with no perms if it is not mapped. 2750 2751 // Use an approach that reads memory regions from /proc/{pid}/maps. 2752 // Assume proc maps entries are in ascending order. 2753 // FIXME assert if we find differently. 2754 Mutex::Locker locker (m_mem_region_cache_mutex); 2755 2756 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2757 Error error; 2758 2759 if (m_supports_mem_region == LazyBool::eLazyBoolNo) 2760 { 2761 // We're done. 2762 error.SetErrorString ("unsupported"); 2763 return error; 2764 } 2765 2766 // If our cache is empty, pull the latest. There should always be at least one memory region 2767 // if memory region handling is supported. 2768 if (m_mem_region_cache.empty ()) 2769 { 2770 error = ProcFileReader::ProcessLineByLine (GetID (), "maps", 2771 [&] (const std::string &line) -> bool 2772 { 2773 MemoryRegionInfo info; 2774 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info); 2775 if (parse_error.Success ()) 2776 { 2777 m_mem_region_cache.push_back (info); 2778 return true; 2779 } 2780 else 2781 { 2782 if (log) 2783 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ()); 2784 return false; 2785 } 2786 }); 2787 2788 // If we had an error, we'll mark unsupported. 2789 if (error.Fail ()) 2790 { 2791 m_supports_mem_region = LazyBool::eLazyBoolNo; 2792 return error; 2793 } 2794 else if (m_mem_region_cache.empty ()) 2795 { 2796 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps 2797 // is supported. Assume we don't support map entries via procfs. 2798 if (log) 2799 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__); 2800 m_supports_mem_region = LazyBool::eLazyBoolNo; 2801 error.SetErrorString ("not supported"); 2802 return error; 2803 } 2804 2805 if (log) 2806 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ()); 2807 2808 // We support memory retrieval, remember that. 2809 m_supports_mem_region = LazyBool::eLazyBoolYes; 2810 } 2811 else 2812 { 2813 if (log) 2814 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 2815 } 2816 2817 lldb::addr_t prev_base_address = 0; 2818 2819 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted. 2820 // There can be a ton of regions on pthreads apps with lots of threads. 2821 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it) 2822 { 2823 MemoryRegionInfo &proc_entry_info = *it; 2824 2825 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 2826 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"); 2827 prev_base_address = proc_entry_info.GetRange ().GetRangeBase (); 2828 2829 // If the target address comes before this entry, indicate distance to next region. 2830 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ()) 2831 { 2832 range_info.GetRange ().SetRangeBase (load_addr); 2833 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr); 2834 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 2835 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 2836 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 2837 2838 return error; 2839 } 2840 else if (proc_entry_info.GetRange ().Contains (load_addr)) 2841 { 2842 // The target address is within the memory region we're processing here. 2843 range_info = proc_entry_info; 2844 return error; 2845 } 2846 2847 // The target memory address comes somewhere after the region we just parsed. 2848 } 2849 2850 // If we made it here, we didn't find an entry that contained the given address. 2851 error.SetErrorString ("address comes after final region"); 2852 2853 if (log) 2854 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ()); 2855 2856 return error; 2857 } 2858 2859 void 2860 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId) 2861 { 2862 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2863 if (log) 2864 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId); 2865 2866 { 2867 Mutex::Locker locker (m_mem_region_cache_mutex); 2868 if (log) 2869 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 2870 m_mem_region_cache.clear (); 2871 } 2872 } 2873 2874 Error 2875 NativeProcessLinux::AllocateMemory ( 2876 lldb::addr_t size, 2877 uint32_t permissions, 2878 lldb::addr_t &addr) 2879 { 2880 // FIXME implementing this requires the equivalent of 2881 // InferiorCallPOSIX::InferiorCallMmap, which depends on 2882 // functional ThreadPlans working with Native*Protocol. 2883 #if 1 2884 return Error ("not implemented yet"); 2885 #else 2886 addr = LLDB_INVALID_ADDRESS; 2887 2888 unsigned prot = 0; 2889 if (permissions & lldb::ePermissionsReadable) 2890 prot |= eMmapProtRead; 2891 if (permissions & lldb::ePermissionsWritable) 2892 prot |= eMmapProtWrite; 2893 if (permissions & lldb::ePermissionsExecutable) 2894 prot |= eMmapProtExec; 2895 2896 // TODO implement this directly in NativeProcessLinux 2897 // (and lift to NativeProcessPOSIX if/when that class is 2898 // refactored out). 2899 if (InferiorCallMmap(this, addr, 0, size, prot, 2900 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 2901 m_addr_to_mmap_size[addr] = size; 2902 return Error (); 2903 } else { 2904 addr = LLDB_INVALID_ADDRESS; 2905 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 2906 } 2907 #endif 2908 } 2909 2910 Error 2911 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr) 2912 { 2913 // FIXME see comments in AllocateMemory - required lower-level 2914 // bits not in place yet (ThreadPlans) 2915 return Error ("not implemented"); 2916 } 2917 2918 lldb::addr_t 2919 NativeProcessLinux::GetSharedLibraryInfoAddress () 2920 { 2921 #if 1 2922 // punt on this for now 2923 return LLDB_INVALID_ADDRESS; 2924 #else 2925 // Return the image info address for the exe module 2926 #if 1 2927 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2928 2929 ModuleSP module_sp; 2930 Error error = GetExeModuleSP (module_sp); 2931 if (error.Fail ()) 2932 { 2933 if (log) 2934 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ()); 2935 return LLDB_INVALID_ADDRESS; 2936 } 2937 2938 if (module_sp == nullptr) 2939 { 2940 if (log) 2941 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__); 2942 return LLDB_INVALID_ADDRESS; 2943 } 2944 2945 ObjectFileSP object_file_sp = module_sp->GetObjectFile (); 2946 if (object_file_sp == nullptr) 2947 { 2948 if (log) 2949 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__); 2950 return LLDB_INVALID_ADDRESS; 2951 } 2952 2953 return obj_file_sp->GetImageInfoAddress(); 2954 #else 2955 Target *target = &GetTarget(); 2956 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); 2957 Address addr = obj_file->GetImageInfoAddress(target); 2958 2959 if (addr.IsValid()) 2960 return addr.GetLoadAddress(target); 2961 return LLDB_INVALID_ADDRESS; 2962 #endif 2963 #endif // punt on this for now 2964 } 2965 2966 size_t 2967 NativeProcessLinux::UpdateThreads () 2968 { 2969 // The NativeProcessLinux monitoring threads are always up to date 2970 // with respect to thread state and they keep the thread list 2971 // populated properly. All this method needs to do is return the 2972 // thread count. 2973 Mutex::Locker locker (m_threads_mutex); 2974 return m_threads.size (); 2975 } 2976 2977 bool 2978 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const 2979 { 2980 arch = m_arch; 2981 return true; 2982 } 2983 2984 Error 2985 NativeProcessLinux::GetSoftwareBreakpointSize (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size) 2986 { 2987 // FIXME put this behind a breakpoint protocol class that can be 2988 // set per architecture. Need ARM, MIPS support here. 2989 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 2990 static const uint8_t g_i386_opcode [] = { 0xCC }; 2991 2992 switch (m_arch.GetMachine ()) 2993 { 2994 case llvm::Triple::aarch64: 2995 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode)); 2996 return Error (); 2997 2998 case llvm::Triple::x86: 2999 case llvm::Triple::x86_64: 3000 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode)); 3001 return Error (); 3002 3003 default: 3004 assert(false && "CPU type not supported!"); 3005 return Error ("CPU type not supported"); 3006 } 3007 } 3008 3009 Error 3010 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) 3011 { 3012 if (hardware) 3013 return Error ("NativeProcessLinux does not support hardware breakpoints"); 3014 else 3015 return SetSoftwareBreakpoint (addr, size); 3016 } 3017 3018 Error 3019 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, size_t &actual_opcode_size, const uint8_t *&trap_opcode_bytes) 3020 { 3021 // FIXME put this behind a breakpoint protocol class that can be 3022 // set per architecture. Need ARM, MIPS support here. 3023 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3024 static const uint8_t g_i386_opcode [] = { 0xCC }; 3025 3026 switch (m_arch.GetMachine ()) 3027 { 3028 case llvm::Triple::aarch64: 3029 trap_opcode_bytes = g_aarch64_opcode; 3030 actual_opcode_size = sizeof(g_aarch64_opcode); 3031 return Error (); 3032 3033 case llvm::Triple::x86: 3034 case llvm::Triple::x86_64: 3035 trap_opcode_bytes = g_i386_opcode; 3036 actual_opcode_size = sizeof(g_i386_opcode); 3037 return Error (); 3038 3039 default: 3040 assert(false && "CPU type not supported!"); 3041 return Error ("CPU type not supported"); 3042 } 3043 } 3044 3045 #if 0 3046 ProcessMessage::CrashReason 3047 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info) 3048 { 3049 ProcessMessage::CrashReason reason; 3050 assert(info->si_signo == SIGSEGV); 3051 3052 reason = ProcessMessage::eInvalidCrashReason; 3053 3054 switch (info->si_code) 3055 { 3056 default: 3057 assert(false && "unexpected si_code for SIGSEGV"); 3058 break; 3059 case SI_KERNEL: 3060 // Linux will occasionally send spurious SI_KERNEL codes. 3061 // (this is poorly documented in sigaction) 3062 // One way to get this is via unaligned SIMD loads. 3063 reason = ProcessMessage::eInvalidAddress; // for lack of anything better 3064 break; 3065 case SEGV_MAPERR: 3066 reason = ProcessMessage::eInvalidAddress; 3067 break; 3068 case SEGV_ACCERR: 3069 reason = ProcessMessage::ePrivilegedAddress; 3070 break; 3071 } 3072 3073 return reason; 3074 } 3075 #endif 3076 3077 3078 #if 0 3079 ProcessMessage::CrashReason 3080 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info) 3081 { 3082 ProcessMessage::CrashReason reason; 3083 assert(info->si_signo == SIGILL); 3084 3085 reason = ProcessMessage::eInvalidCrashReason; 3086 3087 switch (info->si_code) 3088 { 3089 default: 3090 assert(false && "unexpected si_code for SIGILL"); 3091 break; 3092 case ILL_ILLOPC: 3093 reason = ProcessMessage::eIllegalOpcode; 3094 break; 3095 case ILL_ILLOPN: 3096 reason = ProcessMessage::eIllegalOperand; 3097 break; 3098 case ILL_ILLADR: 3099 reason = ProcessMessage::eIllegalAddressingMode; 3100 break; 3101 case ILL_ILLTRP: 3102 reason = ProcessMessage::eIllegalTrap; 3103 break; 3104 case ILL_PRVOPC: 3105 reason = ProcessMessage::ePrivilegedOpcode; 3106 break; 3107 case ILL_PRVREG: 3108 reason = ProcessMessage::ePrivilegedRegister; 3109 break; 3110 case ILL_COPROC: 3111 reason = ProcessMessage::eCoprocessorError; 3112 break; 3113 case ILL_BADSTK: 3114 reason = ProcessMessage::eInternalStackError; 3115 break; 3116 } 3117 3118 return reason; 3119 } 3120 #endif 3121 3122 #if 0 3123 ProcessMessage::CrashReason 3124 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info) 3125 { 3126 ProcessMessage::CrashReason reason; 3127 assert(info->si_signo == SIGFPE); 3128 3129 reason = ProcessMessage::eInvalidCrashReason; 3130 3131 switch (info->si_code) 3132 { 3133 default: 3134 assert(false && "unexpected si_code for SIGFPE"); 3135 break; 3136 case FPE_INTDIV: 3137 reason = ProcessMessage::eIntegerDivideByZero; 3138 break; 3139 case FPE_INTOVF: 3140 reason = ProcessMessage::eIntegerOverflow; 3141 break; 3142 case FPE_FLTDIV: 3143 reason = ProcessMessage::eFloatDivideByZero; 3144 break; 3145 case FPE_FLTOVF: 3146 reason = ProcessMessage::eFloatOverflow; 3147 break; 3148 case FPE_FLTUND: 3149 reason = ProcessMessage::eFloatUnderflow; 3150 break; 3151 case FPE_FLTRES: 3152 reason = ProcessMessage::eFloatInexactResult; 3153 break; 3154 case FPE_FLTINV: 3155 reason = ProcessMessage::eFloatInvalidOperation; 3156 break; 3157 case FPE_FLTSUB: 3158 reason = ProcessMessage::eFloatSubscriptRange; 3159 break; 3160 } 3161 3162 return reason; 3163 } 3164 #endif 3165 3166 #if 0 3167 ProcessMessage::CrashReason 3168 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info) 3169 { 3170 ProcessMessage::CrashReason reason; 3171 assert(info->si_signo == SIGBUS); 3172 3173 reason = ProcessMessage::eInvalidCrashReason; 3174 3175 switch (info->si_code) 3176 { 3177 default: 3178 assert(false && "unexpected si_code for SIGBUS"); 3179 break; 3180 case BUS_ADRALN: 3181 reason = ProcessMessage::eIllegalAlignment; 3182 break; 3183 case BUS_ADRERR: 3184 reason = ProcessMessage::eIllegalAddress; 3185 break; 3186 case BUS_OBJERR: 3187 reason = ProcessMessage::eHardwareError; 3188 break; 3189 } 3190 3191 return reason; 3192 } 3193 #endif 3194 3195 void 3196 NativeProcessLinux::ServeOperation(OperationArgs *args) 3197 { 3198 NativeProcessLinux *monitor = args->m_monitor; 3199 3200 // We are finised with the arguments and are ready to go. Sync with the 3201 // parent thread and start serving operations on the inferior. 3202 sem_post(&args->m_semaphore); 3203 3204 for(;;) 3205 { 3206 // wait for next pending operation 3207 if (sem_wait(&monitor->m_operation_pending)) 3208 { 3209 if (errno == EINTR) 3210 continue; 3211 assert(false && "Unexpected errno from sem_wait"); 3212 } 3213 3214 reinterpret_cast<Operation*>(monitor->m_operation)->Execute(monitor); 3215 3216 // notify calling thread that operation is complete 3217 sem_post(&monitor->m_operation_done); 3218 } 3219 } 3220 3221 void 3222 NativeProcessLinux::DoOperation(void *op) 3223 { 3224 Mutex::Locker lock(m_operation_mutex); 3225 3226 m_operation = op; 3227 3228 // notify operation thread that an operation is ready to be processed 3229 sem_post(&m_operation_pending); 3230 3231 // wait for operation to complete 3232 while (sem_wait(&m_operation_done)) 3233 { 3234 if (errno == EINTR) 3235 continue; 3236 assert(false && "Unexpected errno from sem_wait"); 3237 } 3238 } 3239 3240 Error 3241 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, lldb::addr_t size, lldb::addr_t &bytes_read) 3242 { 3243 ReadOperation op(addr, buf, size, bytes_read); 3244 DoOperation(&op); 3245 return op.GetError (); 3246 } 3247 3248 Error 3249 NativeProcessLinux::WriteMemory (lldb::addr_t addr, const void *buf, lldb::addr_t size, lldb::addr_t &bytes_written) 3250 { 3251 WriteOperation op(addr, buf, size, bytes_written); 3252 DoOperation(&op); 3253 return op.GetError (); 3254 } 3255 3256 bool 3257 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name, 3258 uint32_t size, RegisterValue &value) 3259 { 3260 bool result; 3261 ReadRegOperation op(tid, offset, reg_name, value, result); 3262 DoOperation(&op); 3263 return result; 3264 } 3265 3266 bool 3267 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset, 3268 const char* reg_name, const RegisterValue &value) 3269 { 3270 bool result; 3271 WriteRegOperation op(tid, offset, reg_name, value, result); 3272 DoOperation(&op); 3273 return result; 3274 } 3275 3276 bool 3277 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3278 { 3279 bool result; 3280 ReadGPROperation op(tid, buf, buf_size, result); 3281 DoOperation(&op); 3282 return result; 3283 } 3284 3285 bool 3286 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3287 { 3288 bool result; 3289 ReadFPROperation op(tid, buf, buf_size, result); 3290 DoOperation(&op); 3291 return result; 3292 } 3293 3294 bool 3295 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3296 { 3297 bool result; 3298 ReadRegisterSetOperation op(tid, buf, buf_size, regset, result); 3299 DoOperation(&op); 3300 return result; 3301 } 3302 3303 bool 3304 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3305 { 3306 bool result; 3307 WriteGPROperation op(tid, buf, buf_size, result); 3308 DoOperation(&op); 3309 return result; 3310 } 3311 3312 bool 3313 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3314 { 3315 bool result; 3316 WriteFPROperation op(tid, buf, buf_size, result); 3317 DoOperation(&op); 3318 return result; 3319 } 3320 3321 bool 3322 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3323 { 3324 bool result; 3325 WriteRegisterSetOperation op(tid, buf, buf_size, regset, result); 3326 DoOperation(&op); 3327 return result; 3328 } 3329 3330 bool 3331 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo) 3332 { 3333 bool result; 3334 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3335 3336 if (log) 3337 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid, 3338 GetUnixSignals().GetSignalAsCString (signo)); 3339 ResumeOperation op (tid, signo, result); 3340 DoOperation (&op); 3341 if (log) 3342 log->Printf ("NativeProcessLinux::%s() resuming result = %s", __FUNCTION__, result ? "true" : "false"); 3343 return result; 3344 } 3345 3346 bool 3347 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo) 3348 { 3349 bool result; 3350 SingleStepOperation op(tid, signo, result); 3351 DoOperation(&op); 3352 return result; 3353 } 3354 3355 bool 3356 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo, int &ptrace_err) 3357 { 3358 bool result; 3359 SiginfoOperation op(tid, siginfo, result, ptrace_err); 3360 DoOperation(&op); 3361 return result; 3362 } 3363 3364 bool 3365 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message) 3366 { 3367 bool result; 3368 EventMessageOperation op(tid, message, result); 3369 DoOperation(&op); 3370 return result; 3371 } 3372 3373 lldb_private::Error 3374 NativeProcessLinux::Detach(lldb::tid_t tid) 3375 { 3376 lldb_private::Error error; 3377 if (tid != LLDB_INVALID_THREAD_ID) 3378 { 3379 DetachOperation op(tid, error); 3380 DoOperation(&op); 3381 } 3382 return error; 3383 } 3384 3385 bool 3386 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags) 3387 { 3388 int target_fd = open(path, flags, 0666); 3389 3390 if (target_fd == -1) 3391 return false; 3392 3393 return (dup2(target_fd, fd) == -1) ? false : true; 3394 } 3395 3396 void 3397 NativeProcessLinux::StopMonitoringChildProcess() 3398 { 3399 lldb::thread_result_t thread_result; 3400 3401 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread)) 3402 { 3403 Host::ThreadCancel(m_monitor_thread, NULL); 3404 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL); 3405 m_monitor_thread = LLDB_INVALID_HOST_THREAD; 3406 } 3407 } 3408 3409 void 3410 NativeProcessLinux::StopMonitor() 3411 { 3412 StopMonitoringChildProcess(); 3413 StopOpThread(); 3414 sem_destroy(&m_operation_pending); 3415 sem_destroy(&m_operation_done); 3416 3417 // TODO: validate whether this still holds, fix up comment. 3418 // Note: ProcessPOSIX passes the m_terminal_fd file descriptor to 3419 // Process::SetSTDIOFileDescriptor, which in turn transfers ownership of 3420 // the descriptor to a ConnectionFileDescriptor object. Consequently 3421 // even though still has the file descriptor, we shouldn't close it here. 3422 } 3423 3424 void 3425 NativeProcessLinux::StopOpThread() 3426 { 3427 lldb::thread_result_t result; 3428 3429 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread)) 3430 return; 3431 3432 Host::ThreadCancel(m_operation_thread, NULL); 3433 Host::ThreadJoin(m_operation_thread, &result, NULL); 3434 m_operation_thread = LLDB_INVALID_HOST_THREAD; 3435 } 3436 3437 bool 3438 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id) 3439 { 3440 for (auto thread_sp : m_threads) 3441 { 3442 assert (thread_sp && "thread list should not contain NULL threads"); 3443 if (thread_sp->GetID () == thread_id) 3444 { 3445 // We have this thread. 3446 return true; 3447 } 3448 } 3449 3450 // We don't have this thread. 3451 return false; 3452 } 3453 3454 NativeThreadProtocolSP 3455 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id) 3456 { 3457 // CONSIDER organize threads by map - we can do better than linear. 3458 for (auto thread_sp : m_threads) 3459 { 3460 if (thread_sp->GetID () == thread_id) 3461 return thread_sp; 3462 } 3463 3464 // We don't have this thread. 3465 return NativeThreadProtocolSP (); 3466 } 3467 3468 bool 3469 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id) 3470 { 3471 Mutex::Locker locker (m_threads_mutex); 3472 for (auto it = m_threads.begin (); it != m_threads.end (); ++it) 3473 { 3474 if (*it && ((*it)->GetID () == thread_id)) 3475 { 3476 m_threads.erase (it); 3477 return true; 3478 } 3479 } 3480 3481 // Didn't find it. 3482 return false; 3483 } 3484 3485 NativeThreadProtocolSP 3486 NativeProcessLinux::AddThread (lldb::tid_t thread_id) 3487 { 3488 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 3489 3490 Mutex::Locker locker (m_threads_mutex); 3491 3492 if (log) 3493 { 3494 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64, 3495 __FUNCTION__, 3496 GetID (), 3497 thread_id); 3498 } 3499 3500 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists"); 3501 3502 // If this is the first thread, save it as the current thread 3503 if (m_threads.empty ()) 3504 SetCurrentThreadID (thread_id); 3505 3506 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id)); 3507 m_threads.push_back (thread_sp); 3508 3509 return thread_sp; 3510 } 3511 3512 NativeThreadProtocolSP 3513 NativeProcessLinux::GetOrCreateThread (lldb::tid_t thread_id, bool &created) 3514 { 3515 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 3516 3517 Mutex::Locker locker (m_threads_mutex); 3518 if (log) 3519 { 3520 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " get/create thread with tid %" PRIu64, 3521 __FUNCTION__, 3522 GetID (), 3523 thread_id); 3524 } 3525 3526 // Retrieve the thread if it is already getting tracked. 3527 NativeThreadProtocolSP thread_sp = MaybeGetThreadNoLock (thread_id); 3528 if (thread_sp) 3529 { 3530 if (log) 3531 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread already tracked, returning", 3532 __FUNCTION__, 3533 GetID (), 3534 thread_id); 3535 created = false; 3536 return thread_sp; 3537 3538 } 3539 3540 // Create the thread metadata since it isn't being tracked. 3541 if (log) 3542 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": thread didn't exist, tracking now", 3543 __FUNCTION__, 3544 GetID (), 3545 thread_id); 3546 3547 thread_sp.reset (new NativeThreadLinux (this, thread_id)); 3548 m_threads.push_back (thread_sp); 3549 created = true; 3550 3551 return thread_sp; 3552 } 3553 3554 Error 3555 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp) 3556 { 3557 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 3558 3559 Error error; 3560 3561 // Get a linux thread pointer. 3562 if (!thread_sp) 3563 { 3564 error.SetErrorString ("null thread_sp"); 3565 if (log) 3566 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 3567 return error; 3568 } 3569 NativeThreadLinux *const linux_thread_p = reinterpret_cast<NativeThreadLinux*> (thread_sp.get()); 3570 3571 // Find out the size of a breakpoint (might depend on where we are in the code). 3572 NativeRegisterContextSP context_sp = linux_thread_p->GetRegisterContext (); 3573 if (!context_sp) 3574 { 3575 error.SetErrorString ("cannot get a NativeRegisterContext for the thread"); 3576 if (log) 3577 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 3578 return error; 3579 } 3580 3581 uint32_t breakpoint_size = 0; 3582 error = GetSoftwareBreakpointSize (context_sp, breakpoint_size); 3583 if (error.Fail ()) 3584 { 3585 if (log) 3586 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ()); 3587 return error; 3588 } 3589 else 3590 { 3591 if (log) 3592 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size); 3593 } 3594 3595 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size. 3596 const lldb::addr_t initial_pc_addr = context_sp->GetPC (); 3597 lldb::addr_t breakpoint_addr = initial_pc_addr; 3598 if (breakpoint_size > static_cast<lldb::addr_t> (0)) 3599 { 3600 // Do not allow breakpoint probe to wrap around. 3601 if (breakpoint_addr >= static_cast<lldb::addr_t> (breakpoint_size)) 3602 breakpoint_addr -= static_cast<lldb::addr_t> (breakpoint_size); 3603 } 3604 3605 // Check if we stopped because of a breakpoint. 3606 NativeBreakpointSP breakpoint_sp; 3607 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp); 3608 if (!error.Success () || !breakpoint_sp) 3609 { 3610 // We didn't find one at a software probe location. Nothing to do. 3611 if (log) 3612 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr); 3613 return Error (); 3614 } 3615 3616 // If the breakpoint is not a software breakpoint, nothing to do. 3617 if (!breakpoint_sp->IsSoftwareBreakpoint ()) 3618 { 3619 if (log) 3620 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr); 3621 return Error (); 3622 } 3623 3624 // 3625 // We have a software breakpoint and need to adjust the PC. 3626 // 3627 3628 // Sanity check. 3629 if (breakpoint_size == 0) 3630 { 3631 // Nothing to do! How did we get here? 3632 if (log) 3633 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); 3634 return Error (); 3635 } 3636 3637 // Change the program counter. 3638 if (log) 3639 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); 3640 3641 error = context_sp->SetPC (breakpoint_addr); 3642 if (error.Fail ()) 3643 { 3644 if (log) 3645 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_p->GetID (), error.AsCString ()); 3646 return error; 3647 } 3648 3649 return error; 3650 } 3651