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