1 //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===// 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 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().ReleaseMasterFileDescriptor(), native_delegate, 99 Info.GetArchitecture(), mainloop)); 100 101 // Enable event reporting 102 ptrace_event_t events; 103 status = PtraceWrapper(PT_GET_EVENT_MASK, pid, &events, sizeof(events)); 104 if (status.Fail()) 105 return status.ToError(); 106 // TODO: PTRACE_FORK | PTRACE_VFORK | PTRACE_POSIX_SPAWN? 107 events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT; 108 status = PtraceWrapper(PT_SET_EVENT_MASK, pid, &events, sizeof(events)); 109 if (status.Fail()) 110 return status.ToError(); 111 112 status = process_up->ReinitializeThreads(); 113 if (status.Fail()) 114 return status.ToError(); 115 116 for (const auto &thread : process_up->m_threads) 117 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 118 process_up->SetState(StateType::eStateStopped, false); 119 120 return std::move(process_up); 121 } 122 123 llvm::Expected<std::unique_ptr<NativeProcessProtocol>> 124 NativeProcessNetBSD::Factory::Attach( 125 lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &native_delegate, 126 MainLoop &mainloop) const { 127 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 128 LLDB_LOG(log, "pid = {0:x}", pid); 129 130 // Retrieve the architecture for the running process. 131 ProcessInstanceInfo Info; 132 if (!Host::GetProcessInfo(pid, Info)) { 133 return llvm::make_error<StringError>("Cannot get process architecture", 134 llvm::inconvertibleErrorCode()); 135 } 136 137 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD( 138 pid, -1, native_delegate, Info.GetArchitecture(), mainloop)); 139 140 Status status = process_up->Attach(); 141 if (!status.Success()) 142 return status.ToError(); 143 144 return std::move(process_up); 145 } 146 147 // Public Instance Methods 148 149 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd, 150 NativeDelegate &delegate, 151 const ArchSpec &arch, 152 MainLoop &mainloop) 153 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch) { 154 if (m_terminal_fd != -1) { 155 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK); 156 assert(status.Success()); 157 } 158 159 Status status; 160 m_sigchld_handle = mainloop.RegisterSignal( 161 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status); 162 assert(m_sigchld_handle && status.Success()); 163 } 164 165 // Handles all waitpid events from the inferior process. 166 void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) { 167 switch (signal) { 168 case SIGTRAP: 169 return MonitorSIGTRAP(pid); 170 case SIGSTOP: 171 return MonitorSIGSTOP(pid); 172 default: 173 return MonitorSignal(pid, signal); 174 } 175 } 176 177 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) { 178 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 179 180 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid); 181 182 /* Stop Tracking All Threads attached to Process */ 183 m_threads.clear(); 184 185 SetExitStatus(status, true); 186 187 // Notify delegate that our process has exited. 188 SetState(StateType::eStateExited, true); 189 } 190 191 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) { 192 ptrace_siginfo_t info; 193 194 const auto siginfo_err = 195 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 196 197 // Get details on the signal raised. 198 if (siginfo_err.Success()) { 199 // Handle SIGSTOP from LLGS (LLDB GDB Server) 200 if (info.psi_siginfo.si_code == SI_USER && 201 info.psi_siginfo.si_pid == ::getpid()) { 202 /* Stop Tracking all Threads attached to Process */ 203 for (const auto &thread : m_threads) { 204 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal( 205 SIGSTOP, &info.psi_siginfo); 206 } 207 } 208 SetState(StateType::eStateStopped, true); 209 } 210 } 211 212 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) { 213 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 214 ptrace_siginfo_t info; 215 216 const auto siginfo_err = 217 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 218 219 // Get details on the signal raised. 220 if (siginfo_err.Fail()) { 221 return; 222 } 223 224 NativeThreadNetBSD* thread = nullptr; 225 if (info.psi_lwpid > 0) { 226 for (const auto &t : m_threads) { 227 if (t->GetID() == static_cast<lldb::tid_t>(info.psi_lwpid)) { 228 thread = static_cast<NativeThreadNetBSD *>(t.get()); 229 break; 230 } 231 static_cast<NativeThreadNetBSD *>(t.get())->SetStoppedWithNoReason(); 232 } 233 if (!thread) 234 LLDB_LOG(log, 235 "thread not found in m_threads, pid = {0}, LWP = {1}", pid, 236 info.psi_lwpid); 237 } 238 239 switch (info.psi_siginfo.si_code) { 240 case TRAP_BRKPT: 241 if (thread) { 242 thread->SetStoppedByBreakpoint(); 243 FixupBreakpointPCAsNeeded(*thread); 244 } 245 SetState(StateType::eStateStopped, true); 246 break; 247 case TRAP_TRACE: 248 if (thread) 249 thread->SetStoppedByTrace(); 250 SetState(StateType::eStateStopped, true); 251 break; 252 case TRAP_EXEC: { 253 Status error = ReinitializeThreads(); 254 if (error.Fail()) { 255 SetState(StateType::eStateInvalid); 256 return; 257 } 258 259 // Let our delegate know we have just exec'd. 260 NotifyDidExec(); 261 262 for (const auto &thread : m_threads) 263 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec(); 264 SetState(StateType::eStateStopped, true); 265 } break; 266 case TRAP_LWP: { 267 ptrace_state_t pst; 268 Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst)); 269 if (error.Fail()) { 270 SetState(StateType::eStateInvalid); 271 return; 272 } 273 274 switch (pst.pe_report_event) { 275 case PTRACE_LWP_CREATE: 276 LLDB_LOG(log, 277 "monitoring new thread, pid = {0}, LWP = {1}", pid, 278 pst.pe_lwp); 279 AddThread(pst.pe_lwp); 280 break; 281 case PTRACE_LWP_EXIT: 282 LLDB_LOG(log, 283 "removing exited thread, pid = {0}, LWP = {1}", pid, 284 pst.pe_lwp); 285 RemoveThread(pst.pe_lwp); 286 break; 287 } 288 289 error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void*>(1), 0); 290 if (error.Fail()) { 291 SetState(StateType::eStateInvalid); 292 return; 293 } 294 } break; 295 case TRAP_DBREG: { 296 if (!thread) 297 break; 298 299 uint32_t wp_index = LLDB_INVALID_INDEX32; 300 Status error = thread->GetRegisterContext().GetWatchpointHitIndex( 301 wp_index, (uintptr_t)info.psi_siginfo.si_addr); 302 if (error.Fail()) 303 LLDB_LOG(log, 304 "received error while checking for watchpoint hits, pid = " 305 "{0}, LWP = {1}, error = {2}", pid, info.psi_lwpid, error); 306 if (wp_index != LLDB_INVALID_INDEX32) { 307 thread->SetStoppedByWatchpoint(wp_index); 308 SetState(StateType::eStateStopped, true); 309 break; 310 } 311 312 thread->SetStoppedByTrace(); 313 SetState(StateType::eStateStopped, true); 314 } break; 315 } 316 } 317 318 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) { 319 ptrace_siginfo_t info; 320 const auto siginfo_err = 321 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info)); 322 323 for (const auto &abs_thread : m_threads) { 324 NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread); 325 assert(info.psi_lwpid >= 0); 326 if (info.psi_lwpid == 0 || 327 static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID()) 328 thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo); 329 else 330 thread.SetStoppedWithNoReason(); 331 } 332 SetState(StateType::eStateStopped, true); 333 } 334 335 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr, 336 int data, int *result) { 337 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE)); 338 Status error; 339 int ret; 340 341 errno = 0; 342 ret = ptrace(req, static_cast<::pid_t>(pid), addr, data); 343 344 if (ret == -1) 345 error.SetErrorToErrno(); 346 347 if (result) 348 *result = ret; 349 350 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret); 351 352 if (error.Fail()) 353 LLDB_LOG(log, "ptrace() failed: {0}", error); 354 355 return error; 356 } 357 358 static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo( 359 const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads, 360 const ResumeActionList &resume_actions) { 361 // We need to account for three possible scenarios: 362 // 1. no signal being sent. 363 // 2. a signal being sent to one thread. 364 // 3. a signal being sent to the whole process. 365 366 // Count signaled threads. While at it, determine which signal is being sent 367 // and ensure there's only one. 368 size_t signaled_threads = 0; 369 int signal = LLDB_INVALID_SIGNAL_NUMBER; 370 lldb::tid_t signaled_lwp; 371 for (const auto &thread : threads) { 372 assert(thread && "thread list should not contain NULL threads"); 373 const ResumeAction *action = 374 resume_actions.GetActionForThread(thread->GetID(), true); 375 if (action) { 376 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) { 377 signaled_threads++; 378 if (action->signal != signal) { 379 if (signal != LLDB_INVALID_SIGNAL_NUMBER) 380 return Status("NetBSD does not support passing multiple signals " 381 "simultaneously") 382 .ToError(); 383 signal = action->signal; 384 signaled_lwp = thread->GetID(); 385 } 386 } 387 } 388 } 389 390 if (signaled_threads == 0) { 391 ptrace_siginfo_t siginfo; 392 siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER; 393 return siginfo; 394 } 395 396 if (signaled_threads > 1 && signaled_threads < threads.size()) 397 return Status("NetBSD does not support passing signal to 1<i<all threads") 398 .ToError(); 399 400 ptrace_siginfo_t siginfo; 401 siginfo.psi_siginfo.si_signo = signal; 402 siginfo.psi_siginfo.si_code = SI_USER; 403 siginfo.psi_siginfo.si_pid = getpid(); 404 siginfo.psi_siginfo.si_uid = getuid(); 405 if (signaled_threads == 1) 406 siginfo.psi_lwpid = signaled_lwp; 407 else // signal for the whole process 408 siginfo.psi_lwpid = 0; 409 return siginfo; 410 } 411 412 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) { 413 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 414 LLDB_LOG(log, "pid {0}", GetID()); 415 416 Status ret; 417 418 Expected<ptrace_siginfo_t> siginfo = 419 ComputeSignalInfo(m_threads, resume_actions); 420 if (!siginfo) 421 return Status(siginfo.takeError()); 422 423 for (const auto &abs_thread : m_threads) { 424 assert(abs_thread && "thread list should not contain NULL threads"); 425 NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread); 426 427 const ResumeAction *action = 428 resume_actions.GetActionForThread(thread.GetID(), true); 429 // we need to explicit issue suspend requests, so it is simpler to map it 430 // into proper action 431 ResumeAction suspend_action{thread.GetID(), eStateSuspended, 432 LLDB_INVALID_SIGNAL_NUMBER}; 433 434 if (action == nullptr) { 435 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(), 436 thread.GetID()); 437 action = &suspend_action; 438 } 439 440 LLDB_LOG( 441 log, 442 "processing resume action state {0} signal {1} for pid {2} tid {3}", 443 action->state, action->signal, GetID(), thread.GetID()); 444 445 switch (action->state) { 446 case eStateRunning: 447 ret = thread.Resume(); 448 break; 449 case eStateStepping: 450 ret = thread.SingleStep(); 451 break; 452 case eStateSuspended: 453 case eStateStopped: 454 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) 455 return Status("Passing signal to suspended thread unsupported"); 456 457 ret = thread.Suspend(); 458 break; 459 460 default: 461 return Status("NativeProcessNetBSD::%s (): unexpected state %s specified " 462 "for pid %" PRIu64 ", tid %" PRIu64, 463 __FUNCTION__, StateAsCString(action->state), GetID(), 464 thread.GetID()); 465 } 466 467 if (!ret.Success()) 468 return ret; 469 } 470 471 int signal = 0; 472 if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) { 473 ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(), 474 sizeof(*siginfo)); 475 if (!ret.Success()) 476 return ret; 477 signal = siginfo->psi_siginfo.si_signo; 478 } 479 480 ret = PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 481 signal); 482 if (ret.Success()) 483 SetState(eStateRunning, true); 484 return ret; 485 } 486 487 Status NativeProcessNetBSD::Halt() { 488 return PtraceWrapper(PT_STOP, GetID()); 489 } 490 491 Status NativeProcessNetBSD::Detach() { 492 Status error; 493 494 // Stop monitoring the inferior. 495 m_sigchld_handle.reset(); 496 497 // Tell ptrace to detach from the process. 498 if (GetID() == LLDB_INVALID_PROCESS_ID) 499 return error; 500 501 return PtraceWrapper(PT_DETACH, GetID()); 502 } 503 504 Status NativeProcessNetBSD::Signal(int signo) { 505 Status error; 506 507 if (kill(GetID(), signo)) 508 error.SetErrorToErrno(); 509 510 return error; 511 } 512 513 Status NativeProcessNetBSD::Interrupt() { 514 return PtraceWrapper(PT_STOP, GetID()); 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 next 579 // 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 load_addr as start and the amount of bytes betwwen 599 // load address and the end of the memory as size. 600 range_info.GetRange().SetRangeBase(load_addr); 601 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 602 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 603 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 604 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 605 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo); 606 return error; 607 } 608 609 Status NativeProcessNetBSD::PopulateMemoryRegionCache() { 610 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 611 // If our cache is empty, pull the latest. There should always be at least 612 // one memory region if memory region handling is supported. 613 if (!m_mem_region_cache.empty()) { 614 LLDB_LOG(log, "reusing {0} cached memory region entries", 615 m_mem_region_cache.size()); 616 return Status(); 617 } 618 619 struct kinfo_vmentry *vm; 620 size_t count, i; 621 vm = kinfo_getvmmap(GetID(), &count); 622 if (vm == NULL) { 623 m_supports_mem_region = LazyBool::eLazyBoolNo; 624 Status error; 625 error.SetErrorString("not supported"); 626 return error; 627 } 628 for (i = 0; i < count; i++) { 629 MemoryRegionInfo info; 630 info.Clear(); 631 info.GetRange().SetRangeBase(vm[i].kve_start); 632 info.GetRange().SetRangeEnd(vm[i].kve_end); 633 info.SetMapped(MemoryRegionInfo::OptionalBool::eYes); 634 635 if (vm[i].kve_protection & VM_PROT_READ) 636 info.SetReadable(MemoryRegionInfo::OptionalBool::eYes); 637 else 638 info.SetReadable(MemoryRegionInfo::OptionalBool::eNo); 639 640 if (vm[i].kve_protection & VM_PROT_WRITE) 641 info.SetWritable(MemoryRegionInfo::OptionalBool::eYes); 642 else 643 info.SetWritable(MemoryRegionInfo::OptionalBool::eNo); 644 645 if (vm[i].kve_protection & VM_PROT_EXECUTE) 646 info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes); 647 else 648 info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo); 649 650 if (vm[i].kve_path[0]) 651 info.SetName(vm[i].kve_path); 652 653 m_mem_region_cache.emplace_back( 654 info, FileSpec(info.GetName().GetCString())); 655 } 656 free(vm); 657 658 if (m_mem_region_cache.empty()) { 659 // No entries after attempting to read them. This shouldn't happen. Assume 660 // we don't support map entries. 661 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support " 662 "for memory region metadata retrieval"); 663 m_supports_mem_region = LazyBool::eLazyBoolNo; 664 Status error; 665 error.SetErrorString("not supported"); 666 return error; 667 } 668 LLDB_LOG(log, "read {0} memory region entries from process {1}", 669 m_mem_region_cache.size(), GetID()); 670 // We support memory retrieval, remember that. 671 m_supports_mem_region = LazyBool::eLazyBoolYes; 672 return Status(); 673 } 674 675 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions, 676 lldb::addr_t &addr) { 677 return Status("Unimplemented"); 678 } 679 680 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) { 681 return Status("Unimplemented"); 682 } 683 684 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() { 685 // punt on this for now 686 return LLDB_INVALID_ADDRESS; 687 } 688 689 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); } 690 691 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size, 692 bool hardware) { 693 if (hardware) 694 return Status("NativeProcessNetBSD does not support hardware breakpoints"); 695 else 696 return SetSoftwareBreakpoint(addr, size); 697 } 698 699 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path, 700 FileSpec &file_spec) { 701 return Status("Unimplemented"); 702 } 703 704 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name, 705 lldb::addr_t &load_addr) { 706 load_addr = LLDB_INVALID_ADDRESS; 707 return Status(); 708 } 709 710 void NativeProcessNetBSD::SigchldHandler() { 711 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS)); 712 // Process all pending waitpid notifications. 713 int status; 714 ::pid_t wait_pid = 715 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG); 716 717 if (wait_pid == 0) 718 return; // We are done. 719 720 if (wait_pid == -1) { 721 Status error(errno, eErrorTypePOSIX); 722 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error); 723 } 724 725 WaitStatus wait_status = WaitStatus::Decode(status); 726 bool exited = wait_status.type == WaitStatus::Exit || 727 (wait_status.type == WaitStatus::Signal && 728 wait_pid == static_cast<::pid_t>(GetID())); 729 730 LLDB_LOG(log, 731 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}", 732 GetID(), wait_pid, status, exited); 733 734 if (exited) 735 MonitorExited(wait_pid, wait_status); 736 else { 737 assert(wait_status.type == WaitStatus::Stop); 738 MonitorCallback(wait_pid, wait_status.status); 739 } 740 } 741 742 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) { 743 for (const auto &thread : m_threads) { 744 assert(thread && "thread list should not contain NULL threads"); 745 if (thread->GetID() == thread_id) { 746 // We have this thread. 747 return true; 748 } 749 } 750 751 // We don't have this thread. 752 return false; 753 } 754 755 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) { 756 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 757 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id); 758 759 assert(thread_id > 0); 760 assert(!HasThreadNoLock(thread_id) && 761 "attempted to add a thread by id that already exists"); 762 763 // If this is the first thread, save it as the current thread 764 if (m_threads.empty()) 765 SetCurrentThreadID(thread_id); 766 767 m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id)); 768 return static_cast<NativeThreadNetBSD &>(*m_threads.back()); 769 } 770 771 void NativeProcessNetBSD::RemoveThread(lldb::tid_t thread_id) { 772 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD)); 773 LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id); 774 775 assert(thread_id > 0); 776 assert(HasThreadNoLock(thread_id) && 777 "attempted to remove a thread that does not exist"); 778 779 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) { 780 if ((*it)->GetID() == thread_id) { 781 m_threads.erase(it); 782 break; 783 } 784 } 785 } 786 787 Status NativeProcessNetBSD::Attach() { 788 // Attach to the requested process. 789 // An attach will cause the thread to stop with a SIGSTOP. 790 Status status = PtraceWrapper(PT_ATTACH, m_pid); 791 if (status.Fail()) 792 return status; 793 794 int wstatus; 795 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this 796 // point we should have a thread stopped if waitpid succeeds. 797 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, 798 m_pid, nullptr, WALLSIG)) < 0) 799 return Status(errno, eErrorTypePOSIX); 800 801 /* Initialize threads */ 802 status = ReinitializeThreads(); 803 if (status.Fail()) 804 return status; 805 806 for (const auto &thread : m_threads) 807 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP); 808 809 // Let our process instance know the thread has stopped. 810 SetState(StateType::eStateStopped); 811 return Status(); 812 } 813 814 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf, 815 size_t size, size_t &bytes_read) { 816 unsigned char *dst = static_cast<unsigned char *>(buf); 817 struct ptrace_io_desc io; 818 819 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 820 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 821 822 bytes_read = 0; 823 io.piod_op = PIOD_READ_D; 824 io.piod_len = size; 825 826 do { 827 io.piod_offs = (void *)(addr + bytes_read); 828 io.piod_addr = dst + bytes_read; 829 830 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 831 if (error.Fail() || io.piod_len == 0) 832 return error; 833 834 bytes_read += io.piod_len; 835 io.piod_len = size - bytes_read; 836 } while (bytes_read < size); 837 838 return Status(); 839 } 840 841 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf, 842 size_t size, size_t &bytes_written) { 843 const unsigned char *src = static_cast<const unsigned char *>(buf); 844 Status error; 845 struct ptrace_io_desc io; 846 847 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY)); 848 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size); 849 850 bytes_written = 0; 851 io.piod_op = PIOD_WRITE_D; 852 io.piod_len = size; 853 854 do { 855 io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written)); 856 io.piod_offs = (void *)(addr + bytes_written); 857 858 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 859 if (error.Fail() || io.piod_len == 0) 860 return error; 861 862 bytes_written += io.piod_len; 863 io.piod_len = size - bytes_written; 864 } while (bytes_written < size); 865 866 return error; 867 } 868 869 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> 870 NativeProcessNetBSD::GetAuxvData() const { 871 /* 872 * ELF_AUX_ENTRIES is currently restricted to kernel 873 * (<sys/exec_elf.h> r. 1.155 specifies 15) 874 * 875 * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this 876 * information isn't needed. 877 */ 878 size_t auxv_size = 100 * sizeof(AuxInfo); 879 880 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf = 881 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size); 882 883 struct ptrace_io_desc io; 884 io.piod_op = PIOD_READ_AUXV; 885 io.piod_offs = 0; 886 io.piod_addr = static_cast<void *>(buf.get()->getBufferStart()); 887 io.piod_len = auxv_size; 888 889 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io); 890 891 if (error.Fail()) 892 return std::error_code(error.GetError(), std::generic_category()); 893 894 if (io.piod_len < 1) 895 return std::error_code(ECANCELED, std::generic_category()); 896 897 return std::move(buf); 898 } 899 900 Status NativeProcessNetBSD::ReinitializeThreads() { 901 // Clear old threads 902 m_threads.clear(); 903 904 // Initialize new thread 905 struct ptrace_lwpinfo info = {}; 906 Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 907 if (error.Fail()) { 908 return error; 909 } 910 // Reinitialize from scratch threads and register them in process 911 while (info.pl_lwpid != 0) { 912 AddThread(info.pl_lwpid); 913 error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info)); 914 if (error.Fail()) { 915 return error; 916 } 917 } 918 919 return error; 920 } 921