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