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 21 // C++ Includes 22 #include <fstream> 23 #include <sstream> 24 #include <string> 25 26 // Other libraries and framework includes 27 #include "lldb/Core/Debugger.h" 28 #include "lldb/Core/EmulateInstruction.h" 29 #include "lldb/Core/Error.h" 30 #include "lldb/Core/Module.h" 31 #include "lldb/Core/ModuleSpec.h" 32 #include "lldb/Core/RegisterValue.h" 33 #include "lldb/Core/Scalar.h" 34 #include "lldb/Core/State.h" 35 #include "lldb/Host/common/NativeBreakpoint.h" 36 #include "lldb/Host/common/NativeRegisterContext.h" 37 #include "lldb/Host/Host.h" 38 #include "lldb/Host/HostInfo.h" 39 #include "lldb/Host/HostNativeThread.h" 40 #include "lldb/Host/ThreadLauncher.h" 41 #include "lldb/Symbol/ObjectFile.h" 42 #include "lldb/Target/Process.h" 43 #include "lldb/Target/ProcessLaunchInfo.h" 44 #include "lldb/Utility/LLDBAssert.h" 45 #include "lldb/Utility/PseudoTerminal.h" 46 47 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 48 #include "Plugins/Process/Utility/LinuxSignals.h" 49 #include "Utility/StringExtractor.h" 50 #include "NativeThreadLinux.h" 51 #include "ProcFileReader.h" 52 #include "Procfs.h" 53 54 // System includes - They have to be included after framework includes because they define some 55 // macros which collide with variable names in other modules 56 #include <linux/unistd.h> 57 #include <sys/personality.h> 58 #include <sys/ptrace.h> 59 #include <sys/socket.h> 60 #include <sys/signalfd.h> 61 #include <sys/types.h> 62 #include <sys/uio.h> 63 #include <sys/user.h> 64 #include <sys/wait.h> 65 66 #if defined (__arm64__) || defined (__aarch64__) 67 // NT_PRSTATUS and NT_FPREGSET definition 68 #include <elf.h> 69 #endif 70 71 #ifdef __ANDROID__ 72 #define __ptrace_request int 73 #define PT_DETACH PTRACE_DETACH 74 #endif 75 76 #define DEBUG_PTRACE_MAXBYTES 20 77 78 // Support ptrace extensions even when compiled without required kernel support 79 #ifndef PT_GETREGS 80 #ifndef PTRACE_GETREGS 81 #define PTRACE_GETREGS 12 82 #endif 83 #endif 84 #ifndef PT_SETREGS 85 #ifndef PTRACE_SETREGS 86 #define PTRACE_SETREGS 13 87 #endif 88 #endif 89 #ifndef PT_GETFPREGS 90 #ifndef PTRACE_GETFPREGS 91 #define PTRACE_GETFPREGS 14 92 #endif 93 #endif 94 #ifndef PT_SETFPREGS 95 #ifndef PTRACE_SETFPREGS 96 #define PTRACE_SETFPREGS 15 97 #endif 98 #endif 99 #ifndef PTRACE_GETREGSET 100 #define PTRACE_GETREGSET 0x4204 101 #endif 102 #ifndef PTRACE_SETREGSET 103 #define PTRACE_SETREGSET 0x4205 104 #endif 105 #ifndef PTRACE_GET_THREAD_AREA 106 #define PTRACE_GET_THREAD_AREA 25 107 #endif 108 #ifndef PTRACE_ARCH_PRCTL 109 #define PTRACE_ARCH_PRCTL 30 110 #endif 111 #ifndef ARCH_GET_FS 112 #define ARCH_SET_GS 0x1001 113 #define ARCH_SET_FS 0x1002 114 #define ARCH_GET_FS 0x1003 115 #define ARCH_GET_GS 0x1004 116 #endif 117 118 #define LLDB_PERSONALITY_GET_CURRENT_SETTINGS 0xffffffff 119 120 // Support hardware breakpoints in case it has not been defined 121 #ifndef TRAP_HWBKPT 122 #define TRAP_HWBKPT 4 123 #endif 124 125 // We disable the tracing of ptrace calls for integration builds to 126 // avoid the additional indirection and checks. 127 #ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION 128 #define PTRACE(req, pid, addr, data, data_size, error) \ 129 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error), #req, __FILE__, __LINE__) 130 #else 131 #define PTRACE(req, pid, addr, data, data_size, error) \ 132 PtraceWrapper((req), (pid), (addr), (data), (data_size), (error)) 133 #endif 134 135 using namespace lldb; 136 using namespace lldb_private; 137 using namespace lldb_private::process_linux; 138 using namespace llvm; 139 140 // Private bits we only need internally. 141 namespace 142 { 143 const UnixSignals& 144 GetUnixSignals () 145 { 146 static process_linux::LinuxSignals signals; 147 return signals; 148 } 149 150 Error 151 ResolveProcessArchitecture (lldb::pid_t pid, Platform &platform, ArchSpec &arch) 152 { 153 // Grab process info for the running process. 154 ProcessInstanceInfo process_info; 155 if (!platform.GetProcessInfo (pid, process_info)) 156 return Error("failed to get process info"); 157 158 // Resolve the executable module. 159 ModuleSP exe_module_sp; 160 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture()); 161 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths ()); 162 Error error = platform.ResolveExecutable( 163 exe_module_spec, 164 exe_module_sp, 165 executable_search_paths.GetSize () ? &executable_search_paths : NULL); 166 167 if (!error.Success ()) 168 return error; 169 170 // Check if we've got our architecture from the exe_module. 171 arch = exe_module_sp->GetArchitecture (); 172 if (arch.IsValid ()) 173 return Error(); 174 else 175 return Error("failed to retrieve a valid architecture from the exe module"); 176 } 177 178 void 179 DisplayBytes (StreamString &s, void *bytes, uint32_t count) 180 { 181 uint8_t *ptr = (uint8_t *)bytes; 182 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 183 for(uint32_t i=0; i<loop_count; i++) 184 { 185 s.Printf ("[%x]", *ptr); 186 ptr++; 187 } 188 } 189 190 void 191 PtraceDisplayBytes(int &req, void *data, size_t data_size) 192 { 193 StreamString buf; 194 Log *verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet ( 195 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE)); 196 197 if (verbose_log) 198 { 199 switch(req) 200 { 201 case PTRACE_POKETEXT: 202 { 203 DisplayBytes(buf, &data, 8); 204 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData()); 205 break; 206 } 207 case PTRACE_POKEDATA: 208 { 209 DisplayBytes(buf, &data, 8); 210 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData()); 211 break; 212 } 213 case PTRACE_POKEUSER: 214 { 215 DisplayBytes(buf, &data, 8); 216 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData()); 217 break; 218 } 219 case PTRACE_SETREGS: 220 { 221 DisplayBytes(buf, data, data_size); 222 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData()); 223 break; 224 } 225 case PTRACE_SETFPREGS: 226 { 227 DisplayBytes(buf, data, data_size); 228 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData()); 229 break; 230 } 231 case PTRACE_SETSIGINFO: 232 { 233 DisplayBytes(buf, data, sizeof(siginfo_t)); 234 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData()); 235 break; 236 } 237 case PTRACE_SETREGSET: 238 { 239 // Extract iov_base from data, which is a pointer to the struct IOVEC 240 DisplayBytes(buf, *(void **)data, data_size); 241 verbose_log->Printf("PTRACE_SETREGSET %s", buf.GetData()); 242 break; 243 } 244 default: 245 { 246 } 247 } 248 } 249 } 250 251 // Wrapper for ptrace to catch errors and log calls. 252 // Note that ptrace sets errno on error because -1 can be a valid result (i.e. for PTRACE_PEEK*) 253 long 254 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error, 255 const char* reqName, const char* file, int line) 256 { 257 long int result; 258 259 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE)); 260 261 PtraceDisplayBytes(req, data, data_size); 262 263 error.Clear(); 264 errno = 0; 265 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 266 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data); 267 else 268 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data); 269 270 if (result == -1) 271 error.SetErrorToErrno(); 272 273 if (log) 274 log->Printf("ptrace(%s, %" PRIu64 ", %p, %p, %zu)=%lX called from file %s line %d", 275 reqName, pid, addr, data, data_size, result, file, line); 276 277 PtraceDisplayBytes(req, data, data_size); 278 279 if (log && error.GetError() != 0) 280 { 281 const char* str; 282 switch (error.GetError()) 283 { 284 case ESRCH: str = "ESRCH"; break; 285 case EINVAL: str = "EINVAL"; break; 286 case EBUSY: str = "EBUSY"; break; 287 case EPERM: str = "EPERM"; break; 288 default: str = error.AsCString(); 289 } 290 log->Printf("ptrace() failed; errno=%d (%s)", error.GetError(), str); 291 } 292 293 return result; 294 } 295 296 #ifdef LLDB_CONFIGURATION_BUILDANDINTEGRATION 297 // Wrapper for ptrace when logging is not required. 298 // Sets errno to 0 prior to calling ptrace. 299 long 300 PtraceWrapper(int req, lldb::pid_t pid, void *addr, void *data, size_t data_size, Error& error) 301 { 302 long result = 0; 303 304 error.Clear(); 305 errno = 0; 306 if (req == PTRACE_GETREGSET || req == PTRACE_SETREGSET) 307 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), *(unsigned int *)addr, data); 308 else 309 result = ptrace(static_cast<__ptrace_request>(req), static_cast< ::pid_t>(pid), addr, data); 310 311 if (result == -1) 312 error.SetErrorToErrno(); 313 return result; 314 } 315 #endif 316 317 //------------------------------------------------------------------------------ 318 // Static implementations of NativeProcessLinux::ReadMemory and 319 // NativeProcessLinux::WriteMemory. This enables mutual recursion between these 320 // functions without needed to go thru the thread funnel. 321 322 size_t 323 DoReadMemory( 324 lldb::pid_t pid, 325 lldb::addr_t vm_addr, 326 void *buf, 327 size_t size, 328 Error &error) 329 { 330 // ptrace word size is determined by the host, not the child 331 static const unsigned word_size = sizeof(void*); 332 unsigned char *dst = static_cast<unsigned char*>(buf); 333 size_t bytes_read; 334 size_t remainder; 335 long data; 336 337 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 338 if (log) 339 ProcessPOSIXLog::IncNestLevel(); 340 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 341 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %d, %p, %p, %zd, _)", __FUNCTION__, 342 pid, word_size, (void*)vm_addr, buf, size); 343 344 assert(sizeof(data) >= word_size); 345 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) 346 { 347 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, nullptr, 0, error); 348 if (error.Fail()) 349 { 350 if (log) 351 ProcessPOSIXLog::DecNestLevel(); 352 return bytes_read; 353 } 354 355 remainder = size - bytes_read; 356 remainder = remainder > word_size ? word_size : remainder; 357 358 // Copy the data into our buffer 359 for (unsigned i = 0; i < remainder; ++i) 360 dst[i] = ((data >> i*8) & 0xFF); 361 362 if (log && ProcessPOSIXLog::AtTopNestLevel() && 363 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 364 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 365 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 366 { 367 uintptr_t print_dst = 0; 368 // Format bytes from data by moving into print_dst for log output 369 for (unsigned i = 0; i < remainder; ++i) 370 print_dst |= (((data >> i*8) & 0xFF) << i*8); 371 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 372 (void*)vm_addr, print_dst, (unsigned long)data); 373 } 374 375 vm_addr += word_size; 376 dst += word_size; 377 } 378 379 if (log) 380 ProcessPOSIXLog::DecNestLevel(); 381 return bytes_read; 382 } 383 384 size_t 385 DoWriteMemory( 386 lldb::pid_t pid, 387 lldb::addr_t vm_addr, 388 const void *buf, 389 size_t size, 390 Error &error) 391 { 392 // ptrace word size is determined by the host, not the child 393 static const unsigned word_size = sizeof(void*); 394 const unsigned char *src = static_cast<const unsigned char*>(buf); 395 size_t bytes_written = 0; 396 size_t remainder; 397 398 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 399 if (log) 400 ProcessPOSIXLog::IncNestLevel(); 401 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 402 log->Printf ("NativeProcessLinux::%s(%" PRIu64 ", %u, %p, %p, %" PRIu64 ")", __FUNCTION__, 403 pid, word_size, (void*)vm_addr, buf, size); 404 405 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) 406 { 407 remainder = size - bytes_written; 408 remainder = remainder > word_size ? word_size : remainder; 409 410 if (remainder == word_size) 411 { 412 unsigned long data = 0; 413 assert(sizeof(data) >= word_size); 414 for (unsigned i = 0; i < word_size; ++i) 415 data |= (unsigned long)src[i] << i*8; 416 417 if (log && ProcessPOSIXLog::AtTopNestLevel() && 418 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 419 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 420 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 421 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 422 (void*)vm_addr, *(const unsigned long*)src, data); 423 424 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data, 0, error)) 425 { 426 if (log) 427 ProcessPOSIXLog::DecNestLevel(); 428 return bytes_written; 429 } 430 } 431 else 432 { 433 unsigned char buff[8]; 434 if (DoReadMemory(pid, vm_addr, 435 buff, word_size, error) != word_size) 436 { 437 if (log) 438 ProcessPOSIXLog::DecNestLevel(); 439 return bytes_written; 440 } 441 442 memcpy(buff, src, remainder); 443 444 if (DoWriteMemory(pid, vm_addr, 445 buff, word_size, error) != word_size) 446 { 447 if (log) 448 ProcessPOSIXLog::DecNestLevel(); 449 return bytes_written; 450 } 451 452 if (log && ProcessPOSIXLog::AtTopNestLevel() && 453 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 454 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 455 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 456 log->Printf ("NativeProcessLinux::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 457 (void*)vm_addr, *(const unsigned long*)src, *(unsigned long*)buff); 458 } 459 460 vm_addr += word_size; 461 src += word_size; 462 } 463 if (log) 464 ProcessPOSIXLog::DecNestLevel(); 465 return bytes_written; 466 } 467 468 //------------------------------------------------------------------------------ 469 /// @class Operation 470 /// @brief Represents a NativeProcessLinux operation. 471 /// 472 /// Under Linux, it is not possible to ptrace() from any other thread but the 473 /// one that spawned or attached to the process from the start. Therefore, when 474 /// a NativeProcessLinux is asked to deliver or change the state of an inferior 475 /// process the operation must be "funneled" to a specific thread to perform the 476 /// task. The Operation class provides an abstract base for all services the 477 /// NativeProcessLinux must perform via the single virtual function Execute, thus 478 /// encapsulating the code that needs to run in the privileged context. 479 class Operation 480 { 481 public: 482 Operation () : m_error() { } 483 484 virtual 485 ~Operation() {} 486 487 virtual void 488 Execute (NativeProcessLinux *process) = 0; 489 490 const Error & 491 GetError () const { return m_error; } 492 493 protected: 494 Error m_error; 495 }; 496 497 //------------------------------------------------------------------------------ 498 /// @class ReadOperation 499 /// @brief Implements NativeProcessLinux::ReadMemory. 500 class ReadOperation : public Operation 501 { 502 public: 503 ReadOperation( 504 lldb::addr_t addr, 505 void *buff, 506 size_t size, 507 size_t &result) : 508 Operation (), 509 m_addr (addr), 510 m_buff (buff), 511 m_size (size), 512 m_result (result) 513 { 514 } 515 516 void Execute (NativeProcessLinux *process) override; 517 518 private: 519 lldb::addr_t m_addr; 520 void *m_buff; 521 size_t m_size; 522 size_t &m_result; 523 }; 524 525 void 526 ReadOperation::Execute (NativeProcessLinux *process) 527 { 528 m_result = DoReadMemory (process->GetID (), m_addr, m_buff, m_size, m_error); 529 } 530 531 //------------------------------------------------------------------------------ 532 /// @class WriteOperation 533 /// @brief Implements NativeProcessLinux::WriteMemory. 534 class WriteOperation : public Operation 535 { 536 public: 537 WriteOperation( 538 lldb::addr_t addr, 539 const void *buff, 540 size_t size, 541 size_t &result) : 542 Operation (), 543 m_addr (addr), 544 m_buff (buff), 545 m_size (size), 546 m_result (result) 547 { 548 } 549 550 void Execute (NativeProcessLinux *process) override; 551 552 private: 553 lldb::addr_t m_addr; 554 const void *m_buff; 555 size_t m_size; 556 size_t &m_result; 557 }; 558 559 void 560 WriteOperation::Execute(NativeProcessLinux *process) 561 { 562 m_result = DoWriteMemory (process->GetID (), m_addr, m_buff, m_size, m_error); 563 } 564 565 //------------------------------------------------------------------------------ 566 /// @class ReadRegOperation 567 /// @brief Implements NativeProcessLinux::ReadRegisterValue. 568 class ReadRegOperation : public Operation 569 { 570 public: 571 ReadRegOperation(lldb::tid_t tid, uint32_t offset, const char *reg_name, 572 RegisterValue &value) 573 : m_tid(tid), 574 m_offset(static_cast<uintptr_t> (offset)), 575 m_reg_name(reg_name), 576 m_value(value) 577 { } 578 579 void Execute(NativeProcessLinux *monitor) override; 580 581 private: 582 lldb::tid_t m_tid; 583 uintptr_t m_offset; 584 const char *m_reg_name; 585 RegisterValue &m_value; 586 }; 587 588 void 589 ReadRegOperation::Execute(NativeProcessLinux *monitor) 590 { 591 #if defined (__arm64__) || defined (__aarch64__) 592 if (m_offset > sizeof(struct user_pt_regs)) 593 { 594 uintptr_t offset = m_offset - sizeof(struct user_pt_regs); 595 if (offset > sizeof(struct user_fpsimd_state)) 596 { 597 m_error.SetErrorString("invalid offset value"); 598 return; 599 } 600 elf_fpregset_t regs; 601 int regset = NT_FPREGSET; 602 struct iovec ioVec; 603 604 ioVec.iov_base = ®s; 605 ioVec.iov_len = sizeof regs; 606 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 607 if (m_error.Success()) 608 { 609 ArchSpec arch; 610 if (monitor->GetArchitecture(arch)) 611 m_value.SetBytes((void *)(((unsigned char *)(®s)) + offset), 16, arch.GetByteOrder()); 612 else 613 m_error.SetErrorString("failed to get architecture"); 614 } 615 } 616 else 617 { 618 elf_gregset_t regs; 619 int regset = NT_PRSTATUS; 620 struct iovec ioVec; 621 622 ioVec.iov_base = ®s; 623 ioVec.iov_len = sizeof regs; 624 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 625 if (m_error.Success()) 626 { 627 ArchSpec arch; 628 if (monitor->GetArchitecture(arch)) 629 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder()); 630 else 631 m_error.SetErrorString("failed to get architecture"); 632 } 633 } 634 #elif defined (__mips__) 635 elf_gregset_t regs; 636 PTRACE(PTRACE_GETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 637 if (m_error.Success()) 638 { 639 lldb_private::ArchSpec arch; 640 if (monitor->GetArchitecture(arch)) 641 m_value.SetBytes((void *)(((unsigned char *)(regs)) + m_offset), 8, arch.GetByteOrder()); 642 else 643 m_error.SetErrorString("failed to get architecture"); 644 } 645 #else 646 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 647 648 lldb::addr_t data = static_cast<unsigned long>(PTRACE(PTRACE_PEEKUSER, m_tid, (void*)m_offset, nullptr, 0, m_error)); 649 if (m_error.Success()) 650 m_value = data; 651 652 if (log) 653 log->Printf ("NativeProcessLinux::%s() reg %s: 0x%" PRIx64, __FUNCTION__, 654 m_reg_name, data); 655 #endif 656 } 657 658 //------------------------------------------------------------------------------ 659 /// @class WriteRegOperation 660 /// @brief Implements NativeProcessLinux::WriteRegisterValue. 661 class WriteRegOperation : public Operation 662 { 663 public: 664 WriteRegOperation(lldb::tid_t tid, unsigned offset, const char *reg_name, 665 const RegisterValue &value) 666 : m_tid(tid), 667 m_offset(offset), 668 m_reg_name(reg_name), 669 m_value(value) 670 { } 671 672 void Execute(NativeProcessLinux *monitor) override; 673 674 private: 675 lldb::tid_t m_tid; 676 uintptr_t m_offset; 677 const char *m_reg_name; 678 const RegisterValue &m_value; 679 }; 680 681 void 682 WriteRegOperation::Execute(NativeProcessLinux *monitor) 683 { 684 #if defined (__arm64__) || defined (__aarch64__) 685 if (m_offset > sizeof(struct user_pt_regs)) 686 { 687 uintptr_t offset = m_offset - sizeof(struct user_pt_regs); 688 if (offset > sizeof(struct user_fpsimd_state)) 689 { 690 m_error.SetErrorString("invalid offset value"); 691 return; 692 } 693 elf_fpregset_t regs; 694 int regset = NT_FPREGSET; 695 struct iovec ioVec; 696 697 ioVec.iov_base = ®s; 698 ioVec.iov_len = sizeof regs; 699 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 700 if (m_error.Success()) 701 { 702 ::memcpy((void *)(((unsigned char *)(®s)) + offset), m_value.GetBytes(), 16); 703 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 704 } 705 } 706 else 707 { 708 elf_gregset_t regs; 709 int regset = NT_PRSTATUS; 710 struct iovec ioVec; 711 712 ioVec.iov_base = ®s; 713 ioVec.iov_len = sizeof regs; 714 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 715 if (m_error.Success()) 716 { 717 ::memcpy((void *)(((unsigned char *)(®s)) + m_offset), m_value.GetBytes(), 8); 718 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, sizeof regs, m_error); 719 } 720 } 721 #elif defined (__mips__) 722 elf_gregset_t regs; 723 PTRACE(PTRACE_GETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 724 if (m_error.Success()) 725 { 726 ::memcpy((void *)(((unsigned char *)(®s)) + m_offset), m_value.GetBytes(), 8); 727 PTRACE(PTRACE_SETREGS, m_tid, NULL, ®s, sizeof regs, m_error); 728 } 729 #else 730 void* buf; 731 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 732 733 buf = (void*) m_value.GetAsUInt64(); 734 735 if (log) 736 log->Printf ("NativeProcessLinux::%s() reg %s: %p", __FUNCTION__, m_reg_name, buf); 737 PTRACE(PTRACE_POKEUSER, m_tid, (void*)m_offset, buf, 0, m_error); 738 #endif 739 } 740 741 //------------------------------------------------------------------------------ 742 /// @class ReadGPROperation 743 /// @brief Implements NativeProcessLinux::ReadGPR. 744 class ReadGPROperation : public Operation 745 { 746 public: 747 ReadGPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 748 : m_tid(tid), m_buf(buf), m_buf_size(buf_size) 749 { } 750 751 void Execute(NativeProcessLinux *monitor) override; 752 753 private: 754 lldb::tid_t m_tid; 755 void *m_buf; 756 size_t m_buf_size; 757 }; 758 759 void 760 ReadGPROperation::Execute(NativeProcessLinux *monitor) 761 { 762 #if defined (__arm64__) || defined (__aarch64__) 763 int regset = NT_PRSTATUS; 764 struct iovec ioVec; 765 766 ioVec.iov_base = m_buf; 767 ioVec.iov_len = m_buf_size; 768 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 769 #else 770 PTRACE(PTRACE_GETREGS, m_tid, nullptr, m_buf, m_buf_size, m_error); 771 #endif 772 } 773 774 //------------------------------------------------------------------------------ 775 /// @class ReadFPROperation 776 /// @brief Implements NativeProcessLinux::ReadFPR. 777 class ReadFPROperation : public Operation 778 { 779 public: 780 ReadFPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 781 : m_tid(tid), 782 m_buf(buf), 783 m_buf_size(buf_size) 784 { } 785 786 void Execute(NativeProcessLinux *monitor) override; 787 788 private: 789 lldb::tid_t m_tid; 790 void *m_buf; 791 size_t m_buf_size; 792 }; 793 794 void 795 ReadFPROperation::Execute(NativeProcessLinux *monitor) 796 { 797 #if defined (__arm64__) || defined (__aarch64__) 798 int regset = NT_FPREGSET; 799 struct iovec ioVec; 800 801 ioVec.iov_base = m_buf; 802 ioVec.iov_len = m_buf_size; 803 PTRACE(PTRACE_GETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 804 #else 805 PTRACE(PTRACE_GETFPREGS, m_tid, nullptr, m_buf, m_buf_size, m_error); 806 #endif 807 } 808 809 //------------------------------------------------------------------------------ 810 /// @class ReadRegisterSetOperation 811 /// @brief Implements NativeProcessLinux::ReadRegisterSet. 812 class ReadRegisterSetOperation : public Operation 813 { 814 public: 815 ReadRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 816 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset) 817 { } 818 819 void Execute(NativeProcessLinux *monitor) override; 820 821 private: 822 lldb::tid_t m_tid; 823 void *m_buf; 824 size_t m_buf_size; 825 const unsigned int m_regset; 826 }; 827 828 void 829 ReadRegisterSetOperation::Execute(NativeProcessLinux *monitor) 830 { 831 PTRACE(PTRACE_GETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error); 832 } 833 834 //------------------------------------------------------------------------------ 835 /// @class WriteGPROperation 836 /// @brief Implements NativeProcessLinux::WriteGPR. 837 class WriteGPROperation : public Operation 838 { 839 public: 840 WriteGPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 841 : m_tid(tid), m_buf(buf), m_buf_size(buf_size) 842 { } 843 844 void Execute(NativeProcessLinux *monitor) override; 845 846 private: 847 lldb::tid_t m_tid; 848 void *m_buf; 849 size_t m_buf_size; 850 }; 851 852 void 853 WriteGPROperation::Execute(NativeProcessLinux *monitor) 854 { 855 #if defined (__arm64__) || defined (__aarch64__) 856 int regset = NT_PRSTATUS; 857 struct iovec ioVec; 858 859 ioVec.iov_base = m_buf; 860 ioVec.iov_len = m_buf_size; 861 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 862 #else 863 PTRACE(PTRACE_SETREGS, m_tid, NULL, m_buf, m_buf_size, m_error); 864 #endif 865 } 866 867 //------------------------------------------------------------------------------ 868 /// @class WriteFPROperation 869 /// @brief Implements NativeProcessLinux::WriteFPR. 870 class WriteFPROperation : public Operation 871 { 872 public: 873 WriteFPROperation(lldb::tid_t tid, void *buf, size_t buf_size) 874 : m_tid(tid), m_buf(buf), m_buf_size(buf_size) 875 { } 876 877 void Execute(NativeProcessLinux *monitor) override; 878 879 private: 880 lldb::tid_t m_tid; 881 void *m_buf; 882 size_t m_buf_size; 883 }; 884 885 void 886 WriteFPROperation::Execute(NativeProcessLinux *monitor) 887 { 888 #if defined (__arm64__) || defined (__aarch64__) 889 int regset = NT_FPREGSET; 890 struct iovec ioVec; 891 892 ioVec.iov_base = m_buf; 893 ioVec.iov_len = m_buf_size; 894 PTRACE(PTRACE_SETREGSET, m_tid, ®set, &ioVec, m_buf_size, m_error); 895 #else 896 PTRACE(PTRACE_SETFPREGS, m_tid, NULL, m_buf, m_buf_size, m_error); 897 #endif 898 } 899 900 //------------------------------------------------------------------------------ 901 /// @class WriteRegisterSetOperation 902 /// @brief Implements NativeProcessLinux::WriteRegisterSet. 903 class WriteRegisterSetOperation : public Operation 904 { 905 public: 906 WriteRegisterSetOperation(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 907 : m_tid(tid), m_buf(buf), m_buf_size(buf_size), m_regset(regset) 908 { } 909 910 void Execute(NativeProcessLinux *monitor) override; 911 912 private: 913 lldb::tid_t m_tid; 914 void *m_buf; 915 size_t m_buf_size; 916 const unsigned int m_regset; 917 }; 918 919 void 920 WriteRegisterSetOperation::Execute(NativeProcessLinux *monitor) 921 { 922 PTRACE(PTRACE_SETREGSET, m_tid, (void *)&m_regset, m_buf, m_buf_size, m_error); 923 } 924 925 //------------------------------------------------------------------------------ 926 /// @class ResumeOperation 927 /// @brief Implements NativeProcessLinux::Resume. 928 class ResumeOperation : public Operation 929 { 930 public: 931 ResumeOperation(lldb::tid_t tid, uint32_t signo) : 932 m_tid(tid), m_signo(signo) { } 933 934 void Execute(NativeProcessLinux *monitor) override; 935 936 private: 937 lldb::tid_t m_tid; 938 uint32_t m_signo; 939 }; 940 941 void 942 ResumeOperation::Execute(NativeProcessLinux *monitor) 943 { 944 intptr_t data = 0; 945 946 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER) 947 data = m_signo; 948 949 PTRACE(PTRACE_CONT, m_tid, nullptr, (void*)data, 0, m_error); 950 if (m_error.Fail()) 951 { 952 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 953 954 if (log) 955 log->Printf ("ResumeOperation (%" PRIu64 ") failed: %s", m_tid, m_error.AsCString()); 956 } 957 } 958 959 //------------------------------------------------------------------------------ 960 /// @class SingleStepOperation 961 /// @brief Implements NativeProcessLinux::SingleStep. 962 class SingleStepOperation : public Operation 963 { 964 public: 965 SingleStepOperation(lldb::tid_t tid, uint32_t signo) 966 : m_tid(tid), m_signo(signo) { } 967 968 void Execute(NativeProcessLinux *monitor) override; 969 970 private: 971 lldb::tid_t m_tid; 972 uint32_t m_signo; 973 }; 974 975 void 976 SingleStepOperation::Execute(NativeProcessLinux *monitor) 977 { 978 intptr_t data = 0; 979 980 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER) 981 data = m_signo; 982 983 PTRACE(PTRACE_SINGLESTEP, m_tid, nullptr, (void*)data, 0, m_error); 984 } 985 986 //------------------------------------------------------------------------------ 987 /// @class SiginfoOperation 988 /// @brief Implements NativeProcessLinux::GetSignalInfo. 989 class SiginfoOperation : public Operation 990 { 991 public: 992 SiginfoOperation(lldb::tid_t tid, void *info) 993 : m_tid(tid), m_info(info) { } 994 995 void Execute(NativeProcessLinux *monitor) override; 996 997 private: 998 lldb::tid_t m_tid; 999 void *m_info; 1000 }; 1001 1002 void 1003 SiginfoOperation::Execute(NativeProcessLinux *monitor) 1004 { 1005 PTRACE(PTRACE_GETSIGINFO, m_tid, nullptr, m_info, 0, m_error); 1006 } 1007 1008 //------------------------------------------------------------------------------ 1009 /// @class EventMessageOperation 1010 /// @brief Implements NativeProcessLinux::GetEventMessage. 1011 class EventMessageOperation : public Operation 1012 { 1013 public: 1014 EventMessageOperation(lldb::tid_t tid, unsigned long *message) 1015 : m_tid(tid), m_message(message) { } 1016 1017 void Execute(NativeProcessLinux *monitor) override; 1018 1019 private: 1020 lldb::tid_t m_tid; 1021 unsigned long *m_message; 1022 }; 1023 1024 void 1025 EventMessageOperation::Execute(NativeProcessLinux *monitor) 1026 { 1027 PTRACE(PTRACE_GETEVENTMSG, m_tid, nullptr, m_message, 0, m_error); 1028 } 1029 1030 class DetachOperation : public Operation 1031 { 1032 public: 1033 DetachOperation(lldb::tid_t tid) : m_tid(tid) { } 1034 1035 void Execute(NativeProcessLinux *monitor) override; 1036 1037 private: 1038 lldb::tid_t m_tid; 1039 }; 1040 1041 void 1042 DetachOperation::Execute(NativeProcessLinux *monitor) 1043 { 1044 PTRACE(PTRACE_DETACH, m_tid, nullptr, 0, 0, m_error); 1045 } 1046 } // end of anonymous namespace 1047 1048 // Simple helper function to ensure flags are enabled on the given file 1049 // descriptor. 1050 static Error 1051 EnsureFDFlags(int fd, int flags) 1052 { 1053 Error error; 1054 1055 int status = fcntl(fd, F_GETFL); 1056 if (status == -1) 1057 { 1058 error.SetErrorToErrno(); 1059 return error; 1060 } 1061 1062 if (fcntl(fd, F_SETFL, status | flags) == -1) 1063 { 1064 error.SetErrorToErrno(); 1065 return error; 1066 } 1067 1068 return error; 1069 } 1070 1071 // This class encapsulates the privileged thread which performs all ptrace and wait operations on 1072 // the inferior. The thread consists of a main loop which waits for events and processes them 1073 // - SIGCHLD (delivered over a signalfd file descriptor): These signals notify us of events in 1074 // the inferior process. Upon receiving this signal we do a waitpid to get more information 1075 // and dispatch to NativeProcessLinux::MonitorCallback. 1076 // - requests for ptrace operations: These initiated via the DoOperation method, which funnels 1077 // them to the Monitor thread via m_operation member. The Monitor thread is signaled over a 1078 // pipe, and the completion of the operation is signalled over the semaphore. 1079 // - thread exit event: this is signaled from the Monitor destructor by closing the write end 1080 // of the command pipe. 1081 class NativeProcessLinux::Monitor 1082 { 1083 private: 1084 // The initial monitor operation (launch or attach). It returns a inferior process id. 1085 std::unique_ptr<InitialOperation> m_initial_operation_up; 1086 1087 ::pid_t m_child_pid = -1; 1088 NativeProcessLinux * m_native_process; 1089 1090 enum { READ, WRITE }; 1091 int m_pipefd[2] = {-1, -1}; 1092 int m_signal_fd = -1; 1093 HostThread m_thread; 1094 1095 // current operation which must be executed on the priviliged thread 1096 Mutex m_operation_mutex; 1097 Operation *m_operation = nullptr; 1098 sem_t m_operation_sem; 1099 Error m_operation_error; 1100 1101 unsigned m_operation_nesting_level = 0; 1102 1103 static constexpr char operation_command = 'o'; 1104 static constexpr char begin_block_command = '{'; 1105 static constexpr char end_block_command = '}'; 1106 1107 void 1108 HandleSignals(); 1109 1110 void 1111 HandleWait(); 1112 1113 // Returns true if the thread should exit. 1114 bool 1115 HandleCommands(); 1116 1117 void 1118 MainLoop(); 1119 1120 static void * 1121 RunMonitor(void *arg); 1122 1123 Error 1124 WaitForAck(); 1125 1126 void 1127 BeginOperationBlock() 1128 { 1129 write(m_pipefd[WRITE], &begin_block_command, sizeof operation_command); 1130 WaitForAck(); 1131 } 1132 1133 void 1134 EndOperationBlock() 1135 { 1136 write(m_pipefd[WRITE], &end_block_command, sizeof operation_command); 1137 WaitForAck(); 1138 } 1139 1140 public: 1141 Monitor(const InitialOperation &initial_operation, 1142 NativeProcessLinux *native_process) 1143 : m_initial_operation_up(new InitialOperation(initial_operation)), 1144 m_native_process(native_process) 1145 { 1146 sem_init(&m_operation_sem, 0, 0); 1147 } 1148 1149 ~Monitor(); 1150 1151 Error 1152 Initialize(); 1153 1154 void 1155 Terminate(); 1156 1157 void 1158 DoOperation(Operation *op); 1159 1160 class ScopedOperationLock { 1161 Monitor &m_monitor; 1162 1163 public: 1164 ScopedOperationLock(Monitor &monitor) 1165 : m_monitor(monitor) 1166 { m_monitor.BeginOperationBlock(); } 1167 1168 ~ScopedOperationLock() 1169 { m_monitor.EndOperationBlock(); } 1170 }; 1171 }; 1172 constexpr char NativeProcessLinux::Monitor::operation_command; 1173 constexpr char NativeProcessLinux::Monitor::begin_block_command; 1174 constexpr char NativeProcessLinux::Monitor::end_block_command; 1175 1176 Error 1177 NativeProcessLinux::Monitor::Initialize() 1178 { 1179 Error error; 1180 1181 // We get a SIGCHLD every time something interesting happens with the inferior. We shall be 1182 // listening for these signals over a signalfd file descriptors. This allows us to wait for 1183 // multiple kinds of events with select. 1184 sigset_t signals; 1185 sigemptyset(&signals); 1186 sigaddset(&signals, SIGCHLD); 1187 m_signal_fd = signalfd(-1, &signals, SFD_NONBLOCK | SFD_CLOEXEC); 1188 if (m_signal_fd < 0) 1189 { 1190 return Error("NativeProcessLinux::Monitor::%s failed due to signalfd failure. Monitoring the inferior will be impossible: %s", 1191 __FUNCTION__, strerror(errno)); 1192 1193 } 1194 1195 if (pipe2(m_pipefd, O_CLOEXEC) == -1) 1196 { 1197 error.SetErrorToErrno(); 1198 return error; 1199 } 1200 1201 if ((error = EnsureFDFlags(m_pipefd[READ], O_NONBLOCK)).Fail()) { 1202 return error; 1203 } 1204 1205 static const char g_thread_name[] = "lldb.process.nativelinux.monitor"; 1206 m_thread = ThreadLauncher::LaunchThread(g_thread_name, Monitor::RunMonitor, this, nullptr); 1207 if (!m_thread.IsJoinable()) 1208 return Error("Failed to create monitor thread for NativeProcessLinux."); 1209 1210 // Wait for initial operation to complete. 1211 return WaitForAck(); 1212 } 1213 1214 void 1215 NativeProcessLinux::Monitor::DoOperation(Operation *op) 1216 { 1217 if (m_thread.EqualsThread(pthread_self())) { 1218 // If we're on the Monitor thread, we can simply execute the operation. 1219 op->Execute(m_native_process); 1220 return; 1221 } 1222 1223 // Otherwise we need to pass the operation to the Monitor thread so it can handle it. 1224 Mutex::Locker lock(m_operation_mutex); 1225 1226 m_operation = op; 1227 1228 // notify the thread that an operation is ready to be processed 1229 write(m_pipefd[WRITE], &operation_command, sizeof operation_command); 1230 1231 WaitForAck(); 1232 } 1233 1234 void 1235 NativeProcessLinux::Monitor::Terminate() 1236 { 1237 if (m_pipefd[WRITE] >= 0) 1238 { 1239 close(m_pipefd[WRITE]); 1240 m_pipefd[WRITE] = -1; 1241 } 1242 if (m_thread.IsJoinable()) 1243 m_thread.Join(nullptr); 1244 } 1245 1246 NativeProcessLinux::Monitor::~Monitor() 1247 { 1248 Terminate(); 1249 if (m_pipefd[READ] >= 0) 1250 close(m_pipefd[READ]); 1251 if (m_signal_fd >= 0) 1252 close(m_signal_fd); 1253 sem_destroy(&m_operation_sem); 1254 } 1255 1256 void 1257 NativeProcessLinux::Monitor::HandleSignals() 1258 { 1259 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1260 1261 // We don't really care about the content of the SIGCHLD siginfo structure, as we will get 1262 // all the information from waitpid(). We just need to read all the signals so that we can 1263 // sleep next time we reach select(). 1264 while (true) 1265 { 1266 signalfd_siginfo info; 1267 ssize_t size = read(m_signal_fd, &info, sizeof info); 1268 if (size == -1) 1269 { 1270 if (errno == EAGAIN || errno == EWOULDBLOCK) 1271 break; // We are done. 1272 if (errno == EINTR) 1273 continue; 1274 if (log) 1275 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor failed: %s", 1276 __FUNCTION__, strerror(errno)); 1277 break; 1278 } 1279 if (size != sizeof info) 1280 { 1281 // We got incomplete information structure. This should not happen, let's just log 1282 // that. 1283 if (log) 1284 log->Printf("NativeProcessLinux::Monitor::%s reading from signalfd file descriptor returned incomplete data: " 1285 "structure size is %zd, read returned %zd bytes", 1286 __FUNCTION__, sizeof info, size); 1287 break; 1288 } 1289 if (log) 1290 log->Printf("NativeProcessLinux::Monitor::%s received signal %s(%d).", __FUNCTION__, 1291 Host::GetSignalAsCString(info.ssi_signo), info.ssi_signo); 1292 } 1293 } 1294 1295 void 1296 NativeProcessLinux::Monitor::HandleWait() 1297 { 1298 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1299 // Process all pending waitpid notifications. 1300 while (true) 1301 { 1302 int status = -1; 1303 ::pid_t wait_pid = waitpid(m_child_pid, &status, __WALL | WNOHANG); 1304 1305 if (wait_pid == 0) 1306 break; // We are done. 1307 1308 if (wait_pid == -1) 1309 { 1310 if (errno == EINTR) 1311 continue; 1312 1313 if (log) 1314 log->Printf("NativeProcessLinux::Monitor::%s waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG) failed: %s", 1315 __FUNCTION__, m_child_pid, strerror(errno)); 1316 break; 1317 } 1318 1319 bool exited = false; 1320 int signal = 0; 1321 int exit_status = 0; 1322 const char *status_cstr = NULL; 1323 if (WIFSTOPPED(status)) 1324 { 1325 signal = WSTOPSIG(status); 1326 status_cstr = "STOPPED"; 1327 } 1328 else if (WIFEXITED(status)) 1329 { 1330 exit_status = WEXITSTATUS(status); 1331 status_cstr = "EXITED"; 1332 exited = true; 1333 } 1334 else if (WIFSIGNALED(status)) 1335 { 1336 signal = WTERMSIG(status); 1337 status_cstr = "SIGNALED"; 1338 if (wait_pid == abs(m_child_pid)) { 1339 exited = true; 1340 exit_status = -1; 1341 } 1342 } 1343 else 1344 status_cstr = "(\?\?\?)"; 1345 1346 if (log) 1347 log->Printf("NativeProcessLinux::Monitor::%s: waitpid (pid = %" PRIi32 ", &status, __WALL | WNOHANG)" 1348 "=> pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i", 1349 __FUNCTION__, m_child_pid, wait_pid, status, status_cstr, signal, exit_status); 1350 1351 m_native_process->MonitorCallback (wait_pid, exited, signal, exit_status); 1352 } 1353 } 1354 1355 bool 1356 NativeProcessLinux::Monitor::HandleCommands() 1357 { 1358 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1359 1360 while (true) 1361 { 1362 char command = 0; 1363 ssize_t size = read(m_pipefd[READ], &command, sizeof command); 1364 if (size == -1) 1365 { 1366 if (errno == EAGAIN || errno == EWOULDBLOCK) 1367 return false; 1368 if (errno == EINTR) 1369 continue; 1370 if (log) 1371 log->Printf("NativeProcessLinux::Monitor::%s exiting because read from command file descriptor failed: %s", __FUNCTION__, strerror(errno)); 1372 return true; 1373 } 1374 if (size == 0) // end of file - write end closed 1375 { 1376 if (log) 1377 log->Printf("NativeProcessLinux::Monitor::%s exit command received, exiting...", __FUNCTION__); 1378 assert(m_operation_nesting_level == 0 && "Unbalanced begin/end block commands detected"); 1379 return true; // We are done. 1380 } 1381 1382 switch (command) 1383 { 1384 case operation_command: 1385 m_operation->Execute(m_native_process); 1386 break; 1387 case begin_block_command: 1388 ++m_operation_nesting_level; 1389 break; 1390 case end_block_command: 1391 assert(m_operation_nesting_level > 0); 1392 --m_operation_nesting_level; 1393 break; 1394 default: 1395 if (log) 1396 log->Printf("NativeProcessLinux::Monitor::%s received unknown command '%c'", 1397 __FUNCTION__, command); 1398 } 1399 1400 // notify calling thread that the command has been processed 1401 sem_post(&m_operation_sem); 1402 } 1403 } 1404 1405 void 1406 NativeProcessLinux::Monitor::MainLoop() 1407 { 1408 ::pid_t child_pid = (*m_initial_operation_up)(m_operation_error); 1409 m_initial_operation_up.reset(); 1410 m_child_pid = -getpgid(child_pid), 1411 sem_post(&m_operation_sem); 1412 1413 while (true) 1414 { 1415 fd_set fds; 1416 FD_ZERO(&fds); 1417 // Only process waitpid events if we are outside of an operation block. Any pending 1418 // events will be processed after we leave the block. 1419 if (m_operation_nesting_level == 0) 1420 FD_SET(m_signal_fd, &fds); 1421 FD_SET(m_pipefd[READ], &fds); 1422 1423 int max_fd = std::max(m_signal_fd, m_pipefd[READ]) + 1; 1424 int r = select(max_fd, &fds, nullptr, nullptr, nullptr); 1425 if (r < 0) 1426 { 1427 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 1428 if (log) 1429 log->Printf("NativeProcessLinux::Monitor::%s exiting because select failed: %s", 1430 __FUNCTION__, strerror(errno)); 1431 return; 1432 } 1433 1434 if (FD_ISSET(m_pipefd[READ], &fds)) 1435 { 1436 if (HandleCommands()) 1437 return; 1438 } 1439 1440 if (FD_ISSET(m_signal_fd, &fds)) 1441 { 1442 HandleSignals(); 1443 HandleWait(); 1444 } 1445 } 1446 } 1447 1448 Error 1449 NativeProcessLinux::Monitor::WaitForAck() 1450 { 1451 Error error; 1452 while (sem_wait(&m_operation_sem) != 0) 1453 { 1454 if (errno == EINTR) 1455 continue; 1456 1457 error.SetErrorToErrno(); 1458 return error; 1459 } 1460 1461 return m_operation_error; 1462 } 1463 1464 void * 1465 NativeProcessLinux::Monitor::RunMonitor(void *arg) 1466 { 1467 static_cast<Monitor *>(arg)->MainLoop(); 1468 return nullptr; 1469 } 1470 1471 1472 NativeProcessLinux::LaunchArgs::LaunchArgs(Module *module, 1473 char const **argv, 1474 char const **envp, 1475 const std::string &stdin_path, 1476 const std::string &stdout_path, 1477 const std::string &stderr_path, 1478 const char *working_dir, 1479 const ProcessLaunchInfo &launch_info) 1480 : m_module(module), 1481 m_argv(argv), 1482 m_envp(envp), 1483 m_stdin_path(stdin_path), 1484 m_stdout_path(stdout_path), 1485 m_stderr_path(stderr_path), 1486 m_working_dir(working_dir), 1487 m_launch_info(launch_info) 1488 { 1489 } 1490 1491 NativeProcessLinux::LaunchArgs::~LaunchArgs() 1492 { } 1493 1494 // ----------------------------------------------------------------------------- 1495 // Public Static Methods 1496 // ----------------------------------------------------------------------------- 1497 1498 Error 1499 NativeProcessLinux::LaunchProcess ( 1500 Module *exe_module, 1501 ProcessLaunchInfo &launch_info, 1502 NativeProcessProtocol::NativeDelegate &native_delegate, 1503 NativeProcessProtocolSP &native_process_sp) 1504 { 1505 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1506 1507 Error error; 1508 1509 // Verify the working directory is valid if one was specified. 1510 const char* working_dir = launch_info.GetWorkingDirectory (); 1511 if (working_dir) 1512 { 1513 FileSpec working_dir_fs (working_dir, true); 1514 if (!working_dir_fs || working_dir_fs.GetFileType () != FileSpec::eFileTypeDirectory) 1515 { 1516 error.SetErrorStringWithFormat ("No such file or directory: %s", working_dir); 1517 return error; 1518 } 1519 } 1520 1521 const FileAction *file_action; 1522 1523 // Default of NULL will mean to use existing open file descriptors. 1524 std::string stdin_path; 1525 std::string stdout_path; 1526 std::string stderr_path; 1527 1528 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 1529 if (file_action) 1530 stdin_path = file_action->GetPath (); 1531 1532 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 1533 if (file_action) 1534 stdout_path = file_action->GetPath (); 1535 1536 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 1537 if (file_action) 1538 stderr_path = file_action->GetPath (); 1539 1540 if (log) 1541 { 1542 if (!stdin_path.empty ()) 1543 log->Printf ("NativeProcessLinux::%s setting STDIN to '%s'", __FUNCTION__, stdin_path.c_str ()); 1544 else 1545 log->Printf ("NativeProcessLinux::%s leaving STDIN as is", __FUNCTION__); 1546 1547 if (!stdout_path.empty ()) 1548 log->Printf ("NativeProcessLinux::%s setting STDOUT to '%s'", __FUNCTION__, stdout_path.c_str ()); 1549 else 1550 log->Printf ("NativeProcessLinux::%s leaving STDOUT as is", __FUNCTION__); 1551 1552 if (!stderr_path.empty ()) 1553 log->Printf ("NativeProcessLinux::%s setting STDERR to '%s'", __FUNCTION__, stderr_path.c_str ()); 1554 else 1555 log->Printf ("NativeProcessLinux::%s leaving STDERR as is", __FUNCTION__); 1556 } 1557 1558 // Create the NativeProcessLinux in launch mode. 1559 native_process_sp.reset (new NativeProcessLinux ()); 1560 1561 if (log) 1562 { 1563 int i = 0; 1564 for (const char **args = launch_info.GetArguments ().GetConstArgumentVector (); *args; ++args, ++i) 1565 { 1566 log->Printf ("NativeProcessLinux::%s arg %d: \"%s\"", __FUNCTION__, i, *args ? *args : "nullptr"); 1567 ++i; 1568 } 1569 } 1570 1571 if (!native_process_sp->RegisterNativeDelegate (native_delegate)) 1572 { 1573 native_process_sp.reset (); 1574 error.SetErrorStringWithFormat ("failed to register the native delegate"); 1575 return error; 1576 } 1577 1578 std::static_pointer_cast<NativeProcessLinux> (native_process_sp)->LaunchInferior ( 1579 exe_module, 1580 launch_info.GetArguments ().GetConstArgumentVector (), 1581 launch_info.GetEnvironmentEntries ().GetConstArgumentVector (), 1582 stdin_path, 1583 stdout_path, 1584 stderr_path, 1585 working_dir, 1586 launch_info, 1587 error); 1588 1589 if (error.Fail ()) 1590 { 1591 native_process_sp.reset (); 1592 if (log) 1593 log->Printf ("NativeProcessLinux::%s failed to launch process: %s", __FUNCTION__, error.AsCString ()); 1594 return error; 1595 } 1596 1597 launch_info.SetProcessID (native_process_sp->GetID ()); 1598 1599 return error; 1600 } 1601 1602 Error 1603 NativeProcessLinux::AttachToProcess ( 1604 lldb::pid_t pid, 1605 NativeProcessProtocol::NativeDelegate &native_delegate, 1606 NativeProcessProtocolSP &native_process_sp) 1607 { 1608 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1609 if (log && log->GetMask ().Test (POSIX_LOG_VERBOSE)) 1610 log->Printf ("NativeProcessLinux::%s(pid = %" PRIi64 ")", __FUNCTION__, pid); 1611 1612 // Grab the current platform architecture. This should be Linux, 1613 // since this code is only intended to run on a Linux host. 1614 PlatformSP platform_sp (Platform::GetHostPlatform ()); 1615 if (!platform_sp) 1616 return Error("failed to get a valid default platform"); 1617 1618 // Retrieve the architecture for the running process. 1619 ArchSpec process_arch; 1620 Error error = ResolveProcessArchitecture (pid, *platform_sp.get (), process_arch); 1621 if (!error.Success ()) 1622 return error; 1623 1624 std::shared_ptr<NativeProcessLinux> native_process_linux_sp (new NativeProcessLinux ()); 1625 1626 if (!native_process_linux_sp->RegisterNativeDelegate (native_delegate)) 1627 { 1628 error.SetErrorStringWithFormat ("failed to register the native delegate"); 1629 return error; 1630 } 1631 1632 native_process_linux_sp->AttachToInferior (pid, error); 1633 if (!error.Success ()) 1634 return error; 1635 1636 native_process_sp = native_process_linux_sp; 1637 return error; 1638 } 1639 1640 // ----------------------------------------------------------------------------- 1641 // Public Instance Methods 1642 // ----------------------------------------------------------------------------- 1643 1644 NativeProcessLinux::NativeProcessLinux () : 1645 NativeProcessProtocol (LLDB_INVALID_PROCESS_ID), 1646 m_arch (), 1647 m_supports_mem_region (eLazyBoolCalculate), 1648 m_mem_region_cache (), 1649 m_mem_region_cache_mutex () 1650 { 1651 } 1652 1653 //------------------------------------------------------------------------------ 1654 // NativeProcessLinux spawns a new thread which performs all operations on the inferior process. 1655 // Refer to Monitor and Operation classes to see why this is necessary. 1656 //------------------------------------------------------------------------------ 1657 void 1658 NativeProcessLinux::LaunchInferior ( 1659 Module *module, 1660 const char *argv[], 1661 const char *envp[], 1662 const std::string &stdin_path, 1663 const std::string &stdout_path, 1664 const std::string &stderr_path, 1665 const char *working_dir, 1666 const ProcessLaunchInfo &launch_info, 1667 Error &error) 1668 { 1669 if (module) 1670 m_arch = module->GetArchitecture (); 1671 1672 SetState (eStateLaunching); 1673 1674 std::unique_ptr<LaunchArgs> args( 1675 new LaunchArgs( 1676 module, argv, envp, 1677 stdin_path, stdout_path, stderr_path, 1678 working_dir, launch_info)); 1679 1680 StartMonitorThread ([&] (Error &e) { return Launch(args.get(), e); }, error); 1681 if (!error.Success ()) 1682 return; 1683 } 1684 1685 void 1686 NativeProcessLinux::AttachToInferior (lldb::pid_t pid, Error &error) 1687 { 1688 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1689 if (log) 1690 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ")", __FUNCTION__, pid); 1691 1692 // We can use the Host for everything except the ResolveExecutable portion. 1693 PlatformSP platform_sp = Platform::GetHostPlatform (); 1694 if (!platform_sp) 1695 { 1696 if (log) 1697 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): no default platform set", __FUNCTION__, pid); 1698 error.SetErrorString ("no default platform available"); 1699 return; 1700 } 1701 1702 // Gather info about the process. 1703 ProcessInstanceInfo process_info; 1704 if (!platform_sp->GetProcessInfo (pid, process_info)) 1705 { 1706 if (log) 1707 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 "): failed to get process info", __FUNCTION__, pid); 1708 error.SetErrorString ("failed to get process info"); 1709 return; 1710 } 1711 1712 // Resolve the executable module 1713 ModuleSP exe_module_sp; 1714 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths()); 1715 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), process_info.GetArchitecture()); 1716 error = platform_sp->ResolveExecutable(exe_module_spec, exe_module_sp, 1717 executable_search_paths.GetSize() ? &executable_search_paths : NULL); 1718 if (!error.Success()) 1719 return; 1720 1721 // Set the architecture to the exe architecture. 1722 m_arch = exe_module_sp->GetArchitecture(); 1723 if (log) 1724 log->Printf ("NativeProcessLinux::%s (pid = %" PRIi64 ") detected architecture %s", __FUNCTION__, pid, m_arch.GetArchitectureName ()); 1725 1726 m_pid = pid; 1727 SetState(eStateAttaching); 1728 1729 StartMonitorThread ([=] (Error &e) { return Attach(pid, e); }, error); 1730 if (!error.Success ()) 1731 return; 1732 } 1733 1734 void 1735 NativeProcessLinux::Terminate () 1736 { 1737 m_monitor_up->Terminate(); 1738 } 1739 1740 ::pid_t 1741 NativeProcessLinux::Launch(LaunchArgs *args, Error &error) 1742 { 1743 assert (args && "null args"); 1744 1745 const char **argv = args->m_argv; 1746 const char **envp = args->m_envp; 1747 const char *working_dir = args->m_working_dir; 1748 1749 lldb_utility::PseudoTerminal terminal; 1750 const size_t err_len = 1024; 1751 char err_str[err_len]; 1752 lldb::pid_t pid; 1753 NativeThreadProtocolSP thread_sp; 1754 1755 lldb::ThreadSP inferior; 1756 1757 // Propagate the environment if one is not supplied. 1758 if (envp == NULL || envp[0] == NULL) 1759 envp = const_cast<const char **>(environ); 1760 1761 if ((pid = terminal.Fork(err_str, err_len)) == static_cast<lldb::pid_t> (-1)) 1762 { 1763 error.SetErrorToGenericError(); 1764 error.SetErrorStringWithFormat("Process fork failed: %s", err_str); 1765 return -1; 1766 } 1767 1768 // Recognized child exit status codes. 1769 enum { 1770 ePtraceFailed = 1, 1771 eDupStdinFailed, 1772 eDupStdoutFailed, 1773 eDupStderrFailed, 1774 eChdirFailed, 1775 eExecFailed, 1776 eSetGidFailed 1777 }; 1778 1779 // Child process. 1780 if (pid == 0) 1781 { 1782 // FIXME consider opening a pipe between parent/child and have this forked child 1783 // send log info to parent re: launch status, in place of the log lines removed here. 1784 1785 // Start tracing this child that is about to exec. 1786 PTRACE(PTRACE_TRACEME, 0, nullptr, nullptr, 0, error); 1787 if (error.Fail()) 1788 exit(ePtraceFailed); 1789 1790 // terminal has already dupped the tty descriptors to stdin/out/err. 1791 // This closes original fd from which they were copied (and avoids 1792 // leaking descriptors to the debugged process. 1793 terminal.CloseSlaveFileDescriptor(); 1794 1795 // Do not inherit setgid powers. 1796 if (setgid(getgid()) != 0) 1797 exit(eSetGidFailed); 1798 1799 // Attempt to have our own process group. 1800 if (setpgid(0, 0) != 0) 1801 { 1802 // FIXME log that this failed. This is common. 1803 // Don't allow this to prevent an inferior exec. 1804 } 1805 1806 // Dup file descriptors if needed. 1807 if (!args->m_stdin_path.empty ()) 1808 if (!DupDescriptor(args->m_stdin_path.c_str (), STDIN_FILENO, O_RDONLY)) 1809 exit(eDupStdinFailed); 1810 1811 if (!args->m_stdout_path.empty ()) 1812 if (!DupDescriptor(args->m_stdout_path.c_str (), STDOUT_FILENO, O_WRONLY | O_CREAT | O_TRUNC)) 1813 exit(eDupStdoutFailed); 1814 1815 if (!args->m_stderr_path.empty ()) 1816 if (!DupDescriptor(args->m_stderr_path.c_str (), STDERR_FILENO, O_WRONLY | O_CREAT | O_TRUNC)) 1817 exit(eDupStderrFailed); 1818 1819 // Close everything besides stdin, stdout, and stderr that has no file 1820 // action to avoid leaking 1821 for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd) 1822 if (!args->m_launch_info.GetFileActionForFD(fd)) 1823 close(fd); 1824 1825 // Change working directory 1826 if (working_dir != NULL && working_dir[0]) 1827 if (0 != ::chdir(working_dir)) 1828 exit(eChdirFailed); 1829 1830 // Disable ASLR if requested. 1831 if (args->m_launch_info.GetFlags ().Test (lldb::eLaunchFlagDisableASLR)) 1832 { 1833 const int old_personality = personality (LLDB_PERSONALITY_GET_CURRENT_SETTINGS); 1834 if (old_personality == -1) 1835 { 1836 // Can't retrieve Linux personality. Cannot disable ASLR. 1837 } 1838 else 1839 { 1840 const int new_personality = personality (ADDR_NO_RANDOMIZE | old_personality); 1841 if (new_personality == -1) 1842 { 1843 // Disabling ASLR failed. 1844 } 1845 else 1846 { 1847 // Disabling ASLR succeeded. 1848 } 1849 } 1850 } 1851 1852 // Execute. We should never return... 1853 execve(argv[0], 1854 const_cast<char *const *>(argv), 1855 const_cast<char *const *>(envp)); 1856 1857 // ...unless exec fails. In which case we definitely need to end the child here. 1858 exit(eExecFailed); 1859 } 1860 1861 // 1862 // This is the parent code here. 1863 // 1864 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 1865 1866 // Wait for the child process to trap on its call to execve. 1867 ::pid_t wpid; 1868 int status; 1869 if ((wpid = waitpid(pid, &status, 0)) < 0) 1870 { 1871 error.SetErrorToErrno(); 1872 if (log) 1873 log->Printf ("NativeProcessLinux::%s waitpid for inferior failed with %s", 1874 __FUNCTION__, error.AsCString ()); 1875 1876 // Mark the inferior as invalid. 1877 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1878 SetState (StateType::eStateInvalid); 1879 1880 return -1; 1881 } 1882 else if (WIFEXITED(status)) 1883 { 1884 // open, dup or execve likely failed for some reason. 1885 error.SetErrorToGenericError(); 1886 switch (WEXITSTATUS(status)) 1887 { 1888 case ePtraceFailed: 1889 error.SetErrorString("Child ptrace failed."); 1890 break; 1891 case eDupStdinFailed: 1892 error.SetErrorString("Child open stdin failed."); 1893 break; 1894 case eDupStdoutFailed: 1895 error.SetErrorString("Child open stdout failed."); 1896 break; 1897 case eDupStderrFailed: 1898 error.SetErrorString("Child open stderr failed."); 1899 break; 1900 case eChdirFailed: 1901 error.SetErrorString("Child failed to set working directory."); 1902 break; 1903 case eExecFailed: 1904 error.SetErrorString("Child exec failed."); 1905 break; 1906 case eSetGidFailed: 1907 error.SetErrorString("Child setgid failed."); 1908 break; 1909 default: 1910 error.SetErrorString("Child returned unknown exit status."); 1911 break; 1912 } 1913 1914 if (log) 1915 { 1916 log->Printf ("NativeProcessLinux::%s inferior exited with status %d before issuing a STOP", 1917 __FUNCTION__, 1918 WEXITSTATUS(status)); 1919 } 1920 1921 // Mark the inferior as invalid. 1922 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1923 SetState (StateType::eStateInvalid); 1924 1925 return -1; 1926 } 1927 assert(WIFSTOPPED(status) && (wpid == static_cast< ::pid_t> (pid)) && 1928 "Could not sync with inferior process."); 1929 1930 if (log) 1931 log->Printf ("NativeProcessLinux::%s inferior started, now in stopped state", __FUNCTION__); 1932 1933 error = SetDefaultPtraceOpts(pid); 1934 if (error.Fail()) 1935 { 1936 if (log) 1937 log->Printf ("NativeProcessLinux::%s inferior failed to set default ptrace options: %s", 1938 __FUNCTION__, error.AsCString ()); 1939 1940 // Mark the inferior as invalid. 1941 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1942 SetState (StateType::eStateInvalid); 1943 1944 return -1; 1945 } 1946 1947 // Release the master terminal descriptor and pass it off to the 1948 // NativeProcessLinux instance. Similarly stash the inferior pid. 1949 m_terminal_fd = terminal.ReleaseMasterFileDescriptor(); 1950 m_pid = pid; 1951 1952 // Set the terminal fd to be in non blocking mode (it simplifies the 1953 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking 1954 // descriptor to read from). 1955 error = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 1956 if (error.Fail()) 1957 { 1958 if (log) 1959 log->Printf ("NativeProcessLinux::%s inferior EnsureFDFlags failed for ensuring terminal O_NONBLOCK setting: %s", 1960 __FUNCTION__, error.AsCString ()); 1961 1962 // Mark the inferior as invalid. 1963 // FIXME this could really use a new state - eStateLaunchFailure. For now, using eStateInvalid. 1964 SetState (StateType::eStateInvalid); 1965 1966 return -1; 1967 } 1968 1969 if (log) 1970 log->Printf ("NativeProcessLinux::%s() adding pid = %" PRIu64, __FUNCTION__, pid); 1971 1972 thread_sp = AddThread (pid); 1973 assert (thread_sp && "AddThread() returned a nullptr thread"); 1974 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP); 1975 NotifyThreadCreate(pid); 1976 1977 // Let our process instance know the thread has stopped. 1978 SetCurrentThreadID (thread_sp->GetID ()); 1979 SetState (StateType::eStateStopped); 1980 1981 if (log) 1982 { 1983 if (error.Success ()) 1984 { 1985 log->Printf ("NativeProcessLinux::%s inferior launching succeeded", __FUNCTION__); 1986 } 1987 else 1988 { 1989 log->Printf ("NativeProcessLinux::%s inferior launching failed: %s", 1990 __FUNCTION__, error.AsCString ()); 1991 return -1; 1992 } 1993 } 1994 return pid; 1995 } 1996 1997 ::pid_t 1998 NativeProcessLinux::Attach(lldb::pid_t pid, Error &error) 1999 { 2000 lldb::ThreadSP inferior; 2001 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2002 2003 // Use a map to keep track of the threads which we have attached/need to attach. 2004 Host::TidMap tids_to_attach; 2005 if (pid <= 1) 2006 { 2007 error.SetErrorToGenericError(); 2008 error.SetErrorString("Attaching to process 1 is not allowed."); 2009 return -1; 2010 } 2011 2012 while (Host::FindProcessThreads(pid, tids_to_attach)) 2013 { 2014 for (Host::TidMap::iterator it = tids_to_attach.begin(); 2015 it != tids_to_attach.end();) 2016 { 2017 if (it->second == false) 2018 { 2019 lldb::tid_t tid = it->first; 2020 2021 // Attach to the requested process. 2022 // An attach will cause the thread to stop with a SIGSTOP. 2023 PTRACE(PTRACE_ATTACH, tid, nullptr, nullptr, 0, error); 2024 if (error.Fail()) 2025 { 2026 // No such thread. The thread may have exited. 2027 // More error handling may be needed. 2028 if (error.GetError() == ESRCH) 2029 { 2030 it = tids_to_attach.erase(it); 2031 continue; 2032 } 2033 else 2034 return -1; 2035 } 2036 2037 int status; 2038 // Need to use __WALL otherwise we receive an error with errno=ECHLD 2039 // At this point we should have a thread stopped if waitpid succeeds. 2040 if ((status = waitpid(tid, NULL, __WALL)) < 0) 2041 { 2042 // No such thread. The thread may have exited. 2043 // More error handling may be needed. 2044 if (errno == ESRCH) 2045 { 2046 it = tids_to_attach.erase(it); 2047 continue; 2048 } 2049 else 2050 { 2051 error.SetErrorToErrno(); 2052 return -1; 2053 } 2054 } 2055 2056 error = SetDefaultPtraceOpts(tid); 2057 if (error.Fail()) 2058 return -1; 2059 2060 if (log) 2061 log->Printf ("NativeProcessLinux::%s() adding tid = %" PRIu64, __FUNCTION__, tid); 2062 2063 it->second = true; 2064 2065 // Create the thread, mark it as stopped. 2066 NativeThreadProtocolSP thread_sp (AddThread (static_cast<lldb::tid_t> (tid))); 2067 assert (thread_sp && "AddThread() returned a nullptr"); 2068 2069 // This will notify this is a new thread and tell the system it is stopped. 2070 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGSTOP); 2071 NotifyThreadCreate(tid); 2072 SetCurrentThreadID (thread_sp->GetID ()); 2073 } 2074 2075 // move the loop forward 2076 ++it; 2077 } 2078 } 2079 2080 if (tids_to_attach.size() > 0) 2081 { 2082 m_pid = pid; 2083 // Let our process instance know the thread has stopped. 2084 SetState (StateType::eStateStopped); 2085 } 2086 else 2087 { 2088 error.SetErrorToGenericError(); 2089 error.SetErrorString("No such process."); 2090 return -1; 2091 } 2092 2093 return pid; 2094 } 2095 2096 Error 2097 NativeProcessLinux::SetDefaultPtraceOpts(lldb::pid_t pid) 2098 { 2099 long ptrace_opts = 0; 2100 2101 // Have the child raise an event on exit. This is used to keep the child in 2102 // limbo until it is destroyed. 2103 ptrace_opts |= PTRACE_O_TRACEEXIT; 2104 2105 // Have the tracer trace threads which spawn in the inferior process. 2106 // TODO: if we want to support tracing the inferiors' child, add the 2107 // appropriate ptrace flags here (PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK) 2108 ptrace_opts |= PTRACE_O_TRACECLONE; 2109 2110 // Have the tracer notify us before execve returns 2111 // (needed to disable legacy SIGTRAP generation) 2112 ptrace_opts |= PTRACE_O_TRACEEXEC; 2113 2114 Error error; 2115 PTRACE(PTRACE_SETOPTIONS, pid, nullptr, (void*)ptrace_opts, 0, error); 2116 return error; 2117 } 2118 2119 static ExitType convert_pid_status_to_exit_type (int status) 2120 { 2121 if (WIFEXITED (status)) 2122 return ExitType::eExitTypeExit; 2123 else if (WIFSIGNALED (status)) 2124 return ExitType::eExitTypeSignal; 2125 else if (WIFSTOPPED (status)) 2126 return ExitType::eExitTypeStop; 2127 else 2128 { 2129 // We don't know what this is. 2130 return ExitType::eExitTypeInvalid; 2131 } 2132 } 2133 2134 static int convert_pid_status_to_return_code (int status) 2135 { 2136 if (WIFEXITED (status)) 2137 return WEXITSTATUS (status); 2138 else if (WIFSIGNALED (status)) 2139 return WTERMSIG (status); 2140 else if (WIFSTOPPED (status)) 2141 return WSTOPSIG (status); 2142 else 2143 { 2144 // We don't know what this is. 2145 return ExitType::eExitTypeInvalid; 2146 } 2147 } 2148 2149 // Handles all waitpid events from the inferior process. 2150 void 2151 NativeProcessLinux::MonitorCallback(lldb::pid_t pid, 2152 bool exited, 2153 int signal, 2154 int status) 2155 { 2156 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS)); 2157 2158 // Certain activities differ based on whether the pid is the tid of the main thread. 2159 const bool is_main_thread = (pid == GetID ()); 2160 2161 // Handle when the thread exits. 2162 if (exited) 2163 { 2164 if (log) 2165 log->Printf ("NativeProcessLinux::%s() got exit signal(%d) , tid = %" PRIu64 " (%s main thread)", __FUNCTION__, signal, pid, is_main_thread ? "is" : "is not"); 2166 2167 // This is a thread that exited. Ensure we're not tracking it anymore. 2168 const bool thread_found = StopTrackingThread (pid); 2169 2170 // Make sure the thread state coordinator knows about this. 2171 NotifyThreadDeath (pid); 2172 2173 if (is_main_thread) 2174 { 2175 // We only set the exit status and notify the delegate if we haven't already set the process 2176 // state to an exited state. We normally should have received a SIGTRAP | (PTRACE_EVENT_EXIT << 8) 2177 // for the main thread. 2178 const bool already_notified = (GetState() == StateType::eStateExited) || (GetState () == StateType::eStateCrashed); 2179 if (!already_notified) 2180 { 2181 if (log) 2182 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 (GetState ())); 2183 // The main thread exited. We're done monitoring. Report to delegate. 2184 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true); 2185 2186 // Notify delegate that our process has exited. 2187 SetState (StateType::eStateExited, true); 2188 } 2189 else 2190 { 2191 if (log) 2192 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " main thread now exited (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found"); 2193 } 2194 } 2195 else 2196 { 2197 // Do we want to report to the delegate in this case? I think not. If this was an orderly 2198 // thread exit, we would already have received the SIGTRAP | (PTRACE_EVENT_EXIT << 8) signal, 2199 // and we would have done an all-stop then. 2200 if (log) 2201 log->Printf ("NativeProcessLinux::%s() tid = %" PRIu64 " handling non-main thread exit (%s)", __FUNCTION__, pid, thread_found ? "stopped tracking thread metadata" : "thread metadata not found"); 2202 } 2203 return; 2204 } 2205 2206 // Get details on the signal raised. 2207 siginfo_t info; 2208 const auto err = GetSignalInfo(pid, &info); 2209 if (err.Success()) 2210 { 2211 // We have retrieved the signal info. Dispatch appropriately. 2212 if (info.si_signo == SIGTRAP) 2213 MonitorSIGTRAP(&info, pid); 2214 else 2215 MonitorSignal(&info, pid, exited); 2216 } 2217 else 2218 { 2219 if (err.GetError() == EINVAL) 2220 { 2221 // This is a group stop reception for this tid. 2222 if (log) 2223 log->Printf ("NativeThreadLinux::%s received a group stop for pid %" PRIu64 " tid %" PRIu64, __FUNCTION__, GetID (), pid); 2224 NotifyThreadStop (pid, false); 2225 } 2226 else 2227 { 2228 // ptrace(GETSIGINFO) failed (but not due to group-stop). 2229 2230 // A return value of ESRCH means the thread/process is no longer on the system, 2231 // so it was killed somehow outside of our control. Either way, we can't do anything 2232 // with it anymore. 2233 2234 // Stop tracking the metadata for the thread since it's entirely off the system now. 2235 const bool thread_found = StopTrackingThread (pid); 2236 2237 // Make sure the thread state coordinator knows about this. 2238 NotifyThreadDeath (pid); 2239 2240 if (log) 2241 log->Printf ("NativeProcessLinux::%s GetSignalInfo failed: %s, tid = %" PRIu64 ", signal = %d, status = %d (%s, %s, %s)", 2242 __FUNCTION__, err.AsCString(), pid, signal, status, err.GetError() == 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"); 2243 2244 if (is_main_thread) 2245 { 2246 // Notify the delegate - our process is not available but appears to have been killed outside 2247 // our control. Is eStateExited the right exit state in this case? 2248 SetExitStatus (convert_pid_status_to_exit_type (status), convert_pid_status_to_return_code (status), nullptr, true); 2249 SetState (StateType::eStateExited, true); 2250 } 2251 else 2252 { 2253 // This thread was pulled out from underneath us. Anything to do here? Do we want to do an all stop? 2254 if (log) 2255 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__, GetID (), pid); 2256 } 2257 } 2258 } 2259 } 2260 2261 void 2262 NativeProcessLinux::WaitForNewThread(::pid_t tid) 2263 { 2264 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2265 2266 NativeThreadProtocolSP new_thread_sp = GetThreadByID(tid); 2267 2268 if (new_thread_sp) 2269 { 2270 // We are already tracking the thread - we got the event on the new thread (see 2271 // MonitorSignal) before this one. We are done. 2272 return; 2273 } 2274 2275 // The thread is not tracked yet, let's wait for it to appear. 2276 int status = -1; 2277 ::pid_t wait_pid; 2278 do 2279 { 2280 if (log) 2281 log->Printf ("NativeProcessLinux::%s() received thread creation event for tid %" PRIu32 ". tid not tracked yet, waiting for thread to appear...", __FUNCTION__, tid); 2282 wait_pid = waitpid(tid, &status, __WALL); 2283 } 2284 while (wait_pid == -1 && errno == EINTR); 2285 // Since we are waiting on a specific tid, this must be the creation event. But let's do 2286 // some checks just in case. 2287 if (wait_pid != tid) { 2288 if (log) 2289 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime", __FUNCTION__, tid); 2290 // The only way I know of this could happen is if the whole process was 2291 // SIGKILLed in the mean time. In any case, we can't do anything about that now. 2292 return; 2293 } 2294 if (WIFEXITED(status)) 2295 { 2296 if (log) 2297 log->Printf ("NativeProcessLinux::%s() waiting for tid %" PRIu32 " returned an 'exited' event. Not tracking the thread.", __FUNCTION__, tid); 2298 // Also a very improbable event. 2299 return; 2300 } 2301 2302 siginfo_t info; 2303 Error error = GetSignalInfo(tid, &info); 2304 if (error.Fail()) 2305 { 2306 if (log) 2307 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " failed. Assuming the thread has disappeared in the meantime.", __FUNCTION__, tid); 2308 return; 2309 } 2310 2311 if (((info.si_pid != 0) || (info.si_code != SI_USER)) && log) 2312 { 2313 // We should be getting a thread creation signal here, but we received something 2314 // else. There isn't much we can do about it now, so we will just log that. Since the 2315 // thread is alive and we are receiving events from it, we shall pretend that it was 2316 // created properly. 2317 log->Printf ("NativeProcessLinux::%s() GetSignalInfo for tid %" PRIu32 " received unexpected signal with code %d from pid %d.", __FUNCTION__, tid, info.si_code, info.si_pid); 2318 } 2319 2320 if (log) 2321 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 ": tracking new thread tid %" PRIu32, 2322 __FUNCTION__, GetID (), tid); 2323 2324 new_thread_sp = AddThread(tid); 2325 std::static_pointer_cast<NativeThreadLinux> (new_thread_sp)->SetRunning (); 2326 Resume (tid, LLDB_INVALID_SIGNAL_NUMBER); 2327 NotifyThreadCreate(tid); 2328 } 2329 2330 void 2331 NativeProcessLinux::MonitorSIGTRAP(const siginfo_t *info, lldb::pid_t pid) 2332 { 2333 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2334 const bool is_main_thread = (pid == GetID ()); 2335 2336 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!"); 2337 if (!info) 2338 return; 2339 2340 Mutex::Locker locker (m_threads_mutex); 2341 2342 // See if we can find a thread for this signal. 2343 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2344 if (!thread_sp) 2345 { 2346 if (log) 2347 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2348 } 2349 2350 switch (info->si_code) 2351 { 2352 // TODO: these two cases are required if we want to support tracing of the inferiors' children. We'd need this to debug a monitor. 2353 // case (SIGTRAP | (PTRACE_EVENT_FORK << 8)): 2354 // case (SIGTRAP | (PTRACE_EVENT_VFORK << 8)): 2355 2356 case (SIGTRAP | (PTRACE_EVENT_CLONE << 8)): 2357 { 2358 // This is the notification on the parent thread which informs us of new thread 2359 // creation. 2360 // We don't want to do anything with the parent thread so we just resume it. In case we 2361 // want to implement "break on thread creation" functionality, we would need to stop 2362 // here. 2363 2364 unsigned long event_message = 0; 2365 if (GetEventMessage (pid, &event_message).Fail()) 2366 { 2367 if (log) 2368 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " received thread creation event but GetEventMessage failed so we don't know the new tid", __FUNCTION__, pid); 2369 } else 2370 WaitForNewThread(event_message); 2371 2372 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2373 break; 2374 } 2375 2376 case (SIGTRAP | (PTRACE_EVENT_EXEC << 8)): 2377 { 2378 NativeThreadProtocolSP main_thread_sp; 2379 if (log) 2380 log->Printf ("NativeProcessLinux::%s() received exec event, code = %d", __FUNCTION__, info->si_code ^ SIGTRAP); 2381 2382 // The thread state coordinator needs to reset due to the exec. 2383 ResetForExec (); 2384 2385 // Remove all but the main thread here. Linux fork creates a new process which only copies the main thread. Mutexes are in undefined state. 2386 if (log) 2387 log->Printf ("NativeProcessLinux::%s exec received, stop tracking all but main thread", __FUNCTION__); 2388 2389 for (auto thread_sp : m_threads) 2390 { 2391 const bool is_main_thread = thread_sp && thread_sp->GetID () == GetID (); 2392 if (is_main_thread) 2393 { 2394 main_thread_sp = thread_sp; 2395 if (log) 2396 log->Printf ("NativeProcessLinux::%s found main thread with tid %" PRIu64 ", keeping", __FUNCTION__, main_thread_sp->GetID ()); 2397 } 2398 else 2399 { 2400 // Tell thread coordinator this thread is dead. 2401 if (log) 2402 log->Printf ("NativeProcessLinux::%s discarding non-main-thread tid %" PRIu64 " due to exec", __FUNCTION__, thread_sp->GetID ()); 2403 } 2404 } 2405 2406 m_threads.clear (); 2407 2408 if (main_thread_sp) 2409 { 2410 m_threads.push_back (main_thread_sp); 2411 SetCurrentThreadID (main_thread_sp->GetID ()); 2412 std::static_pointer_cast<NativeThreadLinux> (main_thread_sp)->SetStoppedByExec (); 2413 } 2414 else 2415 { 2416 SetCurrentThreadID (LLDB_INVALID_THREAD_ID); 2417 if (log) 2418 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 "no main thread found, discarded all threads, we're in a no-thread state!", __FUNCTION__, GetID ()); 2419 } 2420 2421 // Tell coordinator about about the "new" (since exec) stopped main thread. 2422 const lldb::tid_t main_thread_tid = GetID (); 2423 NotifyThreadCreate(main_thread_tid); 2424 2425 // NOTE: ideally these next statements would execute at the same time as the coordinator thread create was executed. 2426 // Consider a handler that can execute when that happens. 2427 // Let our delegate know we have just exec'd. 2428 NotifyDidExec (); 2429 2430 // If we have a main thread, indicate we are stopped. 2431 assert (main_thread_sp && "exec called during ptraced process but no main thread metadata tracked"); 2432 2433 // Let the process know we're stopped. 2434 StopRunningThreads (pid); 2435 2436 break; 2437 } 2438 2439 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): 2440 { 2441 // The inferior process or one of its threads is about to exit. 2442 if (! thread_sp) 2443 break; 2444 2445 // This thread is currently stopped. It's not actually dead yet, just about to be. 2446 NotifyThreadStop (pid, false); 2447 // The actual stop reason does not matter much, as we are going to resume the thread a 2448 // few lines down. If we ever want to report this state to the debugger, then we should 2449 // invent a new stop reason. 2450 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedBySignal(LLDB_INVALID_SIGNAL_NUMBER); 2451 2452 unsigned long data = 0; 2453 if (GetEventMessage(pid, &data).Fail()) 2454 data = -1; 2455 2456 if (log) 2457 { 2458 log->Printf ("NativeProcessLinux::%s() received PTRACE_EVENT_EXIT, data = %lx (WIFEXITED=%s,WIFSIGNALED=%s), pid = %" PRIu64 " (%s)", 2459 __FUNCTION__, 2460 data, WIFEXITED (data) ? "true" : "false", WIFSIGNALED (data) ? "true" : "false", 2461 pid, 2462 is_main_thread ? "is main thread" : "not main thread"); 2463 } 2464 2465 if (is_main_thread) 2466 { 2467 SetExitStatus (convert_pid_status_to_exit_type (data), convert_pid_status_to_return_code (data), nullptr, true); 2468 } 2469 2470 const int signo = static_cast<int> (data); 2471 RequestThreadResume (pid, 2472 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2473 { 2474 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2475 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo); 2476 }); 2477 2478 break; 2479 } 2480 2481 case 0: 2482 case TRAP_TRACE: // We receive this on single stepping. 2483 case TRAP_HWBKPT: // We receive this on watchpoint hit 2484 if (thread_sp) 2485 { 2486 // If a watchpoint was hit, report it 2487 uint32_t wp_index; 2488 Error error = thread_sp->GetRegisterContext()->GetWatchpointHitIndex(wp_index); 2489 if (error.Fail() && log) 2490 log->Printf("NativeProcessLinux::%s() " 2491 "received error while checking for watchpoint hits, " 2492 "pid = %" PRIu64 " error = %s", 2493 __FUNCTION__, pid, error.AsCString()); 2494 if (wp_index != LLDB_INVALID_INDEX32) 2495 { 2496 MonitorWatchpoint(pid, thread_sp, wp_index); 2497 break; 2498 } 2499 } 2500 // Otherwise, report step over 2501 MonitorTrace(pid, thread_sp); 2502 break; 2503 2504 case SI_KERNEL: 2505 case TRAP_BRKPT: 2506 MonitorBreakpoint(pid, thread_sp); 2507 break; 2508 2509 case SIGTRAP: 2510 case (SIGTRAP | 0x80): 2511 if (log) 2512 log->Printf ("NativeProcessLinux::%s() received unknown SIGTRAP system call stop event, pid %" PRIu64 "tid %" PRIu64 ", resuming", __FUNCTION__, GetID (), pid); 2513 2514 // This thread is currently stopped. 2515 NotifyThreadStop (pid, false); 2516 if (thread_sp) 2517 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (SIGTRAP); 2518 2519 2520 // Ignore these signals until we know more about them. 2521 RequestThreadResume (pid, 2522 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2523 { 2524 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2525 return Resume (tid_to_resume, LLDB_INVALID_SIGNAL_NUMBER); 2526 }); 2527 break; 2528 2529 default: 2530 assert(false && "Unexpected SIGTRAP code!"); 2531 if (log) 2532 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))); 2533 break; 2534 2535 } 2536 } 2537 2538 void 2539 NativeProcessLinux::MonitorTrace(lldb::pid_t pid, NativeThreadProtocolSP thread_sp) 2540 { 2541 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 2542 if (log) 2543 log->Printf("NativeProcessLinux::%s() received trace event, pid = %" PRIu64 " (single stepping)", 2544 __FUNCTION__, pid); 2545 2546 if (thread_sp) 2547 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace(); 2548 2549 // This thread is currently stopped. 2550 NotifyThreadStop(pid, false); 2551 2552 // Here we don't have to request the rest of the threads to stop or request a deferred stop. 2553 // This would have already happened at the time the Resume() with step operation was signaled. 2554 // At this point, we just need to say we stopped, and the deferred notifcation will fire off 2555 // once all running threads have checked in as stopped. 2556 SetCurrentThreadID(pid); 2557 // Tell the process we have a stop (from software breakpoint). 2558 StopRunningThreads(pid); 2559 } 2560 2561 void 2562 NativeProcessLinux::MonitorBreakpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp) 2563 { 2564 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_BREAKPOINTS)); 2565 if (log) 2566 log->Printf("NativeProcessLinux::%s() received breakpoint event, pid = %" PRIu64, 2567 __FUNCTION__, pid); 2568 2569 // This thread is currently stopped. 2570 NotifyThreadStop(pid, false); 2571 2572 // Mark the thread as stopped at breakpoint. 2573 if (thread_sp) 2574 { 2575 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByBreakpoint(); 2576 Error error = FixupBreakpointPCAsNeeded(thread_sp); 2577 if (error.Fail()) 2578 if (log) 2579 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " fixup: %s", 2580 __FUNCTION__, pid, error.AsCString()); 2581 2582 auto it = m_threads_stepping_with_breakpoint.find(pid); 2583 if (it != m_threads_stepping_with_breakpoint.end()) 2584 { 2585 Error error = RemoveBreakpoint (it->second); 2586 if (error.Fail()) 2587 if (log) 2588 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 " remove stepping breakpoint: %s", 2589 __FUNCTION__, pid, error.AsCString()); 2590 2591 m_threads_stepping_with_breakpoint.erase(it); 2592 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByTrace(); 2593 } 2594 } 2595 else 2596 if (log) 2597 log->Printf("NativeProcessLinux::%s() pid = %" PRIu64 ": " 2598 "warning, cannot process software breakpoint since no thread metadata", 2599 __FUNCTION__, pid); 2600 2601 2602 // We need to tell all other running threads before we notify the delegate about this stop. 2603 StopRunningThreads(pid); 2604 } 2605 2606 void 2607 NativeProcessLinux::MonitorWatchpoint(lldb::pid_t pid, NativeThreadProtocolSP thread_sp, uint32_t wp_index) 2608 { 2609 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_WATCHPOINTS)); 2610 if (log) 2611 log->Printf("NativeProcessLinux::%s() received watchpoint event, " 2612 "pid = %" PRIu64 ", wp_index = %" PRIu32, 2613 __FUNCTION__, pid, wp_index); 2614 2615 // This thread is currently stopped. 2616 NotifyThreadStop(pid, false); 2617 2618 // Mark the thread as stopped at watchpoint. 2619 // The address is at (lldb::addr_t)info->si_addr if we need it. 2620 lldbassert(thread_sp && "thread_sp cannot be NULL"); 2621 std::static_pointer_cast<NativeThreadLinux>(thread_sp)->SetStoppedByWatchpoint(wp_index); 2622 2623 // We need to tell all other running threads before we notify the delegate about this stop. 2624 StopRunningThreads(pid); 2625 } 2626 2627 void 2628 NativeProcessLinux::MonitorSignal(const siginfo_t *info, lldb::pid_t pid, bool exited) 2629 { 2630 assert (info && "null info"); 2631 if (!info) 2632 return; 2633 2634 const int signo = info->si_signo; 2635 const bool is_from_llgs = info->si_pid == getpid (); 2636 2637 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 2638 2639 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 2640 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a 2641 // kill(2) or raise(3). Similarly for tgkill(2) on Linux. 2642 // 2643 // IOW, user generated signals never generate what we consider to be a 2644 // "crash". 2645 // 2646 // Similarly, ACK signals generated by this monitor. 2647 2648 Mutex::Locker locker (m_threads_mutex); 2649 2650 // See if we can find a thread for this signal. 2651 NativeThreadProtocolSP thread_sp = GetThreadByID (pid); 2652 if (!thread_sp) 2653 { 2654 if (log) 2655 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " no thread found for tid %" PRIu64, __FUNCTION__, GetID (), pid); 2656 } 2657 2658 // Handle the signal. 2659 if (info->si_code == SI_TKILL || info->si_code == SI_USER) 2660 { 2661 if (log) 2662 log->Printf ("NativeProcessLinux::%s() received signal %s (%d) with code %s, (siginfo pid = %d (%s), waitpid pid = %" PRIu64 ")", 2663 __FUNCTION__, 2664 GetUnixSignals ().GetSignalAsCString (signo), 2665 signo, 2666 (info->si_code == SI_TKILL ? "SI_TKILL" : "SI_USER"), 2667 info->si_pid, 2668 is_from_llgs ? "from llgs" : "not from llgs", 2669 pid); 2670 } 2671 2672 // Check for new thread notification. 2673 if ((info->si_pid == 0) && (info->si_code == SI_USER)) 2674 { 2675 // A new thread creation is being signaled. This is one of two parts that come in 2676 // a non-deterministic order. This code handles the case where the new thread event comes 2677 // before the event on the parent thread. For the opposite case see code in 2678 // MonitorSIGTRAP. 2679 if (log) 2680 log->Printf ("NativeProcessLinux::%s() pid = %" PRIu64 " tid %" PRIu64 ": new thread notification", 2681 __FUNCTION__, GetID (), pid); 2682 2683 thread_sp = AddThread(pid); 2684 assert (thread_sp.get() && "failed to create the tracking data for newly created inferior thread"); 2685 // We can now resume the newly created thread. 2686 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2687 Resume (pid, LLDB_INVALID_SIGNAL_NUMBER); 2688 NotifyThreadCreate(pid); 2689 // Done handling. 2690 return; 2691 } 2692 2693 // Check for thread stop notification. 2694 if (is_from_llgs && (info->si_code == SI_TKILL) && (signo == SIGSTOP)) 2695 { 2696 // This is a tgkill()-based stop. 2697 if (thread_sp) 2698 { 2699 if (log) 2700 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread stopped", 2701 __FUNCTION__, 2702 GetID (), 2703 pid); 2704 2705 // Check that we're not already marked with a stop reason. 2706 // Note this thread really shouldn't already be marked as stopped - if we were, that would imply that 2707 // the kernel signaled us with the thread stopping which we handled and marked as stopped, 2708 // and that, without an intervening resume, we received another stop. It is more likely 2709 // that we are missing the marking of a run state somewhere if we find that the thread was 2710 // marked as stopped. 2711 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp); 2712 assert (linux_thread_sp && "linux_thread_sp is null!"); 2713 2714 const StateType thread_state = linux_thread_sp->GetState (); 2715 if (!StateIsStoppedState (thread_state, false)) 2716 { 2717 // An inferior thread has stopped because of a SIGSTOP we have sent it. 2718 // Generally, these are not important stops and we don't want to report them as 2719 // they are just used to stop other threads when one thread (the one with the 2720 // *real* stop reason) hits a breakpoint (watchpoint, etc...). However, in the 2721 // case of an asynchronous Interrupt(), this *is* the real stop reason, so we 2722 // leave the signal intact if this is the thread that was chosen as the 2723 // triggering thread. 2724 if (m_pending_notification_up && m_pending_notification_up->triggering_tid == pid) 2725 linux_thread_sp->SetStoppedBySignal(SIGSTOP); 2726 else 2727 linux_thread_sp->SetStoppedBySignal(0); 2728 2729 SetCurrentThreadID (thread_sp->GetID ()); 2730 NotifyThreadStop (thread_sp->GetID (), true); 2731 } 2732 else 2733 { 2734 if (log) 2735 { 2736 // Retrieve the signal name if the thread was stopped by a signal. 2737 int stop_signo = 0; 2738 const bool stopped_by_signal = linux_thread_sp->IsStopped (&stop_signo); 2739 const char *signal_name = stopped_by_signal ? GetUnixSignals ().GetSignalAsCString (stop_signo) : "<not stopped by signal>"; 2740 if (!signal_name) 2741 signal_name = "<no-signal-name>"; 2742 2743 log->Printf ("NativeProcessLinux::%s() pid %" PRIu64 " tid %" PRIu64 ", thread was already marked as a stopped state (state=%s, signal=%d (%s)), leaving stop signal as is", 2744 __FUNCTION__, 2745 GetID (), 2746 linux_thread_sp->GetID (), 2747 StateAsCString (thread_state), 2748 stop_signo, 2749 signal_name); 2750 } 2751 // Tell the thread state coordinator about the stop. 2752 NotifyThreadStop (thread_sp->GetID (), false); 2753 } 2754 } 2755 2756 // Done handling. 2757 return; 2758 } 2759 2760 if (log) 2761 log->Printf ("NativeProcessLinux::%s() received signal %s", __FUNCTION__, GetUnixSignals ().GetSignalAsCString (signo)); 2762 2763 // This thread is stopped. 2764 NotifyThreadStop (pid, false); 2765 2766 switch (signo) 2767 { 2768 case SIGSTOP: 2769 { 2770 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo); 2771 if (log) 2772 { 2773 if (is_from_llgs) 2774 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from llgs, most likely an interrupt", __FUNCTION__, GetID (), pid); 2775 else 2776 log->Printf ("NativeProcessLinux::%s pid = %" PRIu64 " tid %" PRIu64 " received SIGSTOP from outside of debugger", __FUNCTION__, GetID (), pid); 2777 } 2778 2779 // Resume this thread to get the group-stop mechanism to fire off the true group stops. 2780 // This thread will get stopped again as part of the group-stop completion. 2781 RequestThreadResume (pid, 2782 [=](lldb::tid_t tid_to_resume, bool supress_signal) 2783 { 2784 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 2785 // Pass this signal number on to the inferior to handle. 2786 return Resume (tid_to_resume, (supress_signal) ? LLDB_INVALID_SIGNAL_NUMBER : signo); 2787 }); 2788 } 2789 break; 2790 case SIGSEGV: 2791 case SIGILL: 2792 case SIGFPE: 2793 case SIGBUS: 2794 if (thread_sp) 2795 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetCrashedWithException (*info); 2796 break; 2797 default: 2798 // This is just a pre-signal-delivery notification of the incoming signal. 2799 if (thread_sp) 2800 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStoppedBySignal (signo); 2801 2802 break; 2803 } 2804 2805 // Send a stop to the debugger after we get all other threads to stop. 2806 StopRunningThreads (pid); 2807 } 2808 2809 namespace { 2810 2811 struct EmulatorBaton 2812 { 2813 NativeProcessLinux* m_process; 2814 NativeRegisterContext* m_reg_context; 2815 2816 // eRegisterKindDWARF -> RegsiterValue 2817 std::unordered_map<uint32_t, RegisterValue> m_register_values; 2818 2819 EmulatorBaton(NativeProcessLinux* process, NativeRegisterContext* reg_context) : 2820 m_process(process), m_reg_context(reg_context) {} 2821 }; 2822 2823 } // anonymous namespace 2824 2825 static size_t 2826 ReadMemoryCallback (EmulateInstruction *instruction, 2827 void *baton, 2828 const EmulateInstruction::Context &context, 2829 lldb::addr_t addr, 2830 void *dst, 2831 size_t length) 2832 { 2833 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2834 2835 size_t bytes_read; 2836 emulator_baton->m_process->ReadMemory(addr, dst, length, bytes_read); 2837 return bytes_read; 2838 } 2839 2840 static bool 2841 ReadRegisterCallback (EmulateInstruction *instruction, 2842 void *baton, 2843 const RegisterInfo *reg_info, 2844 RegisterValue ®_value) 2845 { 2846 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2847 2848 auto it = emulator_baton->m_register_values.find(reg_info->kinds[eRegisterKindDWARF]); 2849 if (it != emulator_baton->m_register_values.end()) 2850 { 2851 reg_value = it->second; 2852 return true; 2853 } 2854 2855 // The emulator only fill in the dwarf regsiter numbers (and in some case 2856 // the generic register numbers). Get the full register info from the 2857 // register context based on the dwarf register numbers. 2858 const RegisterInfo* full_reg_info = emulator_baton->m_reg_context->GetRegisterInfo( 2859 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]); 2860 2861 Error error = emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value); 2862 if (error.Success()) 2863 return true; 2864 2865 return false; 2866 } 2867 2868 static bool 2869 WriteRegisterCallback (EmulateInstruction *instruction, 2870 void *baton, 2871 const EmulateInstruction::Context &context, 2872 const RegisterInfo *reg_info, 2873 const RegisterValue ®_value) 2874 { 2875 EmulatorBaton* emulator_baton = static_cast<EmulatorBaton*>(baton); 2876 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] = reg_value; 2877 return true; 2878 } 2879 2880 static size_t 2881 WriteMemoryCallback (EmulateInstruction *instruction, 2882 void *baton, 2883 const EmulateInstruction::Context &context, 2884 lldb::addr_t addr, 2885 const void *dst, 2886 size_t length) 2887 { 2888 return length; 2889 } 2890 2891 static lldb::addr_t 2892 ReadFlags (NativeRegisterContext* regsiter_context) 2893 { 2894 const RegisterInfo* flags_info = regsiter_context->GetRegisterInfo( 2895 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2896 return regsiter_context->ReadRegisterAsUnsigned(flags_info, LLDB_INVALID_ADDRESS); 2897 } 2898 2899 Error 2900 NativeProcessLinux::SetupSoftwareSingleStepping(NativeThreadProtocolSP thread_sp) 2901 { 2902 Error error; 2903 NativeRegisterContextSP register_context_sp = thread_sp->GetRegisterContext(); 2904 2905 std::unique_ptr<EmulateInstruction> emulator_ap( 2906 EmulateInstruction::FindPlugin(m_arch, eInstructionTypePCModifying, nullptr)); 2907 2908 if (emulator_ap == nullptr) 2909 return Error("Instruction emulator not found!"); 2910 2911 EmulatorBaton baton(this, register_context_sp.get()); 2912 emulator_ap->SetBaton(&baton); 2913 emulator_ap->SetReadMemCallback(&ReadMemoryCallback); 2914 emulator_ap->SetReadRegCallback(&ReadRegisterCallback); 2915 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback); 2916 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback); 2917 2918 if (!emulator_ap->ReadInstruction()) 2919 return Error("Read instruction failed!"); 2920 2921 bool emulation_result = emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC); 2922 2923 const RegisterInfo* reg_info_pc = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); 2924 const RegisterInfo* reg_info_flags = register_context_sp->GetRegisterInfo(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FLAGS); 2925 2926 auto pc_it = baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]); 2927 auto flags_it = baton.m_register_values.find(reg_info_flags->kinds[eRegisterKindDWARF]); 2928 2929 lldb::addr_t next_pc; 2930 lldb::addr_t next_flags; 2931 if (emulation_result) 2932 { 2933 assert(pc_it != baton.m_register_values.end() && "Emulation was successfull but PC wasn't updated"); 2934 next_pc = pc_it->second.GetAsUInt64(); 2935 2936 if (flags_it != baton.m_register_values.end()) 2937 next_flags = flags_it->second.GetAsUInt64(); 2938 else 2939 next_flags = ReadFlags (register_context_sp.get()); 2940 } 2941 else if (pc_it == baton.m_register_values.end()) 2942 { 2943 // Emulate instruction failed and it haven't changed PC. Advance PC 2944 // with the size of the current opcode because the emulation of all 2945 // PC modifying instruction should be successful. The failure most 2946 // likely caused by a not supported instruction which don't modify PC. 2947 next_pc = register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize(); 2948 next_flags = ReadFlags (register_context_sp.get()); 2949 } 2950 else 2951 { 2952 // The instruction emulation failed after it modified the PC. It is an 2953 // unknown error where we can't continue because the next instruction is 2954 // modifying the PC but we don't know how. 2955 return Error ("Instruction emulation failed unexpectedly."); 2956 } 2957 2958 if (m_arch.GetMachine() == llvm::Triple::arm) 2959 { 2960 if (next_flags & 0x20) 2961 { 2962 // Thumb mode 2963 error = SetSoftwareBreakpoint(next_pc, 2); 2964 } 2965 else 2966 { 2967 // Arm mode 2968 error = SetSoftwareBreakpoint(next_pc, 4); 2969 } 2970 } 2971 else if (m_arch.GetMachine() == llvm::Triple::mips64 2972 || m_arch.GetMachine() == llvm::Triple::mips64el) 2973 error = SetSoftwareBreakpoint(next_pc, 4); 2974 else 2975 { 2976 // No size hint is given for the next breakpoint 2977 error = SetSoftwareBreakpoint(next_pc, 0); 2978 } 2979 2980 if (error.Fail()) 2981 return error; 2982 2983 m_threads_stepping_with_breakpoint.insert({thread_sp->GetID(), next_pc}); 2984 2985 return Error(); 2986 } 2987 2988 bool 2989 NativeProcessLinux::SupportHardwareSingleStepping() const 2990 { 2991 if (m_arch.GetMachine() == llvm::Triple::arm 2992 || m_arch.GetMachine() == llvm::Triple::mips64 || m_arch.GetMachine() == llvm::Triple::mips64el) 2993 return false; 2994 return true; 2995 } 2996 2997 Error 2998 NativeProcessLinux::Resume (const ResumeActionList &resume_actions) 2999 { 3000 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD)); 3001 if (log) 3002 log->Printf ("NativeProcessLinux::%s called: pid %" PRIu64, __FUNCTION__, GetID ()); 3003 3004 lldb::tid_t deferred_signal_tid = LLDB_INVALID_THREAD_ID; 3005 lldb::tid_t deferred_signal_skip_tid = LLDB_INVALID_THREAD_ID; 3006 int deferred_signo = 0; 3007 NativeThreadProtocolSP deferred_signal_thread_sp; 3008 bool stepping = false; 3009 bool software_single_step = !SupportHardwareSingleStepping(); 3010 3011 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3012 Mutex::Locker locker (m_threads_mutex); 3013 3014 if (software_single_step) 3015 { 3016 for (auto thread_sp : m_threads) 3017 { 3018 assert (thread_sp && "thread list should not contain NULL threads"); 3019 3020 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 3021 if (action == nullptr) 3022 continue; 3023 3024 if (action->state == eStateStepping) 3025 { 3026 Error error = SetupSoftwareSingleStepping(thread_sp); 3027 if (error.Fail()) 3028 return error; 3029 } 3030 } 3031 } 3032 3033 for (auto thread_sp : m_threads) 3034 { 3035 assert (thread_sp && "thread list should not contain NULL threads"); 3036 3037 const ResumeAction *const action = resume_actions.GetActionForThread (thread_sp->GetID (), true); 3038 3039 if (action == nullptr) 3040 { 3041 if (log) 3042 log->Printf ("NativeProcessLinux::%s no action specified for pid %" PRIu64 " tid %" PRIu64, 3043 __FUNCTION__, GetID (), thread_sp->GetID ()); 3044 continue; 3045 } 3046 3047 if (log) 3048 { 3049 log->Printf ("NativeProcessLinux::%s processing resume action state %s for pid %" PRIu64 " tid %" PRIu64, 3050 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 3051 } 3052 3053 switch (action->state) 3054 { 3055 case eStateRunning: 3056 { 3057 // Run the thread, possibly feeding it the signal. 3058 const int signo = action->signal; 3059 RequestThreadResumeAsNeeded (thread_sp->GetID (), 3060 [=](lldb::tid_t tid_to_resume, bool supress_signal) 3061 { 3062 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetRunning (); 3063 // Pass this signal number on to the inferior to handle. 3064 const auto resume_result = Resume (tid_to_resume, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3065 if (resume_result.Success()) 3066 SetState(eStateRunning, true); 3067 return resume_result; 3068 }); 3069 break; 3070 } 3071 3072 case eStateStepping: 3073 { 3074 // Request the step. 3075 const int signo = action->signal; 3076 RequestThreadResume (thread_sp->GetID (), 3077 [=](lldb::tid_t tid_to_step, bool supress_signal) 3078 { 3079 std::static_pointer_cast<NativeThreadLinux> (thread_sp)->SetStepping (); 3080 3081 Error step_result; 3082 if (software_single_step) 3083 step_result = Resume (tid_to_step, (signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3084 else 3085 step_result = SingleStep (tid_to_step,(signo > 0 && !supress_signal) ? signo : LLDB_INVALID_SIGNAL_NUMBER); 3086 3087 assert (step_result.Success() && "SingleStep() failed"); 3088 if (step_result.Success()) 3089 SetState(eStateStepping, true); 3090 return step_result; 3091 }); 3092 stepping = true; 3093 break; 3094 } 3095 3096 case eStateSuspended: 3097 case eStateStopped: 3098 // if we haven't chosen a deferred signal tid yet, use this one. 3099 if (deferred_signal_tid == LLDB_INVALID_THREAD_ID) 3100 { 3101 deferred_signal_tid = thread_sp->GetID (); 3102 deferred_signal_thread_sp = thread_sp; 3103 deferred_signo = SIGSTOP; 3104 } 3105 break; 3106 3107 default: 3108 return Error ("NativeProcessLinux::%s (): unexpected state %s specified for pid %" PRIu64 ", tid %" PRIu64, 3109 __FUNCTION__, StateAsCString (action->state), GetID (), thread_sp->GetID ()); 3110 } 3111 } 3112 3113 // If we had any thread stopping, then do a deferred notification of the chosen stop thread id and signal 3114 // after all other running threads have stopped. 3115 // If there is a stepping thread involved we'll be eventually stopped by SIGTRAP trace signal. 3116 if (deferred_signal_tid != LLDB_INVALID_THREAD_ID && !stepping) 3117 StopRunningThreadsWithSkipTID(deferred_signal_tid, deferred_signal_skip_tid); 3118 3119 return Error(); 3120 } 3121 3122 Error 3123 NativeProcessLinux::Halt () 3124 { 3125 Error error; 3126 3127 if (kill (GetID (), SIGSTOP) != 0) 3128 error.SetErrorToErrno (); 3129 3130 return error; 3131 } 3132 3133 Error 3134 NativeProcessLinux::Detach () 3135 { 3136 Error error; 3137 3138 // Tell ptrace to detach from the process. 3139 if (GetID () != LLDB_INVALID_PROCESS_ID) 3140 error = Detach (GetID ()); 3141 3142 // Stop monitoring the inferior. 3143 m_monitor_up->Terminate(); 3144 3145 // No error. 3146 return error; 3147 } 3148 3149 Error 3150 NativeProcessLinux::Signal (int signo) 3151 { 3152 Error error; 3153 3154 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3155 if (log) 3156 log->Printf ("NativeProcessLinux::%s: sending signal %d (%s) to pid %" PRIu64, 3157 __FUNCTION__, signo, GetUnixSignals ().GetSignalAsCString (signo), GetID ()); 3158 3159 if (kill(GetID(), signo)) 3160 error.SetErrorToErrno(); 3161 3162 return error; 3163 } 3164 3165 Error 3166 NativeProcessLinux::Interrupt () 3167 { 3168 // Pick a running thread (or if none, a not-dead stopped thread) as 3169 // the chosen thread that will be the stop-reason thread. 3170 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3171 3172 NativeThreadProtocolSP running_thread_sp; 3173 NativeThreadProtocolSP stopped_thread_sp; 3174 3175 if (log) 3176 log->Printf ("NativeProcessLinux::%s selecting running thread for interrupt target", __FUNCTION__); 3177 3178 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3179 Mutex::Locker locker (m_threads_mutex); 3180 3181 for (auto thread_sp : m_threads) 3182 { 3183 // The thread shouldn't be null but lets just cover that here. 3184 if (!thread_sp) 3185 continue; 3186 3187 // If we have a running or stepping thread, we'll call that the 3188 // target of the interrupt. 3189 const auto thread_state = thread_sp->GetState (); 3190 if (thread_state == eStateRunning || 3191 thread_state == eStateStepping) 3192 { 3193 running_thread_sp = thread_sp; 3194 break; 3195 } 3196 else if (!stopped_thread_sp && StateIsStoppedState (thread_state, true)) 3197 { 3198 // Remember the first non-dead stopped thread. We'll use that as a backup if there are no running threads. 3199 stopped_thread_sp = thread_sp; 3200 } 3201 } 3202 3203 if (!running_thread_sp && !stopped_thread_sp) 3204 { 3205 Error error("found no running/stepping or live stopped threads as target for interrupt"); 3206 if (log) 3207 log->Printf ("NativeProcessLinux::%s skipping due to error: %s", __FUNCTION__, error.AsCString ()); 3208 3209 return error; 3210 } 3211 3212 NativeThreadProtocolSP deferred_signal_thread_sp = running_thread_sp ? running_thread_sp : stopped_thread_sp; 3213 3214 if (log) 3215 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " %s tid %" PRIu64 " chosen for interrupt target", 3216 __FUNCTION__, 3217 GetID (), 3218 running_thread_sp ? "running" : "stopped", 3219 deferred_signal_thread_sp->GetID ()); 3220 3221 StopRunningThreads(deferred_signal_thread_sp->GetID()); 3222 3223 return Error(); 3224 } 3225 3226 Error 3227 NativeProcessLinux::Kill () 3228 { 3229 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3230 if (log) 3231 log->Printf ("NativeProcessLinux::%s called for PID %" PRIu64, __FUNCTION__, GetID ()); 3232 3233 Error error; 3234 3235 switch (m_state) 3236 { 3237 case StateType::eStateInvalid: 3238 case StateType::eStateExited: 3239 case StateType::eStateCrashed: 3240 case StateType::eStateDetached: 3241 case StateType::eStateUnloaded: 3242 // Nothing to do - the process is already dead. 3243 if (log) 3244 log->Printf ("NativeProcessLinux::%s ignored for PID %" PRIu64 " due to current state: %s", __FUNCTION__, GetID (), StateAsCString (m_state)); 3245 return error; 3246 3247 case StateType::eStateConnected: 3248 case StateType::eStateAttaching: 3249 case StateType::eStateLaunching: 3250 case StateType::eStateStopped: 3251 case StateType::eStateRunning: 3252 case StateType::eStateStepping: 3253 case StateType::eStateSuspended: 3254 // We can try to kill a process in these states. 3255 break; 3256 } 3257 3258 if (kill (GetID (), SIGKILL) != 0) 3259 { 3260 error.SetErrorToErrno (); 3261 return error; 3262 } 3263 3264 return error; 3265 } 3266 3267 static Error 3268 ParseMemoryRegionInfoFromProcMapsLine (const std::string &maps_line, MemoryRegionInfo &memory_region_info) 3269 { 3270 memory_region_info.Clear(); 3271 3272 StringExtractor line_extractor (maps_line.c_str ()); 3273 3274 // Format: {address_start_hex}-{address_end_hex} perms offset dev inode pathname 3275 // perms: rwxp (letter is present if set, '-' if not, final character is p=private, s=shared). 3276 3277 // Parse out the starting address 3278 lldb::addr_t start_address = line_extractor.GetHexMaxU64 (false, 0); 3279 3280 // Parse out hyphen separating start and end address from range. 3281 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != '-')) 3282 return Error ("malformed /proc/{pid}/maps entry, missing dash between address range"); 3283 3284 // Parse out the ending address 3285 lldb::addr_t end_address = line_extractor.GetHexMaxU64 (false, start_address); 3286 3287 // Parse out the space after the address. 3288 if (!line_extractor.GetBytesLeft () || (line_extractor.GetChar () != ' ')) 3289 return Error ("malformed /proc/{pid}/maps entry, missing space after range"); 3290 3291 // Save the range. 3292 memory_region_info.GetRange ().SetRangeBase (start_address); 3293 memory_region_info.GetRange ().SetRangeEnd (end_address); 3294 3295 // Parse out each permission entry. 3296 if (line_extractor.GetBytesLeft () < 4) 3297 return Error ("malformed /proc/{pid}/maps entry, missing some portion of permissions"); 3298 3299 // Handle read permission. 3300 const char read_perm_char = line_extractor.GetChar (); 3301 if (read_perm_char == 'r') 3302 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eYes); 3303 else 3304 { 3305 assert ( (read_perm_char == '-') && "unexpected /proc/{pid}/maps read permission char" ); 3306 memory_region_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 3307 } 3308 3309 // Handle write permission. 3310 const char write_perm_char = line_extractor.GetChar (); 3311 if (write_perm_char == 'w') 3312 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eYes); 3313 else 3314 { 3315 assert ( (write_perm_char == '-') && "unexpected /proc/{pid}/maps write permission char" ); 3316 memory_region_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 3317 } 3318 3319 // Handle execute permission. 3320 const char exec_perm_char = line_extractor.GetChar (); 3321 if (exec_perm_char == 'x') 3322 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eYes); 3323 else 3324 { 3325 assert ( (exec_perm_char == '-') && "unexpected /proc/{pid}/maps exec permission char" ); 3326 memory_region_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 3327 } 3328 3329 return Error (); 3330 } 3331 3332 Error 3333 NativeProcessLinux::GetMemoryRegionInfo (lldb::addr_t load_addr, MemoryRegionInfo &range_info) 3334 { 3335 // FIXME review that the final memory region returned extends to the end of the virtual address space, 3336 // with no perms if it is not mapped. 3337 3338 // Use an approach that reads memory regions from /proc/{pid}/maps. 3339 // Assume proc maps entries are in ascending order. 3340 // FIXME assert if we find differently. 3341 Mutex::Locker locker (m_mem_region_cache_mutex); 3342 3343 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3344 Error error; 3345 3346 if (m_supports_mem_region == LazyBool::eLazyBoolNo) 3347 { 3348 // We're done. 3349 error.SetErrorString ("unsupported"); 3350 return error; 3351 } 3352 3353 // If our cache is empty, pull the latest. There should always be at least one memory region 3354 // if memory region handling is supported. 3355 if (m_mem_region_cache.empty ()) 3356 { 3357 error = ProcFileReader::ProcessLineByLine (GetID (), "maps", 3358 [&] (const std::string &line) -> bool 3359 { 3360 MemoryRegionInfo info; 3361 const Error parse_error = ParseMemoryRegionInfoFromProcMapsLine (line, info); 3362 if (parse_error.Success ()) 3363 { 3364 m_mem_region_cache.push_back (info); 3365 return true; 3366 } 3367 else 3368 { 3369 if (log) 3370 log->Printf ("NativeProcessLinux::%s failed to parse proc maps line '%s': %s", __FUNCTION__, line.c_str (), error.AsCString ()); 3371 return false; 3372 } 3373 }); 3374 3375 // If we had an error, we'll mark unsupported. 3376 if (error.Fail ()) 3377 { 3378 m_supports_mem_region = LazyBool::eLazyBoolNo; 3379 return error; 3380 } 3381 else if (m_mem_region_cache.empty ()) 3382 { 3383 // No entries after attempting to read them. This shouldn't happen if /proc/{pid}/maps 3384 // is supported. Assume we don't support map entries via procfs. 3385 if (log) 3386 log->Printf ("NativeProcessLinux::%s failed to find any procfs maps entries, assuming no support for memory region metadata retrieval", __FUNCTION__); 3387 m_supports_mem_region = LazyBool::eLazyBoolNo; 3388 error.SetErrorString ("not supported"); 3389 return error; 3390 } 3391 3392 if (log) 3393 log->Printf ("NativeProcessLinux::%s read %" PRIu64 " memory region entries from /proc/%" PRIu64 "/maps", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ()), GetID ()); 3394 3395 // We support memory retrieval, remember that. 3396 m_supports_mem_region = LazyBool::eLazyBoolYes; 3397 } 3398 else 3399 { 3400 if (log) 3401 log->Printf ("NativeProcessLinux::%s reusing %" PRIu64 " cached memory region entries", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 3402 } 3403 3404 lldb::addr_t prev_base_address = 0; 3405 3406 // FIXME start by finding the last region that is <= target address using binary search. Data is sorted. 3407 // There can be a ton of regions on pthreads apps with lots of threads. 3408 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end (); ++it) 3409 { 3410 MemoryRegionInfo &proc_entry_info = *it; 3411 3412 // Sanity check assumption that /proc/{pid}/maps entries are ascending. 3413 assert ((proc_entry_info.GetRange ().GetRangeBase () >= prev_base_address) && "descending /proc/pid/maps entries detected, unexpected"); 3414 prev_base_address = proc_entry_info.GetRange ().GetRangeBase (); 3415 3416 // If the target address comes before this entry, indicate distance to next region. 3417 if (load_addr < proc_entry_info.GetRange ().GetRangeBase ()) 3418 { 3419 range_info.GetRange ().SetRangeBase (load_addr); 3420 range_info.GetRange ().SetByteSize (proc_entry_info.GetRange ().GetRangeBase () - load_addr); 3421 range_info.SetReadable (MemoryRegionInfo::OptionalBool::eNo); 3422 range_info.SetWritable (MemoryRegionInfo::OptionalBool::eNo); 3423 range_info.SetExecutable (MemoryRegionInfo::OptionalBool::eNo); 3424 3425 return error; 3426 } 3427 else if (proc_entry_info.GetRange ().Contains (load_addr)) 3428 { 3429 // The target address is within the memory region we're processing here. 3430 range_info = proc_entry_info; 3431 return error; 3432 } 3433 3434 // The target memory address comes somewhere after the region we just parsed. 3435 } 3436 3437 // If we made it here, we didn't find an entry that contained the given address. 3438 error.SetErrorString ("address comes after final region"); 3439 3440 if (log) 3441 log->Printf ("NativeProcessLinux::%s failed to find map entry for address 0x%" PRIx64 ": %s", __FUNCTION__, load_addr, error.AsCString ()); 3442 3443 return error; 3444 } 3445 3446 void 3447 NativeProcessLinux::DoStopIDBumped (uint32_t newBumpId) 3448 { 3449 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3450 if (log) 3451 log->Printf ("NativeProcessLinux::%s(newBumpId=%" PRIu32 ") called", __FUNCTION__, newBumpId); 3452 3453 { 3454 Mutex::Locker locker (m_mem_region_cache_mutex); 3455 if (log) 3456 log->Printf ("NativeProcessLinux::%s clearing %" PRIu64 " entries from the cache", __FUNCTION__, static_cast<uint64_t> (m_mem_region_cache.size ())); 3457 m_mem_region_cache.clear (); 3458 } 3459 } 3460 3461 Error 3462 NativeProcessLinux::AllocateMemory(size_t size, uint32_t permissions, lldb::addr_t &addr) 3463 { 3464 // FIXME implementing this requires the equivalent of 3465 // InferiorCallPOSIX::InferiorCallMmap, which depends on 3466 // functional ThreadPlans working with Native*Protocol. 3467 #if 1 3468 return Error ("not implemented yet"); 3469 #else 3470 addr = LLDB_INVALID_ADDRESS; 3471 3472 unsigned prot = 0; 3473 if (permissions & lldb::ePermissionsReadable) 3474 prot |= eMmapProtRead; 3475 if (permissions & lldb::ePermissionsWritable) 3476 prot |= eMmapProtWrite; 3477 if (permissions & lldb::ePermissionsExecutable) 3478 prot |= eMmapProtExec; 3479 3480 // TODO implement this directly in NativeProcessLinux 3481 // (and lift to NativeProcessPOSIX if/when that class is 3482 // refactored out). 3483 if (InferiorCallMmap(this, addr, 0, size, prot, 3484 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) { 3485 m_addr_to_mmap_size[addr] = size; 3486 return Error (); 3487 } else { 3488 addr = LLDB_INVALID_ADDRESS; 3489 return Error("unable to allocate %" PRIu64 " bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions)); 3490 } 3491 #endif 3492 } 3493 3494 Error 3495 NativeProcessLinux::DeallocateMemory (lldb::addr_t addr) 3496 { 3497 // FIXME see comments in AllocateMemory - required lower-level 3498 // bits not in place yet (ThreadPlans) 3499 return Error ("not implemented"); 3500 } 3501 3502 lldb::addr_t 3503 NativeProcessLinux::GetSharedLibraryInfoAddress () 3504 { 3505 #if 1 3506 // punt on this for now 3507 return LLDB_INVALID_ADDRESS; 3508 #else 3509 // Return the image info address for the exe module 3510 #if 1 3511 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3512 3513 ModuleSP module_sp; 3514 Error error = GetExeModuleSP (module_sp); 3515 if (error.Fail ()) 3516 { 3517 if (log) 3518 log->Warning ("NativeProcessLinux::%s failed to retrieve exe module: %s", __FUNCTION__, error.AsCString ()); 3519 return LLDB_INVALID_ADDRESS; 3520 } 3521 3522 if (module_sp == nullptr) 3523 { 3524 if (log) 3525 log->Warning ("NativeProcessLinux::%s exe module returned was NULL", __FUNCTION__); 3526 return LLDB_INVALID_ADDRESS; 3527 } 3528 3529 ObjectFileSP object_file_sp = module_sp->GetObjectFile (); 3530 if (object_file_sp == nullptr) 3531 { 3532 if (log) 3533 log->Warning ("NativeProcessLinux::%s exe module returned a NULL object file", __FUNCTION__); 3534 return LLDB_INVALID_ADDRESS; 3535 } 3536 3537 return obj_file_sp->GetImageInfoAddress(); 3538 #else 3539 Target *target = &GetTarget(); 3540 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile(); 3541 Address addr = obj_file->GetImageInfoAddress(target); 3542 3543 if (addr.IsValid()) 3544 return addr.GetLoadAddress(target); 3545 return LLDB_INVALID_ADDRESS; 3546 #endif 3547 #endif // punt on this for now 3548 } 3549 3550 size_t 3551 NativeProcessLinux::UpdateThreads () 3552 { 3553 // The NativeProcessLinux monitoring threads are always up to date 3554 // with respect to thread state and they keep the thread list 3555 // populated properly. All this method needs to do is return the 3556 // thread count. 3557 Mutex::Locker locker (m_threads_mutex); 3558 return m_threads.size (); 3559 } 3560 3561 bool 3562 NativeProcessLinux::GetArchitecture (ArchSpec &arch) const 3563 { 3564 arch = m_arch; 3565 return true; 3566 } 3567 3568 Error 3569 NativeProcessLinux::GetSoftwareBreakpointPCOffset (NativeRegisterContextSP context_sp, uint32_t &actual_opcode_size) 3570 { 3571 // FIXME put this behind a breakpoint protocol class that can be 3572 // set per architecture. Need ARM, MIPS support here. 3573 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3574 static const uint8_t g_i386_opcode [] = { 0xCC }; 3575 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 3576 3577 switch (m_arch.GetMachine ()) 3578 { 3579 case llvm::Triple::aarch64: 3580 actual_opcode_size = static_cast<uint32_t> (sizeof(g_aarch64_opcode)); 3581 return Error (); 3582 3583 case llvm::Triple::arm: 3584 actual_opcode_size = 0; // On arm the PC don't get updated for breakpoint hits 3585 return Error (); 3586 3587 case llvm::Triple::x86: 3588 case llvm::Triple::x86_64: 3589 actual_opcode_size = static_cast<uint32_t> (sizeof(g_i386_opcode)); 3590 return Error (); 3591 3592 case llvm::Triple::mips64: 3593 case llvm::Triple::mips64el: 3594 actual_opcode_size = static_cast<uint32_t> (sizeof(g_mips64_opcode)); 3595 return Error (); 3596 3597 default: 3598 assert(false && "CPU type not supported!"); 3599 return Error ("CPU type not supported"); 3600 } 3601 } 3602 3603 Error 3604 NativeProcessLinux::SetBreakpoint (lldb::addr_t addr, uint32_t size, bool hardware) 3605 { 3606 if (hardware) 3607 return Error ("NativeProcessLinux does not support hardware breakpoints"); 3608 else 3609 return SetSoftwareBreakpoint (addr, size); 3610 } 3611 3612 Error 3613 NativeProcessLinux::GetSoftwareBreakpointTrapOpcode (size_t trap_opcode_size_hint, 3614 size_t &actual_opcode_size, 3615 const uint8_t *&trap_opcode_bytes) 3616 { 3617 // FIXME put this behind a breakpoint protocol class that can be set per 3618 // architecture. Need MIPS support here. 3619 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xd4 }; 3620 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 3621 // linux kernel does otherwise. 3622 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 }; 3623 static const uint8_t g_i386_opcode [] = { 0xCC }; 3624 static const uint8_t g_mips64_opcode[] = { 0x00, 0x00, 0x00, 0x0d }; 3625 static const uint8_t g_mips64el_opcode[] = { 0x0d, 0x00, 0x00, 0x00 }; 3626 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde }; 3627 3628 switch (m_arch.GetMachine ()) 3629 { 3630 case llvm::Triple::aarch64: 3631 trap_opcode_bytes = g_aarch64_opcode; 3632 actual_opcode_size = sizeof(g_aarch64_opcode); 3633 return Error (); 3634 3635 case llvm::Triple::arm: 3636 switch (trap_opcode_size_hint) 3637 { 3638 case 2: 3639 trap_opcode_bytes = g_thumb_breakpoint_opcode; 3640 actual_opcode_size = sizeof(g_thumb_breakpoint_opcode); 3641 return Error (); 3642 case 4: 3643 trap_opcode_bytes = g_arm_breakpoint_opcode; 3644 actual_opcode_size = sizeof(g_arm_breakpoint_opcode); 3645 return Error (); 3646 default: 3647 assert(false && "Unrecognised trap opcode size hint!"); 3648 return Error ("Unrecognised trap opcode size hint!"); 3649 } 3650 3651 case llvm::Triple::x86: 3652 case llvm::Triple::x86_64: 3653 trap_opcode_bytes = g_i386_opcode; 3654 actual_opcode_size = sizeof(g_i386_opcode); 3655 return Error (); 3656 3657 case llvm::Triple::mips64: 3658 trap_opcode_bytes = g_mips64_opcode; 3659 actual_opcode_size = sizeof(g_mips64_opcode); 3660 return Error (); 3661 3662 case llvm::Triple::mips64el: 3663 trap_opcode_bytes = g_mips64el_opcode; 3664 actual_opcode_size = sizeof(g_mips64el_opcode); 3665 return Error (); 3666 3667 default: 3668 assert(false && "CPU type not supported!"); 3669 return Error ("CPU type not supported"); 3670 } 3671 } 3672 3673 #if 0 3674 ProcessMessage::CrashReason 3675 NativeProcessLinux::GetCrashReasonForSIGSEGV(const siginfo_t *info) 3676 { 3677 ProcessMessage::CrashReason reason; 3678 assert(info->si_signo == SIGSEGV); 3679 3680 reason = ProcessMessage::eInvalidCrashReason; 3681 3682 switch (info->si_code) 3683 { 3684 default: 3685 assert(false && "unexpected si_code for SIGSEGV"); 3686 break; 3687 case SI_KERNEL: 3688 // Linux will occasionally send spurious SI_KERNEL codes. 3689 // (this is poorly documented in sigaction) 3690 // One way to get this is via unaligned SIMD loads. 3691 reason = ProcessMessage::eInvalidAddress; // for lack of anything better 3692 break; 3693 case SEGV_MAPERR: 3694 reason = ProcessMessage::eInvalidAddress; 3695 break; 3696 case SEGV_ACCERR: 3697 reason = ProcessMessage::ePrivilegedAddress; 3698 break; 3699 } 3700 3701 return reason; 3702 } 3703 #endif 3704 3705 3706 #if 0 3707 ProcessMessage::CrashReason 3708 NativeProcessLinux::GetCrashReasonForSIGILL(const siginfo_t *info) 3709 { 3710 ProcessMessage::CrashReason reason; 3711 assert(info->si_signo == SIGILL); 3712 3713 reason = ProcessMessage::eInvalidCrashReason; 3714 3715 switch (info->si_code) 3716 { 3717 default: 3718 assert(false && "unexpected si_code for SIGILL"); 3719 break; 3720 case ILL_ILLOPC: 3721 reason = ProcessMessage::eIllegalOpcode; 3722 break; 3723 case ILL_ILLOPN: 3724 reason = ProcessMessage::eIllegalOperand; 3725 break; 3726 case ILL_ILLADR: 3727 reason = ProcessMessage::eIllegalAddressingMode; 3728 break; 3729 case ILL_ILLTRP: 3730 reason = ProcessMessage::eIllegalTrap; 3731 break; 3732 case ILL_PRVOPC: 3733 reason = ProcessMessage::ePrivilegedOpcode; 3734 break; 3735 case ILL_PRVREG: 3736 reason = ProcessMessage::ePrivilegedRegister; 3737 break; 3738 case ILL_COPROC: 3739 reason = ProcessMessage::eCoprocessorError; 3740 break; 3741 case ILL_BADSTK: 3742 reason = ProcessMessage::eInternalStackError; 3743 break; 3744 } 3745 3746 return reason; 3747 } 3748 #endif 3749 3750 #if 0 3751 ProcessMessage::CrashReason 3752 NativeProcessLinux::GetCrashReasonForSIGFPE(const siginfo_t *info) 3753 { 3754 ProcessMessage::CrashReason reason; 3755 assert(info->si_signo == SIGFPE); 3756 3757 reason = ProcessMessage::eInvalidCrashReason; 3758 3759 switch (info->si_code) 3760 { 3761 default: 3762 assert(false && "unexpected si_code for SIGFPE"); 3763 break; 3764 case FPE_INTDIV: 3765 reason = ProcessMessage::eIntegerDivideByZero; 3766 break; 3767 case FPE_INTOVF: 3768 reason = ProcessMessage::eIntegerOverflow; 3769 break; 3770 case FPE_FLTDIV: 3771 reason = ProcessMessage::eFloatDivideByZero; 3772 break; 3773 case FPE_FLTOVF: 3774 reason = ProcessMessage::eFloatOverflow; 3775 break; 3776 case FPE_FLTUND: 3777 reason = ProcessMessage::eFloatUnderflow; 3778 break; 3779 case FPE_FLTRES: 3780 reason = ProcessMessage::eFloatInexactResult; 3781 break; 3782 case FPE_FLTINV: 3783 reason = ProcessMessage::eFloatInvalidOperation; 3784 break; 3785 case FPE_FLTSUB: 3786 reason = ProcessMessage::eFloatSubscriptRange; 3787 break; 3788 } 3789 3790 return reason; 3791 } 3792 #endif 3793 3794 #if 0 3795 ProcessMessage::CrashReason 3796 NativeProcessLinux::GetCrashReasonForSIGBUS(const siginfo_t *info) 3797 { 3798 ProcessMessage::CrashReason reason; 3799 assert(info->si_signo == SIGBUS); 3800 3801 reason = ProcessMessage::eInvalidCrashReason; 3802 3803 switch (info->si_code) 3804 { 3805 default: 3806 assert(false && "unexpected si_code for SIGBUS"); 3807 break; 3808 case BUS_ADRALN: 3809 reason = ProcessMessage::eIllegalAlignment; 3810 break; 3811 case BUS_ADRERR: 3812 reason = ProcessMessage::eIllegalAddress; 3813 break; 3814 case BUS_OBJERR: 3815 reason = ProcessMessage::eHardwareError; 3816 break; 3817 } 3818 3819 return reason; 3820 } 3821 #endif 3822 3823 Error 3824 NativeProcessLinux::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t watch_flags, bool hardware) 3825 { 3826 // The base SetWatchpoint will end up executing monitor operations. Let's lock the monitor 3827 // for it. 3828 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3829 return NativeProcessProtocol::SetWatchpoint(addr, size, watch_flags, hardware); 3830 } 3831 3832 Error 3833 NativeProcessLinux::RemoveWatchpoint (lldb::addr_t addr) 3834 { 3835 // The base RemoveWatchpoint will end up executing monitor operations. Let's lock the monitor 3836 // for it. 3837 Monitor::ScopedOperationLock monitor_lock(*m_monitor_up); 3838 return NativeProcessProtocol::RemoveWatchpoint(addr); 3839 } 3840 3841 Error 3842 NativeProcessLinux::ReadMemory (lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3843 { 3844 ReadOperation op(addr, buf, size, bytes_read); 3845 m_monitor_up->DoOperation(&op); 3846 return op.GetError (); 3847 } 3848 3849 Error 3850 NativeProcessLinux::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) 3851 { 3852 Error error = ReadMemory(addr, buf, size, bytes_read); 3853 if (error.Fail()) return error; 3854 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); 3855 } 3856 3857 Error 3858 NativeProcessLinux::WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) 3859 { 3860 WriteOperation op(addr, buf, size, bytes_written); 3861 m_monitor_up->DoOperation(&op); 3862 return op.GetError (); 3863 } 3864 3865 Error 3866 NativeProcessLinux::ReadRegisterValue(lldb::tid_t tid, uint32_t offset, const char* reg_name, 3867 uint32_t size, RegisterValue &value) 3868 { 3869 ReadRegOperation op(tid, offset, reg_name, value); 3870 m_monitor_up->DoOperation(&op); 3871 return op.GetError(); 3872 } 3873 3874 Error 3875 NativeProcessLinux::WriteRegisterValue(lldb::tid_t tid, unsigned offset, 3876 const char* reg_name, const RegisterValue &value) 3877 { 3878 WriteRegOperation op(tid, offset, reg_name, value); 3879 m_monitor_up->DoOperation(&op); 3880 return op.GetError(); 3881 } 3882 3883 Error 3884 NativeProcessLinux::ReadGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3885 { 3886 ReadGPROperation op(tid, buf, buf_size); 3887 m_monitor_up->DoOperation(&op); 3888 return op.GetError(); 3889 } 3890 3891 Error 3892 NativeProcessLinux::ReadFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3893 { 3894 ReadFPROperation op(tid, buf, buf_size); 3895 m_monitor_up->DoOperation(&op); 3896 return op.GetError(); 3897 } 3898 3899 Error 3900 NativeProcessLinux::ReadRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3901 { 3902 ReadRegisterSetOperation op(tid, buf, buf_size, regset); 3903 m_monitor_up->DoOperation(&op); 3904 return op.GetError(); 3905 } 3906 3907 Error 3908 NativeProcessLinux::WriteGPR(lldb::tid_t tid, void *buf, size_t buf_size) 3909 { 3910 WriteGPROperation op(tid, buf, buf_size); 3911 m_monitor_up->DoOperation(&op); 3912 return op.GetError(); 3913 } 3914 3915 Error 3916 NativeProcessLinux::WriteFPR(lldb::tid_t tid, void *buf, size_t buf_size) 3917 { 3918 WriteFPROperation op(tid, buf, buf_size); 3919 m_monitor_up->DoOperation(&op); 3920 return op.GetError(); 3921 } 3922 3923 Error 3924 NativeProcessLinux::WriteRegisterSet(lldb::tid_t tid, void *buf, size_t buf_size, unsigned int regset) 3925 { 3926 WriteRegisterSetOperation op(tid, buf, buf_size, regset); 3927 m_monitor_up->DoOperation(&op); 3928 return op.GetError(); 3929 } 3930 3931 Error 3932 NativeProcessLinux::Resume (lldb::tid_t tid, uint32_t signo) 3933 { 3934 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 3935 3936 if (log) 3937 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " with signal %s", __FUNCTION__, tid, 3938 GetUnixSignals().GetSignalAsCString (signo)); 3939 ResumeOperation op (tid, signo); 3940 m_monitor_up->DoOperation (&op); 3941 if (log) 3942 log->Printf ("NativeProcessLinux::%s() resuming thread = %" PRIu64 " result = %s", __FUNCTION__, tid, op.GetError().Success() ? "true" : "false"); 3943 return op.GetError(); 3944 } 3945 3946 Error 3947 NativeProcessLinux::SingleStep(lldb::tid_t tid, uint32_t signo) 3948 { 3949 SingleStepOperation op(tid, signo); 3950 m_monitor_up->DoOperation(&op); 3951 return op.GetError(); 3952 } 3953 3954 Error 3955 NativeProcessLinux::GetSignalInfo(lldb::tid_t tid, void *siginfo) 3956 { 3957 SiginfoOperation op(tid, siginfo); 3958 m_monitor_up->DoOperation(&op); 3959 return op.GetError(); 3960 } 3961 3962 Error 3963 NativeProcessLinux::GetEventMessage(lldb::tid_t tid, unsigned long *message) 3964 { 3965 EventMessageOperation op(tid, message); 3966 m_monitor_up->DoOperation(&op); 3967 return op.GetError(); 3968 } 3969 3970 Error 3971 NativeProcessLinux::Detach(lldb::tid_t tid) 3972 { 3973 if (tid == LLDB_INVALID_THREAD_ID) 3974 return Error(); 3975 3976 DetachOperation op(tid); 3977 m_monitor_up->DoOperation(&op); 3978 return op.GetError(); 3979 } 3980 3981 bool 3982 NativeProcessLinux::DupDescriptor(const char *path, int fd, int flags) 3983 { 3984 int target_fd = open(path, flags, 0666); 3985 3986 if (target_fd == -1) 3987 return false; 3988 3989 if (dup2(target_fd, fd) == -1) 3990 return false; 3991 3992 return (close(target_fd) == -1) ? false : true; 3993 } 3994 3995 void 3996 NativeProcessLinux::StartMonitorThread(const InitialOperation &initial_operation, Error &error) 3997 { 3998 m_monitor_up.reset(new Monitor(initial_operation, this)); 3999 error = m_monitor_up->Initialize(); 4000 if (error.Fail()) { 4001 m_monitor_up.reset(); 4002 } 4003 } 4004 4005 bool 4006 NativeProcessLinux::HasThreadNoLock (lldb::tid_t thread_id) 4007 { 4008 for (auto thread_sp : m_threads) 4009 { 4010 assert (thread_sp && "thread list should not contain NULL threads"); 4011 if (thread_sp->GetID () == thread_id) 4012 { 4013 // We have this thread. 4014 return true; 4015 } 4016 } 4017 4018 // We don't have this thread. 4019 return false; 4020 } 4021 4022 NativeThreadProtocolSP 4023 NativeProcessLinux::MaybeGetThreadNoLock (lldb::tid_t thread_id) 4024 { 4025 // CONSIDER organize threads by map - we can do better than linear. 4026 for (auto thread_sp : m_threads) 4027 { 4028 if (thread_sp->GetID () == thread_id) 4029 return thread_sp; 4030 } 4031 4032 // We don't have this thread. 4033 return NativeThreadProtocolSP (); 4034 } 4035 4036 bool 4037 NativeProcessLinux::StopTrackingThread (lldb::tid_t thread_id) 4038 { 4039 Mutex::Locker locker (m_threads_mutex); 4040 for (auto it = m_threads.begin (); it != m_threads.end (); ++it) 4041 { 4042 if (*it && ((*it)->GetID () == thread_id)) 4043 { 4044 m_threads.erase (it); 4045 return true; 4046 } 4047 } 4048 4049 // Didn't find it. 4050 return false; 4051 } 4052 4053 NativeThreadProtocolSP 4054 NativeProcessLinux::AddThread (lldb::tid_t thread_id) 4055 { 4056 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 4057 4058 Mutex::Locker locker (m_threads_mutex); 4059 4060 if (log) 4061 { 4062 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " adding thread with tid %" PRIu64, 4063 __FUNCTION__, 4064 GetID (), 4065 thread_id); 4066 } 4067 4068 assert (!HasThreadNoLock (thread_id) && "attempted to add a thread by id that already exists"); 4069 4070 // If this is the first thread, save it as the current thread 4071 if (m_threads.empty ()) 4072 SetCurrentThreadID (thread_id); 4073 4074 NativeThreadProtocolSP thread_sp (new NativeThreadLinux (this, thread_id)); 4075 m_threads.push_back (thread_sp); 4076 4077 return thread_sp; 4078 } 4079 4080 Error 4081 NativeProcessLinux::FixupBreakpointPCAsNeeded (NativeThreadProtocolSP &thread_sp) 4082 { 4083 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 4084 4085 Error error; 4086 4087 // Get a linux thread pointer. 4088 if (!thread_sp) 4089 { 4090 error.SetErrorString ("null thread_sp"); 4091 if (log) 4092 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 4093 return error; 4094 } 4095 std::shared_ptr<NativeThreadLinux> linux_thread_sp = std::static_pointer_cast<NativeThreadLinux> (thread_sp); 4096 4097 // Find out the size of a breakpoint (might depend on where we are in the code). 4098 NativeRegisterContextSP context_sp = linux_thread_sp->GetRegisterContext (); 4099 if (!context_sp) 4100 { 4101 error.SetErrorString ("cannot get a NativeRegisterContext for the thread"); 4102 if (log) 4103 log->Printf ("NativeProcessLinux::%s failed: %s", __FUNCTION__, error.AsCString ()); 4104 return error; 4105 } 4106 4107 uint32_t breakpoint_size = 0; 4108 error = GetSoftwareBreakpointPCOffset (context_sp, breakpoint_size); 4109 if (error.Fail ()) 4110 { 4111 if (log) 4112 log->Printf ("NativeProcessLinux::%s GetBreakpointSize() failed: %s", __FUNCTION__, error.AsCString ()); 4113 return error; 4114 } 4115 else 4116 { 4117 if (log) 4118 log->Printf ("NativeProcessLinux::%s breakpoint size: %" PRIu32, __FUNCTION__, breakpoint_size); 4119 } 4120 4121 // First try probing for a breakpoint at a software breakpoint location: PC - breakpoint size. 4122 const lldb::addr_t initial_pc_addr = context_sp->GetPC (); 4123 lldb::addr_t breakpoint_addr = initial_pc_addr; 4124 if (breakpoint_size > 0) 4125 { 4126 // Do not allow breakpoint probe to wrap around. 4127 if (breakpoint_addr >= breakpoint_size) 4128 breakpoint_addr -= breakpoint_size; 4129 } 4130 4131 // Check if we stopped because of a breakpoint. 4132 NativeBreakpointSP breakpoint_sp; 4133 error = m_breakpoint_list.GetBreakpoint (breakpoint_addr, breakpoint_sp); 4134 if (!error.Success () || !breakpoint_sp) 4135 { 4136 // We didn't find one at a software probe location. Nothing to do. 4137 if (log) 4138 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " no lldb breakpoint found at current pc with adjustment: 0x%" PRIx64, __FUNCTION__, GetID (), breakpoint_addr); 4139 return Error (); 4140 } 4141 4142 // If the breakpoint is not a software breakpoint, nothing to do. 4143 if (!breakpoint_sp->IsSoftwareBreakpoint ()) 4144 { 4145 if (log) 4146 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " breakpoint found at 0x%" PRIx64 ", not software, nothing to adjust", __FUNCTION__, GetID (), breakpoint_addr); 4147 return Error (); 4148 } 4149 4150 // 4151 // We have a software breakpoint and need to adjust the PC. 4152 // 4153 4154 // Sanity check. 4155 if (breakpoint_size == 0) 4156 { 4157 // Nothing to do! How did we get here? 4158 if (log) 4159 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); 4160 return Error (); 4161 } 4162 4163 // Change the program counter. 4164 if (log) 4165 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": changing PC from 0x%" PRIx64 " to 0x%" PRIx64, __FUNCTION__, GetID (), linux_thread_sp->GetID (), initial_pc_addr, breakpoint_addr); 4166 4167 error = context_sp->SetPC (breakpoint_addr); 4168 if (error.Fail ()) 4169 { 4170 if (log) 4171 log->Printf ("NativeProcessLinux::%s pid %" PRIu64 " tid %" PRIu64 ": failed to set PC: %s", __FUNCTION__, GetID (), linux_thread_sp->GetID (), error.AsCString ()); 4172 return error; 4173 } 4174 4175 return error; 4176 } 4177 4178 Error 4179 NativeProcessLinux::GetLoadedModuleFileSpec(const char* module_path, FileSpec& file_spec) 4180 { 4181 char maps_file_name[32]; 4182 snprintf(maps_file_name, sizeof(maps_file_name), "/proc/%" PRIu64 "/maps", GetID()); 4183 4184 FileSpec maps_file_spec(maps_file_name, false); 4185 if (!maps_file_spec.Exists()) { 4186 file_spec.Clear(); 4187 return Error("/proc/%" PRIu64 "/maps file doesn't exists!", GetID()); 4188 } 4189 4190 FileSpec module_file_spec(module_path, true); 4191 4192 std::ifstream maps_file(maps_file_name); 4193 std::string maps_data_str((std::istreambuf_iterator<char>(maps_file)), std::istreambuf_iterator<char>()); 4194 StringRef maps_data(maps_data_str.c_str()); 4195 4196 while (!maps_data.empty()) 4197 { 4198 StringRef maps_row; 4199 std::tie(maps_row, maps_data) = maps_data.split('\n'); 4200 4201 SmallVector<StringRef, 16> maps_columns; 4202 maps_row.split(maps_columns, StringRef(" "), -1, false); 4203 4204 if (maps_columns.size() >= 6) 4205 { 4206 file_spec.SetFile(maps_columns[5].str().c_str(), false); 4207 if (file_spec.GetFilename() == module_file_spec.GetFilename()) 4208 return Error(); 4209 } 4210 } 4211 4212 file_spec.Clear(); 4213 return Error("Module file (%s) not found in /proc/%" PRIu64 "/maps file!", 4214 module_file_spec.GetFilename().AsCString(), GetID()); 4215 } 4216 4217 Error 4218 NativeProcessLinux::DoResume( 4219 lldb::tid_t tid, 4220 NativeThreadLinux::ResumeThreadFunction request_thread_resume_function, 4221 bool error_when_already_running) 4222 { 4223 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4224 4225 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 4226 lldbassert(thread_sp != nullptr); 4227 4228 auto& context = thread_sp->GetThreadContext(); 4229 // Tell the thread to resume if we don't already think it is running. 4230 const bool is_stopped = StateIsStoppedState(thread_sp->GetState(), true); 4231 4232 lldbassert(!(error_when_already_running && !is_stopped)); 4233 4234 if (!is_stopped) 4235 { 4236 // It's not an error, just a log, if the error_when_already_running flag is not set. 4237 // This covers cases where, for instance, we're just trying to resume all threads 4238 // from the user side. 4239 if (log) 4240 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " optional resume skipped since it is already running", 4241 __FUNCTION__, 4242 tid); 4243 return Error(); 4244 } 4245 4246 // Before we do the resume below, first check if we have a pending 4247 // stop notification this is currently or was previously waiting for 4248 // this thread to stop. This is potentially a buggy situation since 4249 // we're ostensibly waiting for threads to stop before we send out the 4250 // pending notification, and here we are resuming one before we send 4251 // out the pending stop notification. 4252 if (m_pending_notification_up && log) 4253 { 4254 if (m_pending_notification_up->wait_for_stop_tids.count (tid) > 0) 4255 { 4256 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that is actively waiting for this thread to stop. Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid); 4257 } 4258 else if (m_pending_notification_up->original_wait_for_stop_tids.count (tid) > 0) 4259 { 4260 log->Printf("NativeProcessLinux::%s about to resume tid %" PRIu64 " per explicit request but we have a pending stop notification (tid %" PRIu64 ") that hasn't fired yet and this is one of the threads we had been waiting on (and already marked satisfied for this tid). Valid sequence of events?", __FUNCTION__, tid, m_pending_notification_up->triggering_tid); 4261 for (auto tid : m_pending_notification_up->wait_for_stop_tids) 4262 { 4263 log->Printf("NativeProcessLinux::%s tid %" PRIu64 " deferred stop notification still waiting on tid %" PRIu64, 4264 __FUNCTION__, 4265 m_pending_notification_up->triggering_tid, 4266 tid); 4267 } 4268 } 4269 } 4270 4271 // Request a resume. We expect this to be synchronous and the system 4272 // to reflect it is running after this completes. 4273 const auto error = request_thread_resume_function (tid, false); 4274 if (error.Success()) 4275 context.request_resume_function = request_thread_resume_function; 4276 else if (log) 4277 { 4278 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 4279 __FUNCTION__, tid, error.AsCString ()); 4280 } 4281 4282 return error; 4283 } 4284 4285 //===----------------------------------------------------------------------===// 4286 4287 void 4288 NativeProcessLinux::StopThreads(const lldb::tid_t triggering_tid, 4289 const ThreadIDSet &wait_for_stop_tids) 4290 { 4291 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4292 std::lock_guard<std::mutex> lock(m_event_mutex); 4293 4294 if (log) 4295 { 4296 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", wait_for_stop_tids.size(): %zd)", 4297 __FUNCTION__, triggering_tid, wait_for_stop_tids.size()); 4298 } 4299 4300 DoStopThreads(PendingNotificationUP(new PendingNotification( 4301 triggering_tid, wait_for_stop_tids, ThreadIDSet()))); 4302 4303 if (log) 4304 { 4305 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4306 } 4307 } 4308 4309 void 4310 NativeProcessLinux::StopRunningThreads(const lldb::tid_t triggering_tid) 4311 { 4312 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4313 std::lock_guard<std::mutex> lock(m_event_mutex); 4314 4315 if (log) 4316 { 4317 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ")", 4318 __FUNCTION__, triggering_tid); 4319 } 4320 4321 DoStopThreads(PendingNotificationUP(new PendingNotification(triggering_tid))); 4322 4323 if (log) 4324 { 4325 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4326 } 4327 } 4328 4329 void 4330 NativeProcessLinux::StopRunningThreadsWithSkipTID(lldb::tid_t triggering_tid, 4331 lldb::tid_t skip_stop_request_tid) 4332 { 4333 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4334 std::lock_guard<std::mutex> lock(m_event_mutex); 4335 4336 if (log) 4337 { 4338 log->Printf("NativeProcessLinux::%s about to process event: (triggering_tid: %" PRIu64 ", skip_stop_request_tid: %" PRIu64 ")", 4339 __FUNCTION__, triggering_tid, skip_stop_request_tid); 4340 } 4341 4342 DoStopThreads(PendingNotificationUP(new PendingNotification( 4343 triggering_tid, 4344 ThreadIDSet(), 4345 skip_stop_request_tid != LLDB_INVALID_THREAD_ID ? NativeProcessLinux::ThreadIDSet {skip_stop_request_tid} : ThreadIDSet ()))); 4346 4347 if (log) 4348 { 4349 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4350 } 4351 } 4352 4353 void 4354 NativeProcessLinux::SignalIfRequirementsSatisfied() 4355 { 4356 if (m_pending_notification_up && m_pending_notification_up->wait_for_stop_tids.empty ()) 4357 { 4358 SetCurrentThreadID(m_pending_notification_up->triggering_tid); 4359 SetState(StateType::eStateStopped, true); 4360 m_pending_notification_up.reset(); 4361 } 4362 } 4363 4364 bool 4365 NativeProcessLinux::RequestStopOnAllSpecifiedThreads() 4366 { 4367 // Request a stop for all the thread stops that need to be stopped 4368 // and are not already known to be stopped. Keep a list of all the 4369 // threads from which we still need to hear a stop reply. 4370 4371 ThreadIDSet sent_tids; 4372 for (auto tid : m_pending_notification_up->wait_for_stop_tids) 4373 { 4374 // Validate we know about all tids for which we must first receive a stop before 4375 // triggering the deferred stop notification. 4376 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 4377 lldbassert(thread_sp != nullptr); 4378 4379 // If the pending stop thread is currently running, we need to send it a stop request. 4380 if (StateIsRunningState(thread_sp->GetState())) 4381 { 4382 thread_sp->RequestStop(); 4383 sent_tids.insert (tid); 4384 } 4385 } 4386 // We only need to wait for the sent_tids - so swap our wait set 4387 // to the sent tids. The rest are already stopped and we won't 4388 // be receiving stop notifications for them. 4389 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids); 4390 4391 // Succeeded, keep running. 4392 return true; 4393 } 4394 4395 void 4396 NativeProcessLinux::RequestStopOnAllRunningThreads() 4397 { 4398 // Request a stop for all the thread stops that need to be stopped 4399 // and are not already known to be stopped. Keep a list of all the 4400 // threads from which we still need to hear a stop reply. 4401 4402 ThreadIDSet sent_tids; 4403 for (const auto &thread_sp: m_threads) 4404 { 4405 // We only care about running threads 4406 if (StateIsStoppedState(thread_sp->GetState(), true)) 4407 continue; 4408 4409 const lldb::tid_t tid = thread_sp->GetID(); 4410 4411 // Request this thread stop if the tid stop request is not explicitly ignored. 4412 const bool skip_stop_request = m_pending_notification_up->skip_stop_request_tids.count (tid) > 0; 4413 if (!skip_stop_request) 4414 static_pointer_cast<NativeThreadLinux>(thread_sp)->RequestStop(); 4415 4416 // Even if we skipped sending the stop request for other reasons (like stepping), 4417 // we still need to wait for that stepping thread to notify completion/stop. 4418 sent_tids.insert (tid); 4419 } 4420 4421 // Set the wait list to the set of tids for which we requested stops. 4422 m_pending_notification_up->wait_for_stop_tids.swap (sent_tids); 4423 } 4424 4425 4426 Error 4427 NativeProcessLinux::ThreadDidStop (lldb::tid_t tid, bool initiated_by_llgs) 4428 { 4429 // Ensure we know about the thread. 4430 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 4431 lldbassert(thread_sp != nullptr); 4432 4433 // Update the global list of known thread states. This one is definitely stopped. 4434 auto& context = thread_sp->GetThreadContext(); 4435 const auto stop_was_requested = context.stop_requested; 4436 context.stop_requested = false; 4437 4438 // If we have a pending notification, remove this from the set. 4439 if (m_pending_notification_up) 4440 { 4441 m_pending_notification_up->wait_for_stop_tids.erase(tid); 4442 SignalIfRequirementsSatisfied(); 4443 } 4444 4445 Error error; 4446 if (initiated_by_llgs && context.request_resume_function && !stop_was_requested) 4447 { 4448 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4449 // We can end up here if stop was initiated by LLGS but by this time a 4450 // thread stop has occurred - maybe initiated by another event. 4451 if (log) 4452 log->Printf("Resuming thread %" PRIu64 " since stop wasn't requested", tid); 4453 error = context.request_resume_function (tid, true); 4454 if (error.Fail() && log) 4455 { 4456 log->Printf("NativeProcessLinux::%s failed to resume thread tid %" PRIu64 ": %s", 4457 __FUNCTION__, tid, error.AsCString ()); 4458 } 4459 } 4460 return error; 4461 } 4462 4463 void 4464 NativeProcessLinux::DoStopThreads(PendingNotificationUP &¬ification_up) 4465 { 4466 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4467 if (m_pending_notification_up && log) 4468 { 4469 // Yikes - we've already got a pending signal notification in progress. 4470 // Log this info. We lose the pending notification here. 4471 log->Printf("NativeProcessLinux::%s dropping existing pending signal notification for tid %" PRIu64 ", to be replaced with signal for tid %" PRIu64, 4472 __FUNCTION__, 4473 m_pending_notification_up->triggering_tid, 4474 notification_up->triggering_tid); 4475 } 4476 m_pending_notification_up = std::move(notification_up); 4477 4478 if (m_pending_notification_up->request_stop_on_all_unstopped_threads) 4479 RequestStopOnAllRunningThreads(); 4480 else 4481 { 4482 if (!RequestStopOnAllSpecifiedThreads()) 4483 return; 4484 } 4485 4486 SignalIfRequirementsSatisfied(); 4487 } 4488 4489 void 4490 NativeProcessLinux::ThreadWasCreated (lldb::tid_t tid) 4491 { 4492 auto thread_sp = std::static_pointer_cast<NativeThreadLinux>(GetThreadByID(tid)); 4493 lldbassert(thread_sp != nullptr); 4494 4495 if (m_pending_notification_up && StateIsRunningState(thread_sp->GetState())) 4496 { 4497 // We will need to wait for this new thread to stop as well before firing the 4498 // notification. 4499 m_pending_notification_up->wait_for_stop_tids.insert(tid); 4500 thread_sp->RequestStop(); 4501 } 4502 } 4503 4504 void 4505 NativeProcessLinux::ThreadDidDie (lldb::tid_t tid) 4506 { 4507 // If we have a pending notification, remove this from the set. 4508 if (m_pending_notification_up) 4509 { 4510 m_pending_notification_up->wait_for_stop_tids.erase(tid); 4511 SignalIfRequirementsSatisfied(); 4512 } 4513 } 4514 4515 Error 4516 NativeProcessLinux::NotifyThreadStop (lldb::tid_t tid, bool initiated_by_llgs) 4517 { 4518 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4519 std::lock_guard<std::mutex> lock(m_event_mutex); 4520 4521 if (log) 4522 { 4523 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ", %sinitiated by llgs)", 4524 __FUNCTION__, tid, initiated_by_llgs?"":"not "); 4525 } 4526 4527 Error error = ThreadDidStop (tid, initiated_by_llgs); 4528 4529 if (log) 4530 { 4531 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4532 } 4533 4534 return error; 4535 } 4536 4537 Error 4538 NativeProcessLinux::RequestThreadResume (lldb::tid_t tid, 4539 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function) 4540 { 4541 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4542 std::lock_guard<std::mutex> lock(m_event_mutex); 4543 4544 if (log) 4545 { 4546 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", 4547 __FUNCTION__, tid); 4548 } 4549 4550 Error error = DoResume(tid, request_thread_resume_function, true); 4551 4552 if (log) 4553 { 4554 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4555 } 4556 4557 return error; 4558 } 4559 4560 Error 4561 NativeProcessLinux::RequestThreadResumeAsNeeded (lldb::tid_t tid, 4562 const NativeThreadLinux::ResumeThreadFunction &request_thread_resume_function) 4563 { 4564 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4565 std::lock_guard<std::mutex> lock(m_event_mutex); 4566 4567 if (log) 4568 { 4569 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", 4570 __FUNCTION__, tid); 4571 } 4572 4573 Error error = DoResume (tid, request_thread_resume_function, false); 4574 4575 if (log) 4576 { 4577 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4578 } 4579 4580 return error; 4581 } 4582 4583 void 4584 NativeProcessLinux::NotifyThreadCreate(lldb::tid_t tid) 4585 { 4586 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4587 std::lock_guard<std::mutex> lock(m_event_mutex); 4588 4589 if (log) 4590 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid); 4591 4592 ThreadWasCreated(tid); 4593 4594 if (log) 4595 { 4596 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4597 } 4598 } 4599 4600 void 4601 NativeProcessLinux::NotifyThreadDeath (lldb::tid_t tid) 4602 { 4603 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4604 std::lock_guard<std::mutex> lock(m_event_mutex); 4605 4606 if (log) 4607 { 4608 log->Printf("NativeProcessLinux::%s about to process event: (tid: %" PRIu64 ")", __FUNCTION__, tid); 4609 } 4610 4611 ThreadDidDie(tid); 4612 4613 if (log) 4614 { 4615 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4616 } 4617 } 4618 4619 void 4620 NativeProcessLinux::ResetForExec () 4621 { 4622 Log *const log = GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD); 4623 std::lock_guard<std::mutex> lock(m_event_mutex); 4624 4625 if (log) 4626 { 4627 log->Printf("NativeProcessLinux::%s about to process event", __FUNCTION__); 4628 } 4629 4630 // Clear the pending notification if there was one. 4631 m_pending_notification_up.reset (); 4632 4633 if (log) 4634 { 4635 log->Printf("NativeProcessLinux::%s event processing done", __FUNCTION__); 4636 } 4637 } 4638