1 //===-- NativeProcessNetBSD.cpp ------------------------------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "NativeProcessNetBSD.h"
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"
26 // System includes - They have to be included after framework includes because
27 // they define some macros which collide with variable names in other modules
29 #include <sys/types.h>
30 #include <sys/ptrace.h>
31 #include <sys/sysctl.h>
33 #include <uvm/uvm_prot.h>
39 using namespace lldb_private;
40 using namespace lldb_private::process_netbsd;
43 // Simple helper function to ensure flags are enabled on the given file
45 static Status EnsureFDFlags(int fd, int flags) {
48 int status = fcntl(fd, F_GETFL);
50 error.SetErrorToErrno();
54 if (fcntl(fd, F_SETFL, status | flags) == -1) {
55 error.SetErrorToErrno();
62 // -----------------------------------------------------------------------------
63 // Public Static Methods
64 // -----------------------------------------------------------------------------
66 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
67 NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
68 NativeDelegate &native_delegate,
69 MainLoop &mainloop) const {
70 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
73 ::pid_t pid = ProcessLauncherPosixFork()
74 .LaunchProcess(launch_info, status)
76 LLDB_LOG(log, "pid = {0:x}", pid);
78 LLDB_LOG(log, "failed to launch process: {0}", status);
79 return status.ToError();
82 // Wait for the child process to trap on its call to execve.
84 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
87 if (!WIFSTOPPED(wstatus)) {
88 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
89 WaitStatus::Decode(wstatus));
90 return llvm::make_error<StringError>("Could not sync with inferior process",
91 llvm::inconvertibleErrorCode());
93 LLDB_LOG(log, "inferior started, now in stopped state");
95 ProcessInstanceInfo Info;
96 if (!Host::GetProcessInfo(pid, Info)) {
97 return llvm::make_error<StringError>("Cannot get process architecture",
98 llvm::inconvertibleErrorCode());
101 // Set the architecture to the exe architecture.
102 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
103 Info.GetArchitecture().GetArchitectureName());
105 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
106 pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
107 Info.GetArchitecture(), mainloop));
109 status = process_up->ReinitializeThreads();
111 return status.ToError();
113 for (const auto &thread : process_up->m_threads)
114 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
115 process_up->SetState(StateType::eStateStopped, false);
117 return std::move(process_up);
120 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
121 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);
127 // Retrieve the architecture for the running process.
128 ProcessInstanceInfo Info;
129 if (!Host::GetProcessInfo(pid, Info)) {
130 return llvm::make_error<StringError>("Cannot get process architecture",
131 llvm::inconvertibleErrorCode());
134 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
135 pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
137 Status status = process_up->Attach();
138 if (!status.Success())
139 return status.ToError();
141 return std::move(process_up);
144 // -----------------------------------------------------------------------------
145 // Public Instance Methods
146 // -----------------------------------------------------------------------------
148 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
149 NativeDelegate &delegate,
150 const ArchSpec &arch,
152 : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
153 if (m_terminal_fd != -1) {
154 Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
155 assert(status.Success());
159 m_sigchld_handle = mainloop.RegisterSignal(
160 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
161 assert(m_sigchld_handle && status.Success());
164 // Handles all waitpid events from the inferior process.
165 void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
168 return MonitorSIGTRAP(pid);
170 return MonitorSIGSTOP(pid);
172 return MonitorSignal(pid, signal);
176 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
177 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
179 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
181 /* Stop Tracking All Threads attached to Process */
184 SetExitStatus(status, true);
186 // Notify delegate that our process has exited.
187 SetState(StateType::eStateExited, true);
190 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
191 ptrace_siginfo_t info;
193 const auto siginfo_err =
194 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
196 // Get details on the signal raised.
197 if (siginfo_err.Success()) {
198 // Handle SIGSTOP from LLGS (LLDB GDB Server)
199 if (info.psi_siginfo.si_code == SI_USER &&
200 info.psi_siginfo.si_pid == ::getpid()) {
201 /* Stop Tracking all Threads attached to Process */
202 for (const auto &thread : m_threads) {
203 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
204 SIGSTOP, &info.psi_siginfo);
210 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
211 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
212 ptrace_siginfo_t info;
214 const auto siginfo_err =
215 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
217 // Get details on the signal raised.
218 if (siginfo_err.Fail()) {
222 switch (info.psi_siginfo.si_code) {
224 for (const auto &thread : m_threads) {
225 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
226 FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
228 SetState(StateType::eStateStopped, true);
231 for (const auto &thread : m_threads)
232 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
233 SetState(StateType::eStateStopped, true);
236 Status error = ReinitializeThreads();
238 SetState(StateType::eStateInvalid);
242 // Let our delegate know we have just exec'd.
245 for (const auto &thread : m_threads)
246 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
247 SetState(StateType::eStateStopped, true);
250 // If a watchpoint was hit, report it
252 Status error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
253 .GetRegisterContext()
254 .GetWatchpointHitIndex(
255 wp_index, (uintptr_t)info.psi_siginfo.si_addr);
258 "received error while checking for watchpoint hits, pid = "
259 "{0}, LWP = {1}, error = {2}",
260 GetID(), info.psi_lwpid, error);
261 if (wp_index != LLDB_INVALID_INDEX32) {
262 for (const auto &thread : m_threads)
263 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
265 SetState(StateType::eStateStopped, true);
269 // If a breakpoint was hit, report it
271 error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
272 .GetRegisterContext()
273 .GetHardwareBreakHitIndex(bp_index,
274 (uintptr_t)info.psi_siginfo.si_addr);
277 "received error while checking for hardware "
278 "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
279 GetID(), info.psi_lwpid, error);
280 if (bp_index != LLDB_INVALID_INDEX32) {
281 for (const auto &thread : m_threads)
282 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
283 SetState(StateType::eStateStopped, true);
290 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
291 ptrace_siginfo_t info;
292 const auto siginfo_err =
293 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
295 for (const auto &thread : m_threads) {
296 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
297 info.psi_siginfo.si_signo, &info.psi_siginfo);
299 SetState(StateType::eStateStopped, true);
302 Status NativeProcessNetBSD::PtraceWrapper(int req, lldb::pid_t pid, void *addr,
303 int data, int *result) {
304 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PTRACE));
309 ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
312 error.SetErrorToErrno();
317 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
320 LLDB_LOG(log, "ptrace() failed: {0}", error);
325 Status NativeProcessNetBSD::GetSoftwareBreakpointPCOffset(
326 uint32_t &actual_opcode_size) {
327 // FIXME put this behind a breakpoint protocol class that can be
328 // set per architecture. Need ARM, MIPS support here.
329 static const uint8_t g_i386_opcode[] = {0xCC};
330 switch (m_arch.GetMachine()) {
331 case llvm::Triple::x86_64:
332 actual_opcode_size = static_cast<uint32_t>(sizeof(g_i386_opcode));
335 assert(false && "CPU type not supported!");
336 return Status("CPU type not supported");
341 NativeProcessNetBSD::FixupBreakpointPCAsNeeded(NativeThreadNetBSD &thread) {
342 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
344 // Find out the size of a breakpoint (might depend on where we are in the
346 NativeRegisterContext& context = thread.GetRegisterContext();
347 uint32_t breakpoint_size = 0;
348 error = GetSoftwareBreakpointPCOffset(breakpoint_size);
350 LLDB_LOG(log, "GetBreakpointSize() failed: {0}", error);
353 LLDB_LOG(log, "breakpoint size: {0}", breakpoint_size);
354 // First try probing for a breakpoint at a software breakpoint location: PC -
356 const lldb::addr_t initial_pc_addr =
357 context.GetPCfromBreakpointLocation();
358 lldb::addr_t breakpoint_addr = initial_pc_addr;
359 if (breakpoint_size > 0) {
360 // Do not allow breakpoint probe to wrap around.
361 if (breakpoint_addr >= breakpoint_size)
362 breakpoint_addr -= breakpoint_size;
364 // Check if we stopped because of a breakpoint.
365 NativeBreakpointSP breakpoint_sp;
366 error = m_breakpoint_list.GetBreakpoint(breakpoint_addr, breakpoint_sp);
367 if (!error.Success() || !breakpoint_sp) {
368 // We didn't find one at a software probe location. Nothing to do.
370 "pid {0} no lldb breakpoint found at current pc with "
372 GetID(), breakpoint_addr);
375 // If the breakpoint is not a software breakpoint, nothing to do.
376 if (!breakpoint_sp->IsSoftwareBreakpoint()) {
379 "pid {0} breakpoint found at {1:x}, not software, nothing to adjust",
380 GetID(), breakpoint_addr);
384 // We have a software breakpoint and need to adjust the PC.
387 if (breakpoint_size == 0) {
388 // Nothing to do! How did we get here?
390 "pid {0} breakpoint found at {1:x}, it is software, but the "
391 "size is zero, nothing to do (unexpected)",
392 GetID(), breakpoint_addr);
396 // We have a software breakpoint and need to adjust the PC.
399 if (breakpoint_size == 0) {
400 // Nothing to do! How did we get here?
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);
407 // Change the program counter.
408 LLDB_LOG(log, "pid {0} tid {1}: changing PC from {2:x} to {3:x}", GetID(),
409 thread.GetID(), initial_pc_addr, breakpoint_addr);
410 error = context.SetPC(breakpoint_addr);
412 LLDB_LOG(log, "pid {0} tid {1}: failed to set PC: {2}", GetID(),
413 thread.GetID(), error);
419 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
420 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
421 LLDB_LOG(log, "pid {0}", GetID());
423 const auto &thread = m_threads[0];
424 const ResumeAction *const action =
425 resume_actions.GetActionForThread(thread->GetID(), true);
427 if (action == nullptr) {
428 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
435 switch (action->state) {
436 case eStateRunning: {
437 // Run the thread, possibly feeding it the signal.
438 error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
440 if (!error.Success())
442 for (const auto &thread : m_threads)
443 static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
444 SetState(eStateRunning, true);
448 // Run the thread, possibly feeding it the signal.
449 error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
451 if (!error.Success())
453 for (const auto &thread : m_threads)
454 static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
455 SetState(eStateStepping, true);
458 case eStateSuspended:
460 llvm_unreachable("Unexpected state");
463 return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
464 "for pid %" PRIu64 ", tid %" PRIu64,
465 __FUNCTION__, StateAsCString(action->state), GetID(),
472 Status NativeProcessNetBSD::Halt() {
475 if (kill(GetID(), SIGSTOP) != 0)
476 error.SetErrorToErrno();
481 Status NativeProcessNetBSD::Detach() {
484 // Stop monitoring the inferior.
485 m_sigchld_handle.reset();
487 // Tell ptrace to detach from the process.
488 if (GetID() == LLDB_INVALID_PROCESS_ID)
491 return PtraceWrapper(PT_DETACH, GetID());
494 Status NativeProcessNetBSD::Signal(int signo) {
497 if (kill(GetID(), signo))
498 error.SetErrorToErrno();
503 Status NativeProcessNetBSD::Kill() {
504 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
505 LLDB_LOG(log, "pid {0}", GetID());
510 case StateType::eStateInvalid:
511 case StateType::eStateExited:
512 case StateType::eStateCrashed:
513 case StateType::eStateDetached:
514 case StateType::eStateUnloaded:
515 // Nothing to do - the process is already dead.
516 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
517 StateAsCString(m_state));
520 case StateType::eStateConnected:
521 case StateType::eStateAttaching:
522 case StateType::eStateLaunching:
523 case StateType::eStateStopped:
524 case StateType::eStateRunning:
525 case StateType::eStateStepping:
526 case StateType::eStateSuspended:
527 // We can try to kill a process in these states.
531 if (kill(GetID(), SIGKILL) != 0) {
532 error.SetErrorToErrno();
539 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
540 MemoryRegionInfo &range_info) {
542 if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
544 return Status("unsupported");
547 Status error = PopulateMemoryRegionCache();
552 lldb::addr_t prev_base_address = 0;
553 // FIXME start by finding the last region that is <= target address using
554 // binary search. Data is sorted.
555 // There can be a ton of regions on pthreads apps with lots of threads.
556 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
558 MemoryRegionInfo &proc_entry_info = it->first;
559 // Sanity check assumption that memory map entries are ascending.
560 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
561 "descending memory map entries detected, unexpected");
562 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
563 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
564 // If the target address comes before this entry, indicate distance to next
566 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
567 range_info.GetRange().SetRangeBase(load_addr);
568 range_info.GetRange().SetByteSize(
569 proc_entry_info.GetRange().GetRangeBase() - load_addr);
570 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
571 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
572 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
573 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
575 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
576 // The target address is within the memory region we're processing here.
577 range_info = proc_entry_info;
580 // The target memory address comes somewhere after the region we just
583 // If we made it here, we didn't find an entry that contained the given
584 // address. Return the load_addr as start and the amount of bytes betwwen
585 // load address and the end of the memory as size.
586 range_info.GetRange().SetRangeBase(load_addr);
587 range_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS);
588 range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
589 range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
590 range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
591 range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
595 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
596 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
597 // If our cache is empty, pull the latest. There should always be at least
598 // one memory region if memory region handling is supported.
599 if (!m_mem_region_cache.empty()) {
600 LLDB_LOG(log, "reusing {0} cached memory region entries",
601 m_mem_region_cache.size());
605 struct kinfo_vmentry *vm;
607 vm = kinfo_getvmmap(GetID(), &count);
609 m_supports_mem_region = LazyBool::eLazyBoolNo;
611 error.SetErrorString("not supported");
614 for (i = 0; i < count; i++) {
615 MemoryRegionInfo info;
617 info.GetRange().SetRangeBase(vm[i].kve_start);
618 info.GetRange().SetRangeEnd(vm[i].kve_end);
619 info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
621 if (vm[i].kve_protection & VM_PROT_READ)
622 info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
624 info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
626 if (vm[i].kve_protection & VM_PROT_WRITE)
627 info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
629 info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
631 if (vm[i].kve_protection & VM_PROT_EXECUTE)
632 info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
634 info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
636 if (vm[i].kve_path[0])
637 info.SetName(vm[i].kve_path);
639 m_mem_region_cache.emplace_back(
640 info, FileSpec(info.GetName().GetCString(), true));
644 if (m_mem_region_cache.empty()) {
645 // No entries after attempting to read them. This shouldn't happen. Assume
646 // we don't support map entries.
647 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
648 "for memory region metadata retrieval");
649 m_supports_mem_region = LazyBool::eLazyBoolNo;
651 error.SetErrorString("not supported");
654 LLDB_LOG(log, "read {0} memory region entries from process {1}",
655 m_mem_region_cache.size(), GetID());
656 // We support memory retrieval, remember that.
657 m_supports_mem_region = LazyBool::eLazyBoolYes;
661 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
662 lldb::addr_t &addr) {
663 return Status("Unimplemented");
666 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
667 return Status("Unimplemented");
670 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
671 // punt on this for now
672 return LLDB_INVALID_ADDRESS;
675 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
677 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
680 return Status("NativeProcessNetBSD does not support hardware breakpoints");
682 return SetSoftwareBreakpoint(addr, size);
685 Status NativeProcessNetBSD::GetSoftwareBreakpointTrapOpcode(
686 size_t trap_opcode_size_hint, size_t &actual_opcode_size,
687 const uint8_t *&trap_opcode_bytes) {
688 static const uint8_t g_i386_opcode[] = {0xCC};
690 switch (m_arch.GetMachine()) {
691 case llvm::Triple::x86:
692 case llvm::Triple::x86_64:
693 trap_opcode_bytes = g_i386_opcode;
694 actual_opcode_size = sizeof(g_i386_opcode);
697 assert(false && "CPU type not supported!");
698 return Status("CPU type not supported");
702 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
703 FileSpec &file_spec) {
704 return Status("Unimplemented");
707 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
708 lldb::addr_t &load_addr) {
709 load_addr = LLDB_INVALID_ADDRESS;
713 void NativeProcessNetBSD::SigchldHandler() {
714 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
715 // Process all pending waitpid notifications.
718 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
721 return; // We are done.
723 if (wait_pid == -1) {
724 Status error(errno, eErrorTypePOSIX);
725 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
728 WaitStatus wait_status = WaitStatus::Decode(status);
729 bool exited = wait_status.type == WaitStatus::Exit ||
730 (wait_status.type == WaitStatus::Signal &&
731 wait_pid == static_cast<::pid_t>(GetID()));
734 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
735 GetID(), wait_pid, status, exited);
738 MonitorExited(wait_pid, wait_status);
740 assert(wait_status.type == WaitStatus::Stop);
741 MonitorCallback(wait_pid, wait_status.status);
745 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
746 for (const auto &thread : m_threads) {
747 assert(thread && "thread list should not contain NULL threads");
748 if (thread->GetID() == thread_id) {
749 // We have this thread.
754 // We don't have this thread.
758 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
760 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_THREAD));
761 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
763 assert(!HasThreadNoLock(thread_id) &&
764 "attempted to add a thread by id that already exists");
766 // If this is the first thread, save it as the current thread
767 if (m_threads.empty())
768 SetCurrentThreadID(thread_id);
770 m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
771 return static_cast<NativeThreadNetBSD &>(*m_threads.back());
774 Status NativeProcessNetBSD::Attach() {
775 // Attach to the requested process.
776 // An attach will cause the thread to stop with a SIGSTOP.
777 Status status = PtraceWrapper(PT_ATTACH, m_pid);
782 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
783 // point we should have a thread stopped if waitpid succeeds.
784 if ((wstatus = waitpid(m_pid, NULL, WALLSIG)) < 0)
785 return Status(errno, eErrorTypePOSIX);
787 /* Initialize threads */
788 status = ReinitializeThreads();
792 for (const auto &thread : m_threads)
793 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
795 // Let our process instance know the thread has stopped.
796 SetState(StateType::eStateStopped);
800 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
801 size_t size, size_t &bytes_read) {
802 unsigned char *dst = static_cast<unsigned char *>(buf);
803 struct ptrace_io_desc io;
805 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
806 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
809 io.piod_op = PIOD_READ_D;
813 io.piod_offs = (void *)(addr + bytes_read);
814 io.piod_addr = dst + bytes_read;
816 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
820 bytes_read = io.piod_len;
821 io.piod_len = size - bytes_read;
822 } while (bytes_read < size);
827 Status NativeProcessNetBSD::ReadMemoryWithoutTrap(lldb::addr_t addr, void *buf,
829 size_t &bytes_read) {
830 Status error = ReadMemory(addr, buf, size, bytes_read);
833 return m_breakpoint_list.RemoveTrapsFromBuffer(addr, buf, size);
836 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
837 size_t size, size_t &bytes_written) {
838 const unsigned char *src = static_cast<const unsigned char *>(buf);
840 struct ptrace_io_desc io;
842 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_MEMORY));
843 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
846 io.piod_op = PIOD_WRITE_D;
850 io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
851 io.piod_offs = (void *)(addr + bytes_written);
853 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
857 bytes_written = io.piod_len;
858 io.piod_len = size - bytes_written;
859 } while (bytes_written < size);
864 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
865 NativeProcessNetBSD::GetAuxvData() const {
867 * ELF_AUX_ENTRIES is currently restricted to kernel
868 * (<sys/exec_elf.h> r. 1.155 specifies 15)
870 * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
871 * information isn't needed.
873 size_t auxv_size = 100 * sizeof(AuxInfo);
875 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
876 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
878 struct ptrace_io_desc io;
879 io.piod_op = PIOD_READ_AUXV;
881 io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
882 io.piod_len = auxv_size;
884 Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
887 return std::error_code(error.GetError(), std::generic_category());
890 return std::error_code(ECANCELED, std::generic_category());
892 return std::move(buf);
895 Status NativeProcessNetBSD::ReinitializeThreads() {
899 // Initialize new thread
900 struct ptrace_lwpinfo info = {};
901 Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
905 // Reinitialize from scratch threads and register them in process
906 while (info.pl_lwpid != 0) {
907 AddThread(info.pl_lwpid);
908 error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));