LLDB  mainline
NativeProcessNetBSD.cpp
Go to the documentation of this file.
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 
14 #include "lldb/Host/HostProcess.h"
17 #include "lldb/Target/Process.h"
18 #include "lldb/Utility/State.h"
19 #include "llvm/Support/Errno.h"
20 
21 // System includes - They have to be included after framework includes because
22 // they define some macros which collide with variable names in other modules
23 // clang-format off
24 #include <sys/types.h>
25 #include <sys/ptrace.h>
26 #include <sys/sysctl.h>
27 #include <sys/wait.h>
28 #include <uvm/uvm_prot.h>
29 #include <elf.h>
30 #include <util.h>
31 // clang-format on
32 
33 using namespace lldb;
34 using namespace lldb_private;
35 using namespace lldb_private::process_netbsd;
36 using namespace llvm;
37 
38 // Simple helper function to ensure flags are enabled on the given file
39 // descriptor.
40 static Status EnsureFDFlags(int fd, int flags) {
41  Status error;
42 
43  int status = fcntl(fd, F_GETFL);
44  if (status == -1) {
45  error.SetErrorToErrno();
46  return error;
47  }
48 
49  if (fcntl(fd, F_SETFL, status | flags) == -1) {
50  error.SetErrorToErrno();
51  return error;
52  }
53 
54  return error;
55 }
56 
57 // Public Static Methods
58 
59 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
60 NativeProcessNetBSD::Factory::Launch(ProcessLaunchInfo &launch_info,
61  NativeDelegate &native_delegate,
62  MainLoop &mainloop) const {
64 
65  Status status;
67  .LaunchProcess(launch_info, status)
68  .GetProcessId();
69  LLDB_LOG(log, "pid = {0:x}", pid);
70  if (status.Fail()) {
71  LLDB_LOG(log, "failed to launch process: {0}", status);
72  return status.ToError();
73  }
74 
75  // Wait for the child process to trap on its call to execve.
76  int wstatus;
77  ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
78  assert(wpid == pid);
79  (void)wpid;
80  if (!WIFSTOPPED(wstatus)) {
81  LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
82  WaitStatus::Decode(wstatus));
83  return llvm::make_error<StringError>("Could not sync with inferior process",
84  llvm::inconvertibleErrorCode());
85  }
86  LLDB_LOG(log, "inferior started, now in stopped state");
87 
89  if (!Host::GetProcessInfo(pid, Info)) {
90  return llvm::make_error<StringError>("Cannot get process architecture",
91  llvm::inconvertibleErrorCode());
92  }
93 
94  // Set the architecture to the exe architecture.
95  LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
97 
98  std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
99  pid, launch_info.GetPTY().ReleaseMasterFileDescriptor(), native_delegate,
100  Info.GetArchitecture(), mainloop));
101 
102  status = process_up->ReinitializeThreads();
103  if (status.Fail())
104  return status.ToError();
105 
106  for (const auto &thread : process_up->m_threads)
107  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
108  process_up->SetState(StateType::eStateStopped, false);
109 
110  return std::move(process_up);
111 }
112 
113 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
114 NativeProcessNetBSD::Factory::Attach(
116  MainLoop &mainloop) const {
118  LLDB_LOG(log, "pid = {0:x}", pid);
119 
120  // Retrieve the architecture for the running process.
121  ProcessInstanceInfo Info;
122  if (!Host::GetProcessInfo(pid, Info)) {
123  return llvm::make_error<StringError>("Cannot get process architecture",
124  llvm::inconvertibleErrorCode());
125  }
126 
127  std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
128  pid, -1, native_delegate, Info.GetArchitecture(), mainloop));
129 
130  Status status = process_up->Attach();
131  if (!status.Success())
132  return status.ToError();
133 
134  return std::move(process_up);
135 }
136 
137 // Public Instance Methods
138 
139 NativeProcessNetBSD::NativeProcessNetBSD(::pid_t pid, int terminal_fd,
140  NativeDelegate &delegate,
141  const ArchSpec &arch,
142  MainLoop &mainloop)
143  : NativeProcessProtocol(pid, terminal_fd, delegate), m_arch(arch) {
144  if (m_terminal_fd != -1) {
145  Status status = EnsureFDFlags(m_terminal_fd, O_NONBLOCK);
146  assert(status.Success());
147  }
148 
149  Status status;
150  m_sigchld_handle = mainloop.RegisterSignal(
151  SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
152  assert(m_sigchld_handle && status.Success());
153 }
154 
155 // Handles all waitpid events from the inferior process.
156 void NativeProcessNetBSD::MonitorCallback(lldb::pid_t pid, int signal) {
157  switch (signal) {
158  case SIGTRAP:
159  return MonitorSIGTRAP(pid);
160  case SIGSTOP:
161  return MonitorSIGSTOP(pid);
162  default:
163  return MonitorSignal(pid, signal);
164  }
165 }
166 
167 void NativeProcessNetBSD::MonitorExited(lldb::pid_t pid, WaitStatus status) {
169 
170  LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
171 
172  /* Stop Tracking All Threads attached to Process */
173  m_threads.clear();
174 
175  SetExitStatus(status, true);
176 
177  // Notify delegate that our process has exited.
178  SetState(StateType::eStateExited, true);
179 }
180 
181 void NativeProcessNetBSD::MonitorSIGSTOP(lldb::pid_t pid) {
182  ptrace_siginfo_t info;
183 
184  const auto siginfo_err =
185  PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
186 
187  // Get details on the signal raised.
188  if (siginfo_err.Success()) {
189  // Handle SIGSTOP from LLGS (LLDB GDB Server)
190  if (info.psi_siginfo.si_code == SI_USER &&
191  info.psi_siginfo.si_pid == ::getpid()) {
192  /* Stop Tracking all Threads attached to Process */
193  for (const auto &thread : m_threads) {
194  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
195  SIGSTOP, &info.psi_siginfo);
196  }
197  }
198  }
199 }
200 
201 void NativeProcessNetBSD::MonitorSIGTRAP(lldb::pid_t pid) {
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  return;
211  }
212 
213  switch (info.psi_siginfo.si_code) {
214  case TRAP_BRKPT:
215  for (const auto &thread : m_threads) {
216  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
217  FixupBreakpointPCAsNeeded(static_cast<NativeThreadNetBSD &>(*thread));
218  }
219  SetState(StateType::eStateStopped, true);
220  break;
221  case TRAP_TRACE:
222  for (const auto &thread : m_threads)
223  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByTrace();
224  SetState(StateType::eStateStopped, true);
225  break;
226  case TRAP_EXEC: {
227  Status error = ReinitializeThreads();
228  if (error.Fail()) {
229  SetState(StateType::eStateInvalid);
230  return;
231  }
232 
233  // Let our delegate know we have just exec'd.
234  NotifyDidExec();
235 
236  for (const auto &thread : m_threads)
237  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
238  SetState(StateType::eStateStopped, true);
239  } break;
240  case TRAP_DBREG: {
241  // If a watchpoint was hit, report it
242  uint32_t wp_index;
243  Status error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
244  .GetRegisterContext()
245  .GetWatchpointHitIndex(
246  wp_index, (uintptr_t)info.psi_siginfo.si_addr);
247  if (error.Fail())
248  LLDB_LOG(log,
249  "received error while checking for watchpoint hits, pid = "
250  "{0}, LWP = {1}, error = {2}",
251  GetID(), info.psi_lwpid, error);
252  if (wp_index != LLDB_INVALID_INDEX32) {
253  for (const auto &thread : m_threads)
254  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByWatchpoint(
255  wp_index);
256  SetState(StateType::eStateStopped, true);
257  break;
258  }
259 
260  // If a breakpoint was hit, report it
261  uint32_t bp_index;
262  error = static_cast<NativeThreadNetBSD &>(*m_threads[info.psi_lwpid])
263  .GetRegisterContext()
264  .GetHardwareBreakHitIndex(bp_index,
265  (uintptr_t)info.psi_siginfo.si_addr);
266  if (error.Fail())
267  LLDB_LOG(log,
268  "received error while checking for hardware "
269  "breakpoint hits, pid = {0}, LWP = {1}, error = {2}",
270  GetID(), info.psi_lwpid, error);
271  if (bp_index != LLDB_INVALID_INDEX32) {
272  for (const auto &thread : m_threads)
273  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByBreakpoint();
274  SetState(StateType::eStateStopped, true);
275  break;
276  }
277  } break;
278  }
279 }
280 
281 void NativeProcessNetBSD::MonitorSignal(lldb::pid_t pid, int signal) {
282  ptrace_siginfo_t info;
283  const auto siginfo_err =
284  PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
285 
286  for (const auto &thread : m_threads) {
287  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
288  info.psi_siginfo.si_signo, &info.psi_siginfo);
289  }
290  SetState(StateType::eStateStopped, true);
291 }
292 
294  int data, int *result) {
296  Status error;
297  int ret;
298 
299  errno = 0;
300  ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
301 
302  if (ret == -1)
303  error.SetErrorToErrno();
304 
305  if (result)
306  *result = ret;
307 
308  LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
309 
310  if (error.Fail())
311  LLDB_LOG(log, "ptrace() failed: {0}", error);
312 
313  return error;
314 }
315 
316 Status NativeProcessNetBSD::Resume(const ResumeActionList &resume_actions) {
318  LLDB_LOG(log, "pid {0}", GetID());
319 
320  const auto &thread = m_threads[0];
321  const ResumeAction *const action =
322  resume_actions.GetActionForThread(thread->GetID(), true);
323 
324  if (action == nullptr) {
325  LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
326  thread->GetID());
327  return Status();
328  }
329 
330  Status error;
331 
332  switch (action->state) {
333  case eStateRunning: {
334  // Run the thread, possibly feeding it the signal.
335  error = NativeProcessNetBSD::PtraceWrapper(PT_CONTINUE, GetID(), (void *)1,
336  action->signal);
337  if (!error.Success())
338  return error;
339  for (const auto &thread : m_threads)
340  static_cast<NativeThreadNetBSD &>(*thread).SetRunning();
341  SetState(eStateRunning, true);
342  break;
343  }
344  case eStateStepping:
345  // Run the thread, possibly feeding it the signal.
346  error = NativeProcessNetBSD::PtraceWrapper(PT_STEP, GetID(), (void *)1,
347  action->signal);
348  if (!error.Success())
349  return error;
350  for (const auto &thread : m_threads)
351  static_cast<NativeThreadNetBSD &>(*thread).SetStepping();
352  SetState(eStateStepping, true);
353  break;
354 
355  case eStateSuspended:
356  case eStateStopped:
357  llvm_unreachable("Unexpected state");
358 
359  default:
360  return Status("NativeProcessNetBSD::%s (): unexpected state %s specified "
361  "for pid %" PRIu64 ", tid %" PRIu64,
362  __FUNCTION__, StateAsCString(action->state), GetID(),
363  thread->GetID());
364  }
365 
366  return Status();
367 }
368 
369 Status NativeProcessNetBSD::Halt() {
370  Status error;
371 
372  if (kill(GetID(), SIGSTOP) != 0)
373  error.SetErrorToErrno();
374 
375  return error;
376 }
377 
378 Status NativeProcessNetBSD::Detach() {
379  Status error;
380 
381  // Stop monitoring the inferior.
382  m_sigchld_handle.reset();
383 
384  // Tell ptrace to detach from the process.
385  if (GetID() == LLDB_INVALID_PROCESS_ID)
386  return error;
387 
388  return PtraceWrapper(PT_DETACH, GetID());
389 }
390 
391 Status NativeProcessNetBSD::Signal(int signo) {
392  Status error;
393 
394  if (kill(GetID(), signo))
395  error.SetErrorToErrno();
396 
397  return error;
398 }
399 
400 Status NativeProcessNetBSD::Kill() {
402  LLDB_LOG(log, "pid {0}", GetID());
403 
404  Status error;
405 
406  switch (m_state) {
412  // Nothing to do - the process is already dead.
413  LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
414  StateAsCString(m_state));
415  return error;
416 
424  // We can try to kill a process in these states.
425  break;
426  }
427 
428  if (kill(GetID(), SIGKILL) != 0) {
429  error.SetErrorToErrno();
430  return error;
431  }
432 
433  return error;
434 }
435 
436 Status NativeProcessNetBSD::GetMemoryRegionInfo(lldb::addr_t load_addr,
437  MemoryRegionInfo &range_info) {
438 
439  if (m_supports_mem_region == LazyBool::eLazyBoolNo) {
440  // We're done.
441  return Status("unsupported");
442  }
443 
444  Status error = PopulateMemoryRegionCache();
445  if (error.Fail()) {
446  return error;
447  }
448 
449  lldb::addr_t prev_base_address = 0;
450  // FIXME start by finding the last region that is <= target address using
451  // binary search. Data is sorted.
452  // There can be a ton of regions on pthreads apps with lots of threads.
453  for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
454  ++it) {
455  MemoryRegionInfo &proc_entry_info = it->first;
456  // Sanity check assumption that memory map entries are ascending.
457  assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
458  "descending memory map entries detected, unexpected");
459  prev_base_address = proc_entry_info.GetRange().GetRangeBase();
460  UNUSED_IF_ASSERT_DISABLED(prev_base_address);
461  // If the target address comes before this entry, indicate distance to next
462  // region.
463  if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
464  range_info.GetRange().SetRangeBase(load_addr);
465  range_info.GetRange().SetByteSize(
466  proc_entry_info.GetRange().GetRangeBase() - load_addr);
467  range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
468  range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
469  range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
470  range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
471  return error;
472  } else if (proc_entry_info.GetRange().Contains(load_addr)) {
473  // The target address is within the memory region we're processing here.
474  range_info = proc_entry_info;
475  return error;
476  }
477  // The target memory address comes somewhere after the region we just
478  // parsed.
479  }
480  // If we made it here, we didn't find an entry that contained the given
481  // address. Return the load_addr as start and the amount of bytes betwwen
482  // load address and the end of the memory as size.
483  range_info.GetRange().SetRangeBase(load_addr);
485  range_info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
486  range_info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
487  range_info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
488  range_info.SetMapped(MemoryRegionInfo::OptionalBool::eNo);
489  return error;
490 }
491 
492 Status NativeProcessNetBSD::PopulateMemoryRegionCache() {
494  // If our cache is empty, pull the latest. There should always be at least
495  // one memory region if memory region handling is supported.
496  if (!m_mem_region_cache.empty()) {
497  LLDB_LOG(log, "reusing {0} cached memory region entries",
498  m_mem_region_cache.size());
499  return Status();
500  }
501 
502  struct kinfo_vmentry *vm;
503  size_t count, i;
504  vm = kinfo_getvmmap(GetID(), &count);
505  if (vm == NULL) {
506  m_supports_mem_region = LazyBool::eLazyBoolNo;
507  Status error;
508  error.SetErrorString("not supported");
509  return error;
510  }
511  for (i = 0; i < count; i++) {
512  MemoryRegionInfo info;
513  info.Clear();
514  info.GetRange().SetRangeBase(vm[i].kve_start);
515  info.GetRange().SetRangeEnd(vm[i].kve_end);
516  info.SetMapped(MemoryRegionInfo::OptionalBool::eYes);
517 
518  if (vm[i].kve_protection & VM_PROT_READ)
519  info.SetReadable(MemoryRegionInfo::OptionalBool::eYes);
520  else
521  info.SetReadable(MemoryRegionInfo::OptionalBool::eNo);
522 
523  if (vm[i].kve_protection & VM_PROT_WRITE)
524  info.SetWritable(MemoryRegionInfo::OptionalBool::eYes);
525  else
526  info.SetWritable(MemoryRegionInfo::OptionalBool::eNo);
527 
528  if (vm[i].kve_protection & VM_PROT_EXECUTE)
529  info.SetExecutable(MemoryRegionInfo::OptionalBool::eYes);
530  else
531  info.SetExecutable(MemoryRegionInfo::OptionalBool::eNo);
532 
533  if (vm[i].kve_path[0])
534  info.SetName(vm[i].kve_path);
535 
536  m_mem_region_cache.emplace_back(
537  info, FileSpec(info.GetName().GetCString()));
538  }
539  free(vm);
540 
541  if (m_mem_region_cache.empty()) {
542  // No entries after attempting to read them. This shouldn't happen. Assume
543  // we don't support map entries.
544  LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
545  "for memory region metadata retrieval");
546  m_supports_mem_region = LazyBool::eLazyBoolNo;
547  Status error;
548  error.SetErrorString("not supported");
549  return error;
550  }
551  LLDB_LOG(log, "read {0} memory region entries from process {1}",
552  m_mem_region_cache.size(), GetID());
553  // We support memory retrieval, remember that.
554  m_supports_mem_region = LazyBool::eLazyBoolYes;
555  return Status();
556 }
557 
558 Status NativeProcessNetBSD::AllocateMemory(size_t size, uint32_t permissions,
559  lldb::addr_t &addr) {
560  return Status("Unimplemented");
561 }
562 
563 Status NativeProcessNetBSD::DeallocateMemory(lldb::addr_t addr) {
564  return Status("Unimplemented");
565 }
566 
567 lldb::addr_t NativeProcessNetBSD::GetSharedLibraryInfoAddress() {
568  // punt on this for now
569  return LLDB_INVALID_ADDRESS;
570 }
571 
572 size_t NativeProcessNetBSD::UpdateThreads() { return m_threads.size(); }
573 
574 Status NativeProcessNetBSD::SetBreakpoint(lldb::addr_t addr, uint32_t size,
575  bool hardware) {
576  if (hardware)
577  return Status("NativeProcessNetBSD does not support hardware breakpoints");
578  else
579  return SetSoftwareBreakpoint(addr, size);
580 }
581 
582 Status NativeProcessNetBSD::GetLoadedModuleFileSpec(const char *module_path,
583  FileSpec &file_spec) {
584  return Status("Unimplemented");
585 }
586 
587 Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
588  lldb::addr_t &load_addr) {
589  load_addr = LLDB_INVALID_ADDRESS;
590  return Status();
591 }
592 
593 void NativeProcessNetBSD::SigchldHandler() {
595  // Process all pending waitpid notifications.
596  int status;
597  ::pid_t wait_pid =
598  llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WALLSIG | WNOHANG);
599 
600  if (wait_pid == 0)
601  return; // We are done.
602 
603  if (wait_pid == -1) {
604  Status error(errno, eErrorTypePOSIX);
605  LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
606  }
607 
608  WaitStatus wait_status = WaitStatus::Decode(status);
609  bool exited = wait_status.type == WaitStatus::Exit ||
610  (wait_status.type == WaitStatus::Signal &&
611  wait_pid == static_cast<::pid_t>(GetID()));
612 
613  LLDB_LOG(log,
614  "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
615  GetID(), wait_pid, status, exited);
616 
617  if (exited)
618  MonitorExited(wait_pid, wait_status);
619  else {
620  assert(wait_status.type == WaitStatus::Stop);
621  MonitorCallback(wait_pid, wait_status.status);
622  }
623 }
624 
625 bool NativeProcessNetBSD::HasThreadNoLock(lldb::tid_t thread_id) {
626  for (const auto &thread : m_threads) {
627  assert(thread && "thread list should not contain NULL threads");
628  if (thread->GetID() == thread_id) {
629  // We have this thread.
630  return true;
631  }
632  }
633 
634  // We don't have this thread.
635  return false;
636 }
637 
638 NativeThreadNetBSD &NativeProcessNetBSD::AddThread(lldb::tid_t thread_id) {
639 
641  LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
642 
643  assert(!HasThreadNoLock(thread_id) &&
644  "attempted to add a thread by id that already exists");
645 
646  // If this is the first thread, save it as the current thread
647  if (m_threads.empty())
648  SetCurrentThreadID(thread_id);
649 
650  m_threads.push_back(llvm::make_unique<NativeThreadNetBSD>(*this, thread_id));
651  return static_cast<NativeThreadNetBSD &>(*m_threads.back());
652 }
653 
654 Status NativeProcessNetBSD::Attach() {
655  // Attach to the requested process.
656  // An attach will cause the thread to stop with a SIGSTOP.
657  Status status = PtraceWrapper(PT_ATTACH, m_pid);
658  if (status.Fail())
659  return status;
660 
661  int wstatus;
662  // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
663  // point we should have a thread stopped if waitpid succeeds.
664  if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid,
665  m_pid, nullptr, WALLSIG)) < 0)
666  return Status(errno, eErrorTypePOSIX);
667 
668  /* Initialize threads */
669  status = ReinitializeThreads();
670  if (status.Fail())
671  return status;
672 
673  for (const auto &thread : m_threads)
674  static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
675 
676  // Let our process instance know the thread has stopped.
677  SetState(StateType::eStateStopped);
678  return Status();
679 }
680 
681 Status NativeProcessNetBSD::ReadMemory(lldb::addr_t addr, void *buf,
682  size_t size, size_t &bytes_read) {
683  unsigned char *dst = static_cast<unsigned char *>(buf);
684  struct ptrace_io_desc io;
685 
687  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
688 
689  bytes_read = 0;
690  io.piod_op = PIOD_READ_D;
691  io.piod_len = size;
692 
693  do {
694  io.piod_offs = (void *)(addr + bytes_read);
695  io.piod_addr = dst + bytes_read;
696 
697  Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
698  if (error.Fail() || io.piod_len == 0)
699  return error;
700 
701  bytes_read += io.piod_len;
702  io.piod_len = size - bytes_read;
703  } while (bytes_read < size);
704 
705  return Status();
706 }
707 
708 Status NativeProcessNetBSD::WriteMemory(lldb::addr_t addr, const void *buf,
709  size_t size, size_t &bytes_written) {
710  const unsigned char *src = static_cast<const unsigned char *>(buf);
711  Status error;
712  struct ptrace_io_desc io;
713 
715  LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
716 
717  bytes_written = 0;
718  io.piod_op = PIOD_WRITE_D;
719  io.piod_len = size;
720 
721  do {
722  io.piod_addr = const_cast<void *>(static_cast<const void *>(src + bytes_written));
723  io.piod_offs = (void *)(addr + bytes_written);
724 
725  Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
726  if (error.Fail() || io.piod_len == 0)
727  return error;
728 
729  bytes_written += io.piod_len;
730  io.piod_len = size - bytes_written;
731  } while (bytes_written < size);
732 
733  return error;
734 }
735 
736 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
737 NativeProcessNetBSD::GetAuxvData() const {
738  /*
739  * ELF_AUX_ENTRIES is currently restricted to kernel
740  * (<sys/exec_elf.h> r. 1.155 specifies 15)
741  *
742  * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
743  * information isn't needed.
744  */
745  size_t auxv_size = 100 * sizeof(AuxInfo);
746 
747  ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
748  llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
749 
750  struct ptrace_io_desc io;
751  io.piod_op = PIOD_READ_AUXV;
752  io.piod_offs = 0;
753  io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
754  io.piod_len = auxv_size;
755 
756  Status error = NativeProcessNetBSD::PtraceWrapper(PT_IO, GetID(), &io);
757 
758  if (error.Fail())
759  return std::error_code(error.GetError(), std::generic_category());
760 
761  if (io.piod_len < 1)
762  return std::error_code(ECANCELED, std::generic_category());
763 
764  return std::move(buf);
765 }
766 
767 Status NativeProcessNetBSD::ReinitializeThreads() {
768  // Clear old threads
769  m_threads.clear();
770 
771  // Initialize new thread
772  struct ptrace_lwpinfo info = {};
773  Status error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
774  if (error.Fail()) {
775  return error;
776  }
777  // Reinitialize from scratch threads and register them in process
778  while (info.pl_lwpid != 0) {
779  AddThread(info.pl_lwpid);
780  error = PtraceWrapper(PT_LWPINFO, GetID(), &info, sizeof(info));
781  if (error.Fail()) {
782  return error;
783  }
784  }
785 
786  return error;
787 }
llvm::Error ToError() const
Definition: Status.cpp:88
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:134
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition: State.cpp:14
Enumerations for broadcasting.
Definition: SBLaunchInfo.h:14
void SetExecutable(OptionalBool val)
Definition: Debugger.h:71
bool Contains(BaseType r) const
Definition: RangeMap.h:77
long PtraceWrapper(int req, lldb::pid_t pid, void *addr, int data, const char *reqName, const char *file, int line)
Process is currently trying to attach.
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:92
static Status EnsureFDFlags(int fd, int flags)
#define O_NONBLOCK
#define POSIX_LOG_MEMORY
#define POSIX_LOG_THREAD
A file utility class.
Definition: FileSpec.h:55
An architecture specification class.
Definition: ArchSpec.h:32
void SetMapped(OptionalBool val)
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition: Debug.h:76
void SetName(const char *name)
Process or thread is stopped and can be examined.
POSIX error codes.
void SetRangeEnd(BaseType end)
Definition: RangeMap.h:64
#define LLDB_LOG(log,...)
Definition: Log.h:209
int ReleaseMasterFileDescriptor()
Release the master file descriptor.
Process or thread has crashed and can be examined.
#define SIGSTOP
void SetErrorToErrno()
Set the current error to errno.
Definition: Status.cpp:223
Process has exited and can&#39;t be examined.
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:591
#define LLDB_INVALID_ADDRESS
Invalid value definitions.
Definition: lldb-defines.h:85
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:86
lldb::StateType state
Definition: Debug.h:23
Log * GetLogIfAllCategoriesSet(uint32_t mask)
Definition: Logging.cpp:57
#define POSIX_LOG_PROCESS
Process is connected to remote debug services, but not launched or attached to anything yet...
Process has been detached and can&#39;t be examined.
Process is in the process of launching.
uint64_t tid_t
Definition: lldb-types.h:86
void SetErrorString(llvm::StringRef err_str)
Set the current error string to err_str.
Definition: Status.cpp:241
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:62
bool Success() const
Test for success condition.
Definition: Status.cpp:287
Process or thread is in the process of stepping and can not be examined.
Process is object is valid, but not currently loaded.
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
#define SIGKILL
void SetByteSize(SizeType s)
Definition: RangeMap.h:73
Manages communication with the inferior (debugee) process.
uint64_t addr_t
Definition: lldb-types.h:83
void SetReadable(OptionalBool val)
bool Fail() const
Test for error condition.
Definition: Status.cpp:181
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:247
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
Definition: MainLoop.cpp:297
Definition: SBAddress.h:15
uint64_t pid_t
Definition: lldb-types.h:85
void SetRangeBase(BaseType b)
Definition: RangeMap.h:48
void SetWritable(OptionalBool val)
#define POSIX_LOG_PTRACE
#define SIGTRAP
ValueType GetError() const
Access the error value.
Definition: Status.cpp:174
lldb::pid_t GetProcessId() const
Definition: HostProcess.cpp:29
An error handling class.
Definition: Status.h:44
BaseType GetRangeBase() const
Definition: RangeMap.h:46
Process or thread is running and can&#39;t be examined.