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