1 //===-- NativeProcessNetBSD.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 "NativeProcessNetBSD.h" 11 12 // C Includes 13 14 // C++ Includes 15 16 // Other libraries and framework includes 17 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h" 18 #include "lldb/Core/State.h" 19 #include "lldb/Host/HostProcess.h" 20 #include "lldb/Host/common/NativeBreakpoint.h" 21 #include "lldb/Host/common/NativeRegisterContext.h" 22 #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 23 #include "lldb/Target/Process.h" 24 #include "llvm/Support/Errno.h" 25 26 // System includes - They have to be included after framework includes because 27 // they define some 28 // macros which collide with variable names in other modules 29 // clang-format off 30 #include <sys/types.h> 31 #include <sys/ptrace.h> 32 #include <sys/sysctl.h> 33 #include <sys/wait.h> 34 #include <uvm/uvm_prot.h> 35 #include <elf.h> 36 #include <util.h> 37 // clang-format on 38 39 using namespace lldb; 40 using namespace lldb_private; 41 using namespace lldb_private::process_netbsd; 42 using namespace llvm; 43 44 // Simple helper function to ensure flags are enabled on the given file 45 // descriptor. 46 static Status EnsureFDFlags(int fd, int flags) { 47 Status error; 48 49 int status = fcntl(fd, F_GETFL); 50 if (status == -1) { 51 error.SetErrorToErrno(); 52 return error; 53 } 54 55 if (fcntl(fd, F_SETFL, status | flags) == -1) { 56 error.SetErrorToErrno(); 57 return error; 58 } 59 60 return error; 61 } 62 63 // ----------------------------------------------------------------------------- 64 // Public Static Methods 65 // ----------------------------------------------------------------------------- 66 67 llvm::Expected<NativeProcessProtocolSP> 68 NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info, 69 NativeDelegate &native_delegate, 70 MainLoop &mainloop) const { 71 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 72 73 Status status; 74 ::pid_t pid = ProcessLauncherPosixFork() 75 .LaunchProcess(launch_info, status) 76 .GetProcessId(); 77 LLDB_LOG(log, "pid = {0:x}", pid); 78 if (status.Fail()) { 79 LLDB_LOG(log, "failed to launch process: {0}", status); 80 return status.ToError(); 81 } 82 83 // Wait for the child process to trap on its call to execve. 84 int wstatus; 85 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0); 86 assert(wpid == pid); 87 (void)wpid; 88 if (!WIFSTOPPED(wstatus)) { 89 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}", 90 WaitStatus::Decode(wstatus)); 91 return llvm::make_error<StringError>("Could not sync with inferior process", 92 llvm::inconvertibleErrorCode()); 93 } 94 LLDB_LOG(log, "inferior started, now in stopped state"); 95 96 ArchSpec arch; 97 if ((status = ResolveProcessArchitecture(pid, arch)).Fail()) 98 return status.ToError(); 99 100 // Set the architecture to the exe architecture. 101 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid, 102 arch.GetArchitectureName()); 103 104 std::shared_ptr<NativeProcessNetBSD> process_sp(new NativeProcessNetBSD( 105 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate, 106 arch, mainloop)); 107 108 status = process_sp->ReinitializeThreads(); 109 if (status.Fail()) 110 return status.ToError(); 111 112 for (const auto &thread_sp : process_sp->m_threads) { 113 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal( 114 SIGSTOP); 115 } 116 process_sp->SetState(StateType::eStateStopped); 117 118 return process_sp; 119 } 120 121 llvm::Expected<NativeProcessProtocolSP> NativeProcessNetBSD::Factory::Attach( 122 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 123 MainLoop &mainloop) const { 124 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 125 LLDB_LOG(log, "pid = {0:x}", pid); 126 127 // Retrieve the architecture for the running process. 128 ArchSpec arch; 129 Status status = ResolveProcessArchitecture(pid, arch); 130 if (!status.Success()) 131 return status.ToError(); 132 133 std::shared_ptr<NativeProcessNetBSD> process_sp( 134 new NativeProcessNetBSD(pid, -1, native_delegate, arch, mainloop)); 135 136 status = process_sp->Attach(); 137 if (!status.Success()) 138 return status.ToError(); 139 140 return process_sp; 141 } 142 143 // ----------------------------------------------------------------------------- 144 // Public Instance Methods 145 // ----------------------------------------------------------------------------- 146 147 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd, 148 NativeDelegate &delegate, 149 const ArchSpec &arch, 150 MainLoop &mainloop) 151 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) { 152 if (m_terminal_fd != -1) { 153 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 154 assert(status.Success()); 155 } 156 157 Status status; 158 m_sigchld_handle = mainloop.RegisterSignal( 159 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 160 assert(m_sigchld_handle && status.Success()); 161 } 162 163 // Handles all waitpid events from the inferior process. 164 void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) { 165 switch (signal) { 166 case SIGTRAP: 167 return MonitorSIGTRAP(pid); 168 case SIGSTOP: 169 return MonitorSIGSTOP(pid); 170 default: 171 return MonitorSignal(pid, signal); 172 } 173 } 174 175 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) { 176 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 177 178 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid); 179 180 /* Stop Tracking All Threads attached to Process */ 181 m_threads.clear(); 182 183 SetExitStatus(status, true); 184 185 // Notify delegate that our process has exited. 186 SetState(StateType::eStateExited, true); 187 } 188 189 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) { 190 ptrace_siginfo_t info; 191 192 const auto siginfo_err = 193 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 194 195 // Get details on the signal raised. 196 if (siginfo_err.Success()) { 197 // Handle SIGSTOP from LLGS (LLDB GDB Server) 198 if (info.psi_siginfo.si_code == SI_USER && 199 info.psi_siginfo.si_pid == ::getpid()) { 200 /* Stop Tracking All Threads attached to Process */ 201 for (const auto &thread_sp : m_threads) { 202 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal( 203 SIGSTOP, &info.psi_siginfo); 204 } 205 } 206 } 207 } 208 209 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) { 210 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 211 ptrace_siginfo_t info; 212 213 const auto siginfo_err = 214 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 215 216 // Get details on the signal raised. 217 if (siginfo_err.Fail()) { 218 return; 219 } 220 221 switch (info.psi_siginfo.si_code) { 222 case TRAP_BRKPT: 223 for (const auto &thread_sp : m_threads) { 224 static_pointer_cast<NativeThreadNetBSD>(thread_sp) 225 ->SetStoppedByBreakpoint(); 226 FixupBreakpointPCAsNeeded( 227 *static_pointer_cast<NativeThreadNetBSD>(thread_sp)); 228 } 229 SetState(StateType::eStateStopped, true); 230 break; 231 case TRAP_TRACE: 232 for (const auto &thread_sp : m_threads) { 233 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedByTrace(); 234 } 235 SetState(StateType::eStateStopped, true); 236 break; 237 case TRAP_EXEC: { 238 Status error = ReinitializeThreads(); 239 if (error.Fail()) { 240 SetState(StateType::eStateInvalid); 241 return; 242 } 243 244 // Let our delegate know we have just exec'd. 245 NotifyDidExec(); 246 247 for (const auto &thread_sp : m_threads) { 248 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedByExec(); 249 } 250 SetState(StateType::eStateStopped, true); 251 } break; 252 case TRAP_DBREG: { 253 // If a watchpoint was hit, report it 254 uint32_t wp_index; 255 Status error = 256 static_pointer_cast<NativeThreadNetBSD>(m_threads[info.psi_lwpid]) 257 ->GetRegisterContext() 258 ->GetWatchpointHitIndex(wp_index, 259 (uintptr_t)info.psi_siginfo.si_addr); 260 if (error.Fail()) 261 LLDB_LOG(log, 262 "received error while checking for watchpoint hits, pid = " 263 "{0}, LWP = {1}, error = {2}", 264 GetID(), info.psi_lwpid, error); 265 if (wp_index != LLDB_INVALID_INDEX32) { 266 for (const auto &thread_sp : m_threads) { 267 static_pointer_cast<NativeThreadNetBSD>(thread_sp) 268 ->SetStoppedByWatchpoint(wp_index); 269 } 270 SetState(StateType::eStateStopped, true); 271 break; 272 } 273 274 // If a breakpoint was hit, report it 275 uint32_t bp_index; 276 error = static_pointer_cast<NativeThreadNetBSD>(m_threads[info.psi_lwpid]) 277 ->GetRegisterContext() 278 ->GetHardwareBreakHitIndex(bp_index, 279 (uintptr_t)info.psi_siginfo.si_addr); 280 if (error.Fail()) 281 LLDB_LOG(log, 282 "received error while checking for hardware " 283 "breakpoint hits, pid = {0}, LWP = {1}, error = {2}", 284 GetID(), info.psi_lwpid, error); 285 if (bp_index != LLDB_INVALID_INDEX32) { 286 for (const auto &thread_sp : m_threads) { 287 static_pointer_cast<NativeThreadNetBSD>(thread_sp) 288 ->SetStoppedByBreakpoint(); 289 } 290 SetState(StateType::eStateStopped, true); 291 break; 292 } 293 } break; 294 } 295 } 296 297 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) { 298 ptrace_siginfo_t info; 299 const auto siginfo_err = 300 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 301 302 for (const auto &thread_sp : m_threads) { 303 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal( 304 info.psi_siginfo.si_signo, &info.psi_siginfo); 305 } 306 SetState(StateType::eStateStopped, true); 307 } 308 309 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 310 int data, int *result) { 311 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 312 Status error; 313 int ret; 314 315 errno = 0; 316 ret = ptrace(req, static_cast<::pid_t>(pid), addr, data); 317 318 if (ret == -1) 319 error.SetErrorToErrno(); 320 321 if (result) 322 *result = ret; 323 324 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret); 325 326 if (error.Fail()) 327 LLDB_LOG(log, "ptrace() failed: {0}", error); 328 329 return error; 330 } 331 332 Status NativeProcessNetBSD::GetSoftwareBreakpointPCOffset( 333 uint32_t &actual_opcode_size) { 334 // FIXME put this behind a breakpoint protocol class that can be 335 // set per architecture. Need ARM, MIPS support here. 336 static const uint8_t g_i386_opcode[] = {0xCC}; 337 switch (m_arch.GetMachine()) { 338 case llvm::Triple::x86_64: 339 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode)); 340 return Status(); 341 default: 342 assert(false && "CPU type not supported!"); 343 return Status("CPU type not supported"); 344 } 345 } 346 347 Status 348 NativeProcessNetBSD::FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread) { 349 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS)); 350 Status error; 351 // Find out the size of a breakpoint (might depend on where we are in the 352 // code). 353 NativeRegisterContextSP context_sp = thread.GetRegisterContext(); 354 if (!context_sp) { 355 error.SetErrorString("cannot get a NativeRegisterContext for the thread"); 356 LLDB_LOG(log, "failed: {0}", error); 357 return error; 358 } 359 uint32_t breakpoint_size = 0; 360 error = GetSoftwareBreakpointPCOffset(breakpoint_size); 361 if (error.Fail()) { 362 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error); 363 return error; 364 } else 365 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size); 366 // First try probing for a breakpoint at a software breakpoint location: PC 367 // - breakpoint size. 368 const lldb::addr_t initial_pc_addr = 369 context_sp->GetPCfromBreakpointLocation(); 370 lldb::addr_t breakpoint_addr = initial_pc_addr; 371 if (breakpoint_size > 0) { 372 // Do not allow breakpoint probe to wrap around. 373 if (breakpoint_addr >= breakpoint_size) 374 breakpoint_addr -= breakpoint_size; 375 } 376 // Check if we stopped because of a breakpoint. 377 NativeBreakpointSP breakpoint_sp; 378 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp); 379 if (!error.Success() || !breakpoint_sp) { 380 // We didn't find one at a software probe location. Nothing to do. 381 LLDB_LOG(log, 382 "pid {0} no lldb breakpoint found at current pc with " 383 "adjustment: {1}", 384 GetID(), breakpoint_addr); 385 return Status(); 386 } 387 // If the breakpoint is not a software breakpoint, nothing to do. 388 if (!breakpoint_sp->IsSoftwareBreakpoint()) { 389 LLDB_LOG( 390 log, 391 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust", 392 GetID(), breakpoint_addr); 393 return Status(); 394 } 395 // 396 // We have a software breakpoint and need to adjust the PC. 397 // 398 // Sanity check. 399 if (breakpoint_size == 0) { 400 // Nothing to do! How did we get here? 401 LLDB_LOG(log, 402 "pid {0} breakpoint found at {1:x}, it is software, but the " 403 "size is zero, nothing to do (unexpected)", 404 GetID(), breakpoint_addr); 405 return Status(); 406 } 407 // 408 // We have a software breakpoint and need to adjust the PC. 409 // 410 // Sanity check. 411 if (breakpoint_size == 0) { 412 // Nothing to do! How did we get here? 413 LLDB_LOG(log, 414 "pid {0} breakpoint found at {1:x}, it is software, but the " 415 "size is zero, nothing to do (unexpected)", 416 GetID(), breakpoint_addr); 417 return Status(); 418 } 419 // Change the program counter. 420 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(), 421 thread.GetID(), initial_pc_addr, breakpoint_addr); 422 error = context_sp->SetPC(breakpoint_addr); 423 if (error.Fail()) { 424 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(), 425 thread.GetID(), error); 426 return error; 427 } 428 return error; 429 } 430 431 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { 432 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 433 LLDB_LOG(log, "pid {0}", GetID()); 434 435 const auto &thread_sp = m_threads[0]; 436 const ResumeAction *const action = 437 resume_actions.GetActionForThread(thread_sp->GetID(), true); 438 439 if (action == nullptr) { 440 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 441 thread_sp->GetID()); 442 return Status(); 443 } 444 445 Status error; 446 447 switch (action->state) { 448 case eStateRunning: { 449 // Run the thread, possibly feeding it the signal. 450 error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1, 451 action->signal); 452 if (!error.Success()) 453 return error; 454 for (const auto &thread_sp : m_threads) { 455 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetRunning(); 456 } 457 SetState(eStateRunning, true); 458 break; 459 } 460 case eStateStepping: 461 // Run the thread, possibly feeding it the signal. 462 error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1, 463 action->signal); 464 if (!error.Success()) 465 return error; 466 for (const auto &thread_sp : m_threads) { 467 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStepping(); 468 } 469 SetState(eStateStepping, true); 470 break; 471 472 case eStateSuspended: 473 case eStateStopped: 474 llvm_unreachable("Unexpected state"); 475 476 default: 477 return Status("NativeProcessNetBSD::%s (): unexpected state %s specified " 478 "for pid %" PRIu64 ", tid %" PRIu64, 479 __FUNCTION__, StateAsCString(action->state), GetID(), 480 thread_sp->GetID()); 481 } 482 483 return Status(); 484 } 485 486 Status NativeProcessNetBSD::Halt() { 487 Status error; 488 489 if (kill(GetID(), SIGSTOP) != 0) 490 error.SetErrorToErrno(); 491 492 return error; 493 } 494 495 Status NativeProcessNetBSD::Detach() { 496 Status error; 497 498 // Stop monitoring the inferior. 499 m_sigchld_handle.reset(); 500 501 // Tell ptrace to detach from the process. 502 if (GetID() == LLDB_INVALID_PROCESS_ID) 503 return error; 504 505 return PtraceWrapper(PT_DETACH, GetID()); 506 } 507 508 Status NativeProcessNetBSD::Signal(int signo) { 509 Status error; 510 511 if (kill(GetID(), signo)) 512 error.SetErrorToErrno(); 513 514 return error; 515 } 516 517 Status NativeProcessNetBSD::Kill() { 518 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 519 LLDB_LOG(log, "pid {0}", GetID()); 520 521 Status error; 522 523 switch (m_state) { 524 case StateType::eStateInvalid: 525 case StateType::eStateExited: 526 case StateType::eStateCrashed: 527 case StateType::eStateDetached: 528 case StateType::eStateUnloaded: 529 // Nothing to do - the process is already dead. 530 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(), 531 StateAsCString(m_state)); 532 return error; 533 534 case StateType::eStateConnected: 535 case StateType::eStateAttaching: 536 case StateType::eStateLaunching: 537 case StateType::eStateStopped: 538 case StateType::eStateRunning: 539 case StateType::eStateStepping: 540 case StateType::eStateSuspended: 541 // We can try to kill a process in these states. 542 break; 543 } 544 545 if (kill(GetID(), SIGKILL) != 0) { 546 error.SetErrorToErrno(); 547 return error; 548 } 549 550 return error; 551 } 552 553 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr, 554 MemoryRegionInfo &range_info) { 555 556 if (m_supports_mem_region == LazyBool::eLazyBoolNo) { 557 // We're done. 558 return Status("unsupported"); 559 } 560 561 Status error = PopulateMemoryRegionCache(); 562 if (error.Fail()) { 563 return error; 564 } 565 566 lldb::addr_t prev_base_address = 0; 567 // FIXME start by finding the last region that is <= target address using 568 // binary search. Data is sorted. 569 // There can be a ton of regions on pthreads apps with lots of threads. 570 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end(); 571 ++it) { 572 MemoryRegionInfo &proc_entry_info = it->first; 573 // Sanity check assumption that memory map entries are ascending. 574 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) && 575 "descending memory map entries detected, unexpected"); 576 prev_base_address = proc_entry_info.GetRange().GetRangeBase(); 577 UNUSED_IF_ASSERT_DISABLED(prev_base_address); 578 // If the target address comes before this entry, indicate distance to 579 // next region. 580 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) { 581 range_info.GetRange().SetRangeBase(load_addr); 582 range_info.GetRange().SetByteSize( 583 proc_entry_info.GetRange().GetRangeBase() - load_addr); 584 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 585 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 586 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 587 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 588 return error; 589 } else if (proc_entry_info.GetRange().Contains(load_addr)) { 590 // The target address is within the memory region we're processing here. 591 range_info = proc_entry_info; 592 return error; 593 } 594 // The target memory address comes somewhere after the region we just 595 // parsed. 596 } 597 // If we made it here, we didn't find an entry that contained the given 598 // address. Return the 599 // load_addr as start and the amount of bytes betwwen load address and the 600 // end of the memory as size. 601 range_info.GetRange().SetRangeBase(load_addr); 602 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 603 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 604 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 605 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 606 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 607 return error; 608 } 609 610 Status NativeProcessNetBSD::PopulateMemoryRegionCache() { 611 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 612 // If our cache is empty, pull the latest. There should always be at least 613 // one memory region if memory region handling is supported. 614 if (!m_mem_region_cache.empty()) { 615 LLDB_LOG(log, "reusing {0} cached memory region entries", 616 m_mem_region_cache.size()); 617 return Status(); 618 } 619 620 struct kinfo_vmentry *vm; 621 size_t count, i; 622 vm = kinfo_getvmmap(GetID(), &count); 623 if (vm == NULL) { 624 m_supports_mem_region = LazyBool::eLazyBoolNo; 625 Status error; 626 error.SetErrorString("not supported"); 627 return error; 628 } 629 for (i = 0; i < count; i++) { 630 MemoryRegionInfo info; 631 info.Clear(); 632 info.GetRange().SetRangeBase(vm[i].kve_start); 633 info.GetRange().SetRangeEnd(vm[i].kve_end); 634 info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 635 636 if (vm[i].kve_protection & VM_PROT_READ) 637 info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 638 else 639 info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 640 641 if (vm[i].kve_protection & VM_PROT_WRITE) 642 info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 643 else 644 info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 645 646 if (vm[i].kve_protection & VM_PROT_EXECUTE) 647 info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 648 else 649 info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 650 651 if (vm[i].kve_path[0]) 652 info.SetName(vm[i].kve_path); 653 654 m_mem_region_cache.emplace_back( 655 info, FileSpec(info.GetName().GetCString(), true)); 656 } 657 free(vm); 658 659 if (m_mem_region_cache.empty()) { 660 // No entries after attempting to read them. This shouldn't happen. 661 // Assume we don't support map entries. 662 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support " 663 "for memory region metadata retrieval"); 664 m_supports_mem_region = LazyBool::eLazyBoolNo; 665 Status error; 666 error.SetErrorString("not supported"); 667 return error; 668 } 669 LLDB_LOG(log, "read {0} memory region entries from process {1}", 670 m_mem_region_cache.size(), GetID()); 671 // We support memory retrieval, remember that. 672 m_supports_mem_region = LazyBool::eLazyBoolYes; 673 return Status(); 674 } 675 676 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions, 677 lldb::addr_t &addr) { 678 return Status("Unimplemented"); 679 } 680 681 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) { 682 return Status("Unimplemented"); 683 } 684 685 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() { 686 // punt on this for now 687 return LLDB_INVALID_ADDRESS; 688 } 689 690 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); } 691 692 bool NativeProcessNetBSD::GetArchitecture(ArchSpec &arch) const { 693 arch = m_arch; 694 return true; 695 } 696 697 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, 698 bool hardware) { 699 if (hardware) 700 return Status("NativeProcessNetBSD does not support hardware breakpoints"); 701 else 702 return SetSoftwareBreakpoint(addr, size); 703 } 704 705 Status NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode( 706 size_t trap_opcode_size_hint, size_t &actual_opcode_size, 707 const uint8_t *&trap_opcode_bytes) { 708 static const uint8_t g_i386_opcode[] = {0xCC}; 709 710 switch (m_arch.GetMachine()) { 711 case llvm::Triple::x86: 712 case llvm::Triple::x86_64: 713 trap_opcode_bytes = g_i386_opcode; 714 actual_opcode_size = sizeof(g_i386_opcode); 715 return Status(); 716 default: 717 assert(false && "CPU type not supported!"); 718 return Status("CPU type not supported"); 719 } 720 } 721 722 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path, 723 FileSpec &file_spec) { 724 return Status("Unimplemented"); 725 } 726 727 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name, 728 lldb::addr_t &load_addr) { 729 load_addr = LLDB_INVALID_ADDRESS; 730 return Status(); 731 } 732 733 void NativeProcessNetBSD::SigchldHandler() { 734 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 735 // Process all pending waitpid notifications. 736 int status; 737 ::pid_t wait_pid = 738 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG); 739 740 if (wait_pid == 0) 741 return; // We are done. 742 743 if (wait_pid == -1) { 744 Status error(errno, eErrorTypePOSIX); 745 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error); 746 } 747 748 WaitStatus wait_status = WaitStatus::Decode(status); 749 bool exited = wait_status.type == WaitStatus::Exit || 750 (wait_status.type == WaitStatus::Signal && 751 wait_pid == static_cast<::pid_t>(GetID())); 752 753 LLDB_LOG(log, 754 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}", 755 GetID(), wait_pid, status, exited); 756 757 if (exited) 758 MonitorExited(wait_pid, wait_status); 759 else { 760 assert(wait_status.type == WaitStatus::Stop); 761 MonitorCallback(wait_pid, wait_status.status); 762 } 763 } 764 765 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) { 766 for (auto thread_sp : m_threads) { 767 assert(thread_sp && "thread list should not contain NULL threads"); 768 if (thread_sp->GetID() == thread_id) { 769 // We have this thread. 770 return true; 771 } 772 } 773 774 // We don't have this thread. 775 return false; 776 } 777 778 NativeThreadNetBSDSP NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) { 779 780 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 781 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 782 783 assert(!HasThreadNoLock(thread_id) && 784 "attempted to add a thread by id that already exists"); 785 786 // If this is the first thread, save it as the current thread 787 if (m_threads.empty()) 788 SetCurrentThreadID(thread_id); 789 790 auto thread_sp = std::make_shared<NativeThreadNetBSD>(this, thread_id); 791 m_threads.push_back(thread_sp); 792 return thread_sp; 793 } 794 795 Status NativeProcessNetBSD::Attach() { 796 // Attach to the requested process. 797 // An attach will cause the thread to stop with a SIGSTOP. 798 Status status = PtraceWrapper(PT_ATTACH, m_pid); 799 if (status.Fail()) 800 return status; 801 802 int wstatus; 803 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD 804 // At this point we should have a thread stopped if waitpid succeeds. 805 if ((wstatus = waitpid(m_pid, NULL, WALLSIG)) < 0) 806 return Status(errno, eErrorTypePOSIX); 807 808 /* Initialize threads */ 809 status = ReinitializeThreads(); 810 if (status.Fail()) 811 return status; 812 813 for (const auto &thread_sp : m_threads) { 814 static_pointer_cast<NativeThreadNetBSD>(thread_sp)->SetStoppedBySignal( 815 SIGSTOP); 816 } 817 818 // Let our process instance know the thread has stopped. 819 SetState(StateType::eStateStopped); 820 return Status(); 821 } 822 823 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, 824 size_t size, size_t &bytes_read) { 825 unsigned char *dst = static_cast<unsigned char *>(buf); 826 struct ptrace_io_desc io; 827 828 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 829 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 830 831 bytes_read = 0; 832 io.piod_op = PIOD_READ_D; 833 io.piod_len = size; 834 835 do { 836 io.piod_offs = (void *)(addr + bytes_read); 837 io.piod_addr = dst + bytes_read; 838 839 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 840 if (error.Fail()) 841 return error; 842 843 bytes_read = io.piod_len; 844 io.piod_len = size - bytes_read; 845 } while (bytes_read < size); 846 847 return Status(); 848 } 849 850 Status NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf, 851 size_t size, 852 size_t &bytes_read) { 853 Status error = ReadMemory(addr, buf, size, bytes_read); 854 if (error.Fail()) 855 return error; 856 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size); 857 } 858 859 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, 860 size_t size, size_t &bytes_written) { 861 const unsigned char *src = static_cast<const unsigned char *>(buf); 862 Status error; 863 struct ptrace_io_desc io; 864 865 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 866 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 867 868 bytes_written = 0; 869 io.piod_op = PIOD_WRITE_D; 870 io.piod_len = size; 871 872 do { 873 io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written)); 874 io.piod_offs = (void *)(addr + bytes_written); 875 876 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 877 if (error.Fail()) 878 return error; 879 880 bytes_written = io.piod_len; 881 io.piod_len = size - bytes_written; 882 } while (bytes_written < size); 883 884 return error; 885 } 886 887 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 888 NativeProcessNetBSD::GetAuxvData() const { 889 /* 890 * ELF_AUX_ENTRIES is currently restricted to kernel 891 * (<sys/exec_elf.h> r. 1.155 specifies 15) 892 * 893 * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this 894 * information isn't needed. 895 */ 896 size_t auxv_size = 100 * sizeof(AuxInfo); 897 898 ErrorOr<std::unique_ptr<MemoryBuffer>> buf = 899 llvm::MemoryBuffer::getNewMemBuffer(auxv_size); 900 901 struct ptrace_io_desc io; 902 io.piod_op = PIOD_READ_AUXV; 903 io.piod_offs = 0; 904 io.piod_addr = const_cast<void *>(static_cast<const void *>(buf.get()->getBufferStart())); 905 io.piod_len = auxv_size; 906 907 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 908 909 if (error.Fail()) 910 return std::error_code(error.GetError(), std::generic_category()); 911 912 if (io.piod_len < 1) 913 return std::error_code(ECANCELED, std::generic_category()); 914 915 return buf; 916 } 917 918 Status NativeProcessNetBSD::ReinitializeThreads() { 919 // Clear old threads 920 m_threads.clear(); 921 922 // Initialize new thread 923 struct ptrace_lwpinfo info = {}; 924 Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 925 if (error.Fail()) { 926 return error; 927 } 928 // Reinitialize from scratch threads and register them in process 929 while (info.pl_lwpid != 0) { 930 NativeThreadNetBSDSP thread_sp = AddThread(info.pl_lwpid); 931 error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 932 if (error.Fail()) { 933 return error; 934 } 935 } 936 937 return error; 938 } 939