LLDB mainline
NativeProcessNetBSD.cpp
Go to the documentation of this file.
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
10
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
32using namespace lldb;
33using namespace lldb_private;
34using namespace lldb_private::process_netbsd;
35using namespace llvm;
36
37// Simple helper function to ensure flags are enabled on the given file
38// descriptor.
39static Status EnsureFDFlags(int fd, int flags) {
41
42 int status = fcntl(fd, F_GETFL);
43 if (status == -1) {
45 return error;
46 }
47
48 if (fcntl(fd, F_SETFL, status | flags) == -1) {
50 return error;
51 }
52
53 return error;
54}
55
56// Public Static Methods
57
58llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
60 NativeDelegate &native_delegate) {
62
63 Status status;
65 .LaunchProcess(launch_info, status)
66 .GetProcessId();
67 LLDB_LOG(log, "pid = {0:x}", pid);
68 if (status.Fail()) {
69 LLDB_LOG(log, "failed to launch process: {0}", status);
70 return status.ToError();
71 }
72
73 // Wait for the child process to trap on its call to execve.
74 int wstatus;
75 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
76 assert(wpid == pid);
77 (void)wpid;
78 if (!WIFSTOPPED(wstatus)) {
79 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
80 WaitStatus::Decode(wstatus));
81 return llvm::createStringError("Could not sync with inferior process");
82 }
83 LLDB_LOG(log, "inferior started, now in stopped state");
84
86 if (!Host::GetProcessInfo(pid, Info)) {
87 return llvm::createStringError("Cannot get process architecture");
88 }
89
90 // Set the architecture to the exe architecture.
91 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
92 Info.GetArchitecture().GetArchitectureName());
93
94 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
95 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
96 Info.GetArchitecture(), m_mainloop));
97
98 status = process_up->SetupTrace();
99 if (status.Fail())
100 return status.ToError();
101
102 for (const auto &thread : process_up->m_threads)
103 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
104 process_up->SetState(StateType::eStateStopped, false);
105
106 return std::move(process_up);
107}
108
109llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
113 LLDB_LOG(log, "pid = {0:x}", pid);
114
115 // Retrieve the architecture for the running process.
117 if (!Host::GetProcessInfo(pid, Info)) {
118 return llvm::createStringError("Cannot get process architecture");
119 }
120
121 std::unique_ptr<NativeProcessNetBSD> process_up(new NativeProcessNetBSD(
122 pid, -1, native_delegate, Info.GetArchitecture(), m_mainloop));
123
124 Status status = process_up->Attach();
125 if (!status.Success())
126 return status.ToError();
127
128 return std::move(process_up);
129}
130
137
138// Public Instance Methods
139
141 NativeDelegate &delegate,
142 const ArchSpec &arch,
143 MainLoop &mainloop)
144 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
145 m_main_loop(mainloop) {
146 if (m_terminal_fd != -1) {
148 assert(status.Success());
149 }
150
151 Status status;
153 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
154 assert(m_sigchld_handle && status.Success());
155}
156
157// Handles all waitpid events from the inferior process.
159 switch (signal) {
160 case SIGTRAP:
161 return MonitorSIGTRAP(pid);
162 case SIGSTOP:
163 return MonitorSIGSTOP(pid);
164 default:
165 return MonitorSignal(pid, signal);
166 }
167}
168
171
172 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
173
174 /* Stop Tracking All Threads attached to Process */
175 m_threads.clear();
176
177 SetExitStatus(status, true);
178
179 // Notify delegate that our process has exited.
181}
182
184 ptrace_siginfo_t info;
185
186 const auto siginfo_err =
187 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
188
189 // Get details on the signal raised.
190 if (siginfo_err.Success()) {
191 // Handle SIGSTOP from LLGS (LLDB GDB Server)
192 if (info.psi_siginfo.si_code == SI_USER &&
193 info.psi_siginfo.si_pid == ::getpid()) {
194 /* Stop Tracking all Threads attached to Process */
195 for (const auto &thread : m_threads) {
196 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(
197 SIGSTOP, &info.psi_siginfo);
198 }
199 }
201 }
202}
203
206 ptrace_siginfo_t info;
207
208 const auto siginfo_err =
209 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
210
211 // Get details on the signal raised.
212 if (siginfo_err.Fail()) {
213 LLDB_LOG(log, "PT_GET_SIGINFO failed {0}", siginfo_err);
214 return;
215 }
216
217 LLDB_LOG(log, "got SIGTRAP, pid = {0}, lwpid = {1}, si_code = {2}", pid,
218 info.psi_lwpid, info.psi_siginfo.si_code);
219 NativeThreadNetBSD *thread = nullptr;
220
221 if (info.psi_lwpid > 0) {
222 for (const auto &t : m_threads) {
223 if (t->GetID() == static_cast<lldb::tid_t>(info.psi_lwpid)) {
224 thread = static_cast<NativeThreadNetBSD *>(t.get());
225 break;
226 }
227 static_cast<NativeThreadNetBSD *>(t.get())->SetStoppedWithNoReason();
228 }
229 if (!thread)
230 LLDB_LOG(log, "thread not found in m_threads, pid = {0}, LWP = {1}", pid,
231 info.psi_lwpid);
232 }
233
234 switch (info.psi_siginfo.si_code) {
235 case TRAP_BRKPT:
236 if (thread) {
237 thread->SetStoppedByBreakpoint();
239 }
241 return;
242 case TRAP_TRACE:
243 if (thread)
244 thread->SetStoppedByTrace();
246 return;
247 case TRAP_EXEC: {
249 if (error.Fail()) {
251 return;
252 }
253
254 // Let our delegate know we have just exec'd.
256
257 for (const auto &thread : m_threads)
258 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedByExec();
260 return;
261 }
262 case TRAP_CHLD: {
263 ptrace_state_t pst;
264 Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
265 if (error.Fail()) {
267 return;
268 }
269
270 assert(thread);
271 if (pst.pe_report_event == PTRACE_VFORK_DONE) {
273 thread->SetStoppedByVForkDone();
275 } else {
276 Status error =
277 PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
278 if (error.Fail())
280 }
281 } else {
282 assert(pst.pe_report_event == PTRACE_FORK ||
283 pst.pe_report_event == PTRACE_VFORK);
284 MonitorClone(pst.pe_other_pid, pst.pe_report_event == PTRACE_VFORK,
285 *thread);
286 }
287 return;
288 }
289 case TRAP_LWP: {
290 ptrace_state_t pst;
291 Status error = PtraceWrapper(PT_GET_PROCESS_STATE, pid, &pst, sizeof(pst));
292 if (error.Fail()) {
294 return;
295 }
296
297 switch (pst.pe_report_event) {
298 case PTRACE_LWP_CREATE: {
299 LLDB_LOG(log, "monitoring new thread, pid = {0}, LWP = {1}", pid,
300 pst.pe_lwp);
301 NativeThreadNetBSD &t = AddThread(pst.pe_lwp);
303 static_cast<NativeThreadNetBSD &>(*GetCurrentThread()));
304 if (error.Fail()) {
305 LLDB_LOG(log, "failed to copy watchpoints to new thread {0}: {1}",
306 pst.pe_lwp, error);
308 return;
309 }
310 } break;
311 case PTRACE_LWP_EXIT:
312 LLDB_LOG(log, "removing exited thread, pid = {0}, LWP = {1}", pid,
313 pst.pe_lwp);
314 RemoveThread(pst.pe_lwp);
315 break;
316 }
317
318 error = PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
319 if (error.Fail())
321 return;
322 }
323 case TRAP_DBREG: {
324 if (!thread)
325 break;
326
327 auto &regctx = static_cast<NativeRegisterContextNetBSD &>(
328 thread->GetRegisterContext());
329 uint32_t wp_index = LLDB_INVALID_INDEX32;
330 Status error = regctx.GetWatchpointHitIndex(
331 wp_index, (uintptr_t)info.psi_siginfo.si_addr);
332 if (error.Fail())
333 LLDB_LOG(log,
334 "received error while checking for watchpoint hits, pid = "
335 "{0}, LWP = {1}, error = {2}",
336 pid, info.psi_lwpid, error);
337 if (wp_index != LLDB_INVALID_INDEX32) {
338 thread->SetStoppedByWatchpoint(wp_index);
339 regctx.ClearWatchpointHit(wp_index);
341 return;
342 }
343
344 thread->SetStoppedByTrace();
346 return;
347 }
348 }
349
350 // Either user-generated SIGTRAP or an unknown event that would
351 // otherwise leave the debugger hanging.
352 LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
354}
355
358 ptrace_siginfo_t info;
359
360 const auto siginfo_err =
361 PtraceWrapper(PT_GET_SIGINFO, pid, &info, sizeof(info));
362 if (siginfo_err.Fail()) {
363 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
364 return;
365 }
366
367 for (const auto &abs_thread : m_threads) {
368 NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
369 assert(info.psi_lwpid >= 0);
370 if (info.psi_lwpid == 0 ||
371 static_cast<lldb::tid_t>(info.psi_lwpid) == thread.GetID())
372 thread.SetStoppedBySignal(info.psi_siginfo.si_signo, &info.psi_siginfo);
373 else
374 thread.SetStoppedWithNoReason();
375 }
377}
378
380#ifdef PT_STOP
381 return PtraceWrapper(PT_STOP, pid);
382#else
385 int ret;
386
387 errno = 0;
388 ret = kill(pid, SIGSTOP);
389
390 if (ret == -1)
392
393 LLDB_LOG(log, "kill({0}, SIGSTOP)", pid);
394
395 if (error.Fail())
396 LLDB_LOG(log, "kill() failed: {0}", error);
397
398 return error;
399#endif
400}
401
403 int data, int *result) {
406 int ret;
407
408 errno = 0;
409 ret = ptrace(req, static_cast<::pid_t>(pid), addr, data);
410
411 if (ret == -1)
413
414 if (result)
415 *result = ret;
416
417 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
418
419 if (error.Fail())
420 LLDB_LOG(log, "ptrace() failed: {0}", error);
421
422 return error;
423}
424
425static llvm::Expected<ptrace_siginfo_t> ComputeSignalInfo(
426 const std::vector<std::unique_ptr<NativeThreadProtocol>> &threads,
427 const ResumeActionList &resume_actions) {
428 // We need to account for three possible scenarios:
429 // 1. no signal being sent.
430 // 2. a signal being sent to one thread.
431 // 3. a signal being sent to the whole process.
432
433 // Count signaled threads. While at it, determine which signal is being sent
434 // and ensure there's only one.
435 size_t signaled_threads = 0;
436 int signal = LLDB_INVALID_SIGNAL_NUMBER;
437 lldb::tid_t signaled_lwp;
438 for (const auto &thread : threads) {
439 assert(thread && "thread list should not contain NULL threads");
440 const ResumeAction *action =
441 resume_actions.GetActionForThread(thread->GetID(), true);
442 if (action) {
443 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER) {
444 signaled_threads++;
445 if (action->signal != signal) {
446 if (signal != LLDB_INVALID_SIGNAL_NUMBER)
448 "NetBSD does not support passing multiple signals "
449 "simultaneously")
450 .ToError();
451 signal = action->signal;
452 signaled_lwp = thread->GetID();
453 }
454 }
455 }
456 }
457
458 if (signaled_threads == 0) {
459 ptrace_siginfo_t siginfo;
460 siginfo.psi_siginfo.si_signo = LLDB_INVALID_SIGNAL_NUMBER;
461 return siginfo;
462 }
463
464 if (signaled_threads > 1 && signaled_threads < threads.size())
466 "NetBSD does not support passing signal to 1<i<all threads")
467 .ToError();
468
469 ptrace_siginfo_t siginfo;
470 siginfo.psi_siginfo.si_signo = signal;
471 siginfo.psi_siginfo.si_code = SI_USER;
472 siginfo.psi_siginfo.si_pid = getpid();
473 siginfo.psi_siginfo.si_uid = getuid();
474 if (signaled_threads == 1)
475 siginfo.psi_lwpid = signaled_lwp;
476 else // signal for the whole process
477 siginfo.psi_lwpid = 0;
478 return siginfo;
479}
480
483 LLDB_LOG(log, "pid {0}", GetID());
484
485 Status ret;
486
487 Expected<ptrace_siginfo_t> siginfo =
488 ComputeSignalInfo(m_threads, resume_actions);
489 if (!siginfo)
490 return Status(siginfo.takeError());
491
492 for (const auto &abs_thread : m_threads) {
493 assert(abs_thread && "thread list should not contain NULL threads");
494 NativeThreadNetBSD &thread = static_cast<NativeThreadNetBSD &>(*abs_thread);
495
496 const ResumeAction *action =
497 resume_actions.GetActionForThread(thread.GetID(), true);
498 // we need to explicit issue suspend requests, so it is simpler to map it
499 // into proper action
500 ResumeAction suspend_action{thread.GetID(), eStateSuspended,
502
503 if (action == nullptr) {
504 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
505 thread.GetID());
506 action = &suspend_action;
507 }
508
509 LLDB_LOG(
510 log,
511 "processing resume action state {0} signal {1} for pid {2} tid {3}",
512 action->state, action->signal, GetID(), thread.GetID());
513
514 switch (action->state) {
515 case eStateRunning:
516 ret = thread.Resume();
517 break;
518 case eStateStepping:
519 ret = thread.SingleStep();
520 break;
521 case eStateSuspended:
522 case eStateStopped:
523 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
525 "Passing signal to suspended thread unsupported");
526
527 ret = thread.Suspend();
528 break;
529
530 default:
532 "NativeProcessNetBSD::%s (): unexpected state %s specified "
533 "for pid %" PRIu64 ", tid %" PRIu64,
534 __FUNCTION__, StateAsCString(action->state), GetID(), thread.GetID());
535 }
536
537 if (!ret.Success())
538 return ret;
539 }
540
541 int signal = 0;
542 if (siginfo->psi_siginfo.si_signo != LLDB_INVALID_SIGNAL_NUMBER) {
543 ret = PtraceWrapper(PT_SET_SIGINFO, GetID(), &siginfo.get(),
544 sizeof(*siginfo));
545 if (!ret.Success())
546 return ret;
547 signal = siginfo->psi_siginfo.si_signo;
548 }
549
550 ret =
551 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
552 if (ret.Success())
553 SetState(eStateRunning, true);
554 return ret;
555}
556
558
561
562 // Stop monitoring the inferior.
563 m_sigchld_handle.reset();
564
565 // Tell ptrace to detach from the process.
567 return error;
568
569 return PtraceWrapper(PT_DETACH, GetID(), reinterpret_cast<void *>(1));
570}
571
574
575 if (kill(GetID(), signo))
577
578 return error;
579}
580
582
585 LLDB_LOG(log, "pid {0}", GetID());
586
588
589 switch (m_state) {
595 // Nothing to do - the process is already dead.
596 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
598 return error;
599
607 // We can try to kill a process in these states.
608 break;
609 }
610
611 if (kill(GetID(), SIGKILL) != 0) {
613 return error;
614 }
615
616 return error;
617}
618
620 MemoryRegionInfo &range_info) {
621
623 // We're done.
624 return Status::FromErrorString("unsupported");
625 }
626
628 if (error.Fail()) {
629 return error;
630 }
631
632 lldb::addr_t prev_base_address = 0;
633 // FIXME start by finding the last region that is <= target address using
634 // binary search. Data is sorted.
635 // There can be a ton of regions on pthreads apps with lots of threads.
636 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
637 ++it) {
638 MemoryRegionInfo &proc_entry_info = it->first;
639 // Sanity check assumption that memory map entries are ascending.
640 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
641 "descending memory map entries detected, unexpected");
642 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
643 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
644 // If the target address comes before this entry, indicate distance to next
645 // region.
646 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
647 range_info.GetRange().SetRangeBase(load_addr);
648 range_info.GetRange().SetByteSize(
649 proc_entry_info.GetRange().GetRangeBase() - load_addr);
654 return error;
655 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
656 // The target address is within the memory region we're processing here.
657 range_info = proc_entry_info;
658 return error;
659 }
660 // The target memory address comes somewhere after the region we just
661 // parsed.
662 }
663 // If we made it here, we didn't find an entry that contained the given
664 // address. Return the load_addr as start and the amount of bytes betwwen
665 // load address and the end of the memory as size.
666 range_info.GetRange().SetRangeBase(load_addr);
672 return error;
673}
674
677 // If our cache is empty, pull the latest. There should always be at least
678 // one memory region if memory region handling is supported.
679 if (!m_mem_region_cache.empty()) {
680 LLDB_LOG(log, "reusing {0} cached memory region entries",
681 m_mem_region_cache.size());
682 return Status();
683 }
684
685 struct kinfo_vmentry *vm;
686 size_t count, i;
687 vm = kinfo_getvmmap(GetID(), &count);
688 if (vm == NULL) {
691 error = Status::FromErrorString("not supported");
692 return error;
693 }
694 for (i = 0; i < count; i++) {
695 MemoryRegionInfo info;
696 info.Clear();
697 info.GetRange().SetRangeBase(vm[i].kve_start);
698 info.GetRange().SetRangeEnd(vm[i].kve_end);
700
701 if (vm[i].kve_protection & VM_PROT_READ)
703 else
705
706 if (vm[i].kve_protection & VM_PROT_WRITE)
708 else
710
711 if (vm[i].kve_protection & VM_PROT_EXECUTE)
713 else
715
716 if (vm[i].kve_path[0])
717 info.SetName(vm[i].kve_path);
718
719 m_mem_region_cache.emplace_back(info,
720 FileSpec(info.GetName().GetCString()));
721 }
722 free(vm);
723
724 if (m_mem_region_cache.empty()) {
725 // No entries after attempting to read them. This shouldn't happen. Assume
726 // we don't support map entries.
727 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
728 "for memory region metadata retrieval");
731 error = Status::FromErrorString("not supported");
732 return error;
733 }
734 LLDB_LOG(log, "read {0} memory region entries from process {1}",
735 m_mem_region_cache.size(), GetID());
736 // We support memory retrieval, remember that.
738 return Status();
739}
740
745
747
749 bool hardware) {
750 if (hardware)
752 "NativeProcessNetBSD does not support hardware breakpoints");
753 else
754 return SetSoftwareBreakpoint(addr, size);
755}
756
758 FileSpec &file_spec) {
760 if (error.Fail())
761 return error;
762
763 FileSpec module_file_spec(module_path);
764 FileSystem::Instance().Resolve(module_file_spec);
765
766 file_spec.Clear();
767 for (const auto &it : m_mem_region_cache) {
768 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
769 file_spec = it.second;
770 return Status();
771 }
772 }
774 "Module file (%s) not found in process' memory map!",
775 module_file_spec.GetFilename().AsCString());
776}
777
778Status NativeProcessNetBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
779 lldb::addr_t &load_addr) {
780 load_addr = LLDB_INVALID_ADDRESS;
782 if (error.Fail())
783 return error;
784
785 FileSpec file(file_name);
786 for (const auto &it : m_mem_region_cache) {
787 if (it.second == file) {
788 load_addr = it.first.GetRange().GetRangeBase();
789 return Status();
790 }
791 }
792 return Status::FromErrorStringWithFormat("No load address found for file %s.",
793 file_name.str().c_str());
794}
795
798 int status;
799 ::pid_t wait_pid = llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status,
800 WALLSIG | WNOHANG);
801
802 if (wait_pid == 0)
803 return;
804
805 if (wait_pid == -1) {
807 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
808 return;
809 }
810
811 WaitStatus wait_status = WaitStatus::Decode(status);
812 bool exited = wait_status.type == WaitStatus::Exit ||
813 (wait_status.type == WaitStatus::Signal &&
814 wait_pid == static_cast<::pid_t>(GetID()));
815
816 LLDB_LOG(log,
817 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
818 GetID(), wait_pid, status, exited);
819
820 if (exited)
821 MonitorExited(wait_pid, wait_status);
822 else {
823 assert(wait_status.type == WaitStatus::Stop);
824 MonitorCallback(wait_pid, wait_status.status);
825 }
826}
827
829 for (const auto &thread : m_threads) {
830 assert(thread && "thread list should not contain NULL threads");
831 if (thread->GetID() == thread_id) {
832 // We have this thread.
833 return true;
834 }
835 }
836
837 // We don't have this thread.
838 return false;
839}
840
843 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
844
845 assert(thread_id > 0);
846 assert(!HasThreadNoLock(thread_id) &&
847 "attempted to add a thread by id that already exists");
848
849 // If this is the first thread, save it as the current thread
850 if (m_threads.empty())
851 SetCurrentThreadID(thread_id);
852
853 m_threads.push_back(std::make_unique<NativeThreadNetBSD>(*this, thread_id));
854 return static_cast<NativeThreadNetBSD &>(*m_threads.back());
855}
856
859 LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
860
861 assert(thread_id > 0);
862 assert(HasThreadNoLock(thread_id) &&
863 "attempted to remove a thread that does not exist");
864
865 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
866 if ((*it)->GetID() == thread_id) {
867 m_threads.erase(it);
868 break;
869 }
870 }
871}
872
874 // Attach to the requested process.
875 // An attach will cause the thread to stop with a SIGSTOP.
876 Status status = PtraceWrapper(PT_ATTACH, m_pid);
877 if (status.Fail())
878 return status;
879
880 int wstatus;
881 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
882 // point we should have a thread stopped if waitpid succeeds.
883 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr,
884 WALLSIG)) < 0)
885 return Status(errno, eErrorTypePOSIX);
886
887 // Initialize threads and tracing status
888 // NB: this needs to be called before we set thread state
889 status = SetupTrace();
890 if (status.Fail())
891 return status;
892
893 for (const auto &thread : m_threads)
894 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
895
896 // Let our process instance know the thread has stopped.
897 SetCurrentThreadID(m_threads.front()->GetID());
899 return Status();
900}
901
903 size_t size, size_t &bytes_read) {
904 unsigned char *dst = static_cast<unsigned char *>(buf);
905 struct ptrace_io_desc io;
906
908 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
909
910 bytes_read = 0;
911 io.piod_op = PIOD_READ_D;
912 io.piod_len = size;
913
914 do {
915 io.piod_offs = (void *)(addr + bytes_read);
916 io.piod_addr = dst + bytes_read;
917
919 if (error.Fail() || io.piod_len == 0)
920 return error;
921
922 bytes_read += io.piod_len;
923 io.piod_len = size - bytes_read;
924 } while (bytes_read < size);
925
926 return Status();
927}
928
930 size_t size, size_t &bytes_written) {
931 const unsigned char *src = static_cast<const unsigned char *>(buf);
933 struct ptrace_io_desc io;
934
936 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
937
938 bytes_written = 0;
939 io.piod_op = PIOD_WRITE_D;
940 io.piod_len = size;
941
942 do {
943 io.piod_addr =
944 const_cast<void *>(static_cast<const void *>(src + bytes_written));
945 io.piod_offs = (void *)(addr + bytes_written);
946
948 if (error.Fail() || io.piod_len == 0)
949 return error;
950
951 bytes_written += io.piod_len;
952 io.piod_len = size - bytes_written;
953 } while (bytes_written < size);
954
955 return error;
956}
957
958llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
960 /*
961 * ELF_AUX_ENTRIES is currently restricted to kernel
962 * (<sys/exec_elf.h> r. 1.155 specifies 15)
963 *
964 * ptrace(2) returns the whole AUXV including extra fiels after AT_NULL this
965 * information isn't needed.
966 */
967 size_t auxv_size = 100 * sizeof(AuxInfo);
968
969 ErrorOr<std::unique_ptr<WritableMemoryBuffer>> buf =
970 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
971
972 struct ptrace_io_desc io;
973 io.piod_op = PIOD_READ_AUXV;
974 io.piod_offs = 0;
975 io.piod_addr = static_cast<void *>(buf.get()->getBufferStart());
976 io.piod_len = auxv_size;
977
979
980 if (error.Fail())
981 return std::error_code(error.GetError(), std::generic_category());
982
983 if (io.piod_len < 1)
984 return std::error_code(ECANCELED, std::generic_category());
985
986 return std::move(buf);
987}
988
990 // Enable event reporting
991 ptrace_event_t events;
992 Status status =
993 PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
994 if (status.Fail())
995 return status;
996 // TODO: PTRACE_POSIX_SPAWN?
997 events.pe_set_event |= PTRACE_LWP_CREATE | PTRACE_LWP_EXIT | PTRACE_FORK |
998 PTRACE_VFORK | PTRACE_VFORK_DONE;
999 status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
1000 if (status.Fail())
1001 return status;
1002
1003 return ReinitializeThreads();
1004}
1005
1007 // Clear old threads
1008 m_threads.clear();
1009
1010 // Initialize new thread
1011#ifdef PT_LWPSTATUS
1012 struct ptrace_lwpstatus info = {};
1013 int op = PT_LWPNEXT;
1014#else
1015 struct ptrace_lwpinfo info = {};
1016 int op = PT_LWPINFO;
1017#endif
1018
1019 Status error = PtraceWrapper(op, GetID(), &info, sizeof(info));
1020
1021 if (error.Fail()) {
1022 return error;
1023 }
1024 // Reinitialize from scratch threads and register them in process
1025 while (info.pl_lwpid != 0) {
1026 AddThread(info.pl_lwpid);
1027 error = PtraceWrapper(op, GetID(), &info, sizeof(info));
1028 if (error.Fail()) {
1029 return error;
1030 }
1031 }
1032
1033 return error;
1034}
1035
1036void NativeProcessNetBSD::MonitorClone(::pid_t child_pid, bool is_vfork,
1037 NativeThreadNetBSD &parent_thread) {
1039 LLDB_LOG(log, "clone, child_pid={0}", child_pid);
1040
1041 int status;
1042 ::pid_t wait_pid =
1043 llvm::sys::RetryAfterSignal(-1, ::waitpid, child_pid, &status, 0);
1044 if (wait_pid != child_pid) {
1045 LLDB_LOG(log,
1046 "waiting for pid {0} failed. Assuming the pid has "
1047 "disappeared in the meantime",
1048 child_pid);
1049 return;
1050 }
1051 if (WIFEXITED(status)) {
1052 LLDB_LOG(log,
1053 "waiting for pid {0} returned an 'exited' event. Not "
1054 "tracking it.",
1055 child_pid);
1056 return;
1057 }
1058
1059 ptrace_siginfo_t info;
1060 const auto siginfo_err =
1061 PtraceWrapper(PT_GET_SIGINFO, child_pid, &info, sizeof(info));
1062 if (siginfo_err.Fail()) {
1063 LLDB_LOG(log, "PT_GET_SIGINFO failed {0}", siginfo_err);
1064 return;
1065 }
1066 assert(info.psi_lwpid >= 0);
1067 lldb::tid_t child_tid = info.psi_lwpid;
1068
1069 std::unique_ptr<NativeProcessNetBSD> child_process{
1070 new NativeProcessNetBSD(static_cast<::pid_t>(child_pid), m_terminal_fd,
1072 if (!is_vfork)
1073 child_process->m_software_breakpoints = m_software_breakpoints;
1074
1075 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
1076 if ((m_enabled_extensions & expected_ext) == expected_ext) {
1077 child_process->SetupTrace();
1078 for (const auto &thread : child_process->m_threads)
1079 static_cast<NativeThreadNetBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
1080 child_process->SetState(StateType::eStateStopped, false);
1081
1082 m_delegate.NewSubprocess(this, std::move(child_process));
1083 if (is_vfork)
1084 parent_thread.SetStoppedByVFork(child_pid, child_tid);
1085 else
1086 parent_thread.SetStoppedByFork(child_pid, child_tid);
1088 } else {
1089 child_process->Detach();
1090 Status pt_error =
1091 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 0);
1092 if (pt_error.Fail()) {
1093 LLDB_LOG_ERROR(log, std::move(pt_error.ToError()),
1094 "unable to resume parent process {1}: {0}", GetID());
1096 }
1097 }
1098}
1099
1100llvm::Expected<std::string>
1101NativeProcessNetBSD::SaveCore(llvm::StringRef path_hint) {
1102 llvm::SmallString<128> path{path_hint};
1103 Status error;
1104
1105 // Try with the suggested path first.
1106 if (!path.empty()) {
1107 error = PtraceWrapper(PT_DUMPCORE, GetID(), path.data(), path.size());
1108 if (!error.Fail())
1109 return path.str().str();
1110
1111 // If the request errored, fall back to a generic temporary file.
1112 }
1113
1114 if (std::error_code errc =
1115 llvm::sys::fs::createTemporaryFile("lldb", "core", path))
1116 return llvm::createStringError(errc, "Unable to create a temporary file");
1117
1118 error = PtraceWrapper(PT_DUMPCORE, GetID(), path.data(), path.size());
1119 if (error.Fail())
1120 return error.ToError();
1121 return path.str().str();
1122}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
static Status EnsureFDFlags(int fd, int flags)
static Status EnsureFDFlags(int fd, int flags)
static llvm::Expected< ptrace_siginfo_t > ComputeSignalInfo(const std::vector< std::unique_ptr< NativeThreadProtocol > > &threads, const ResumeActionList &resume_actions)
An architecture specification class.
Definition ArchSpec.h:32
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
const char * GetCString() const
Get the string value as a C string.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
void Clear()
Clears the object state.
Definition FileSpec.cpp:259
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
lldb::pid_t GetProcessId() const
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:177
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
void SetMapped(OptionalBool val)
void SetReadable(OptionalBool val)
void SetExecutable(OptionalBool val)
void SetName(const char *name)
void SetWritable(OptionalBool val)
Abstract class that extends NativeProcessProtocol with ELF specific logic.
void NotifyDidExec() override
Notify the delegate that an exec occurred.
Status SetSoftwareBreakpoint(lldb::addr_t addr, uint32_t size_hint)
void SetState(lldb::StateType state, bool notify_delegates=true)
std::vector< std::unique_ptr< NativeThreadProtocol > > m_threads
virtual bool SetExitStatus(WaitStatus status, bool bNotifyStateChange)
void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread)
Extension
Extension flag constants, returned by Manager::GetSupportedExtensions() and passed to SetEnabledExten...
std::unordered_map< lldb::addr_t, SoftwareBreakpoint > m_software_breakpoints
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
const ResumeAction * GetActionForThread(lldb::tid_t tid, bool default_ok) const
Definition Debug.h:74
An error handling class.
Definition Status.h:118
static Status FromErrno()
Set the current error to errno.
Definition Status.cpp:299
llvm::Error ToError() const
FIXME: Replace all uses with takeError() instead.
Definition Status.cpp:138
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
bool Success() const
Test for success condition.
Definition Status.cpp:303
llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Attach(lldb::pid_t pid, NativeDelegate &native_delegate) override
Attach to an existing process.
Extension GetSupportedExtensions() const override
Get the bitmask of extensions supported by this process plugin.
llvm::Expected< std::unique_ptr< NativeProcessProtocol > > Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate) override
Launch a process for debugging.
llvm::Expected< std::string > SaveCore(llvm::StringRef path_hint) override
Write a core dump (without crashing the program).
void MonitorClone(::pid_t child_pid, bool is_vfork, NativeThreadNetBSD &parent_thread)
Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override
Status Interrupt() override
Tells a process to interrupt all operations as if by a Ctrl-C.
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) override
Status GetLoadedModuleFileSpec(const char *module_path, FileSpec &file_spec) override
Status GetFileLoadAddress(const llvm::StringRef &file_name, lldb::addr_t &load_addr) override
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > GetAuxvData() const override
Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override
std::vector< std::pair< MemoryRegionInfo, FileSpec > > m_mem_region_cache
Status Resume(const ResumeActionList &resume_actions) override
NativeProcessNetBSD(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, MainLoop &mainloop)
void MonitorExited(lldb::pid_t pid, WaitStatus status)
NativeThreadNetBSD & AddThread(lldb::tid_t thread_id)
Status SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, int data=0, int *result=nullptr)
Status Signal(int signo) override
Sends a process a UNIX signal signal.
void SetStoppedByFork(lldb::pid_t child_pid, lldb::tid_t child_tid)
void SetStoppedBySignal(uint32_t signo, const siginfo_t *info=nullptr)
void SetStoppedByVFork(lldb::pid_t child_pid, lldb::tid_t child_tid)
llvm::Error CopyWatchpointsFrom(NativeThreadNetBSD &source)
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_INDEX32
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_PROCESS_ID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
MainLoopPosix MainLoop
Definition MainLoop.h:20
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateLaunching
Process is in the process of launching.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
@ eErrorTypePOSIX
POSIX error codes.
uint64_t pid_t
Definition lldb-types.h:83
uint64_t addr_t
Definition lldb-types.h:80
uint64_t tid_t
Definition lldb-types.h:84
bool Contains(BaseType r) const
Definition RangeMap.h:93
BaseType GetRangeBase() const
Definition RangeMap.h:45
void SetRangeEnd(BaseType end)
Definition RangeMap.h:80
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
void SetByteSize(SizeType s)
Definition RangeMap.h:89
lldb::StateType state
Definition Debug.h:23
static WaitStatus Decode(int wstatus)
#define SIGSTOP
#define O_NONBLOCK
#define SIGTRAP
#define SIGKILL