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