LLDB mainline
NativeProcessFreeBSD.cpp
Go to the documentation of this file.
1//===-- NativeProcessFreeBSD.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
11// clang-format off
12#include <sys/types.h>
13#include <sys/ptrace.h>
14#include <sys/sysctl.h>
15#include <sys/user.h>
16#include <sys/wait.h>
17#include <machine/elf.h>
18// clang-format on
19
23#include "lldb/Target/Process.h"
24#include "lldb/Utility/State.h"
25#include "llvm/Support/Errno.h"
26
27using namespace lldb;
28using namespace lldb_private;
29using namespace lldb_private::process_freebsd;
30using namespace llvm;
31
32// Simple helper function to ensure flags are enabled on the given file
33// descriptor.
34static Status EnsureFDFlags(int fd, int flags) {
36
37 int status = fcntl(fd, F_GETFL);
38 if (status == -1) {
40 return error;
41 }
42
43 if (fcntl(fd, F_SETFL, status | flags) == -1) {
45 return error;
46 }
47
48 return error;
49}
50
51static Status CanTrace() {
52 int proc_debug, ret;
53 size_t len = sizeof(proc_debug);
54 ret = ::sysctlbyname("security.bsd.unprivileged_proc_debug", &proc_debug,
55 &len, nullptr, 0);
56 if (ret != 0)
58 "sysctlbyname() security.bsd.unprivileged_proc_debug failed");
59
60 if (proc_debug < 1)
62 "process debug disabled by security.bsd.unprivileged_proc_debug oid");
63
64 return {};
65}
66
67// Public Static Methods
68
69llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
71 NativeDelegate &native_delegate) {
73 Status status;
74
76 .LaunchProcess(launch_info, status)
77 .GetProcessId();
78 LLDB_LOG(log, "pid = {0:x}", pid);
79 if (status.Fail()) {
80 LLDB_LOG(log, "failed to launch process: {0}", status);
81 auto error = CanTrace();
82 if (error.Fail())
83 return error.ToError();
84 return status.ToError();
85 }
86
87 // Wait for the child process to trap on its call to execve.
88 int wstatus;
89 ::pid_t wpid = llvm::sys::RetryAfterSignal(-1, ::waitpid, pid, &wstatus, 0);
90 assert(wpid == pid);
92 if (!WIFSTOPPED(wstatus)) {
93 LLDB_LOG(log, "Could not sync with inferior process: wstatus={1}",
94 WaitStatus::Decode(wstatus));
95 return llvm::createStringError("Could not sync with inferior process");
96 }
97 LLDB_LOG(log, "inferior started, now in stopped state");
98
100 if (!Host::GetProcessInfo(pid, Info)) {
101 return llvm::createStringError("Cannot get process architecture");
102 }
103
104 // Set the architecture to the exe architecture.
105 LLDB_LOG(log, "pid = {0:x}, detected architecture {1}", pid,
106 Info.GetArchitecture().GetArchitectureName());
107
108 std::unique_ptr<NativeProcessFreeBSD> process_up(new NativeProcessFreeBSD(
109 pid, launch_info.GetPTY().ReleasePrimaryFileDescriptor(), native_delegate,
110 Info.GetArchitecture(), m_mainloop));
111
112 status = process_up->SetupTrace();
113 if (status.Fail())
114 return status.ToError();
115
116 for (const auto &thread : process_up->m_threads)
117 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
118 process_up->SetState(StateType::eStateStopped, false);
119
120 return std::move(process_up);
121}
122
123llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
127 LLDB_LOG(log, "pid = {0:x}", pid);
128
129 // Retrieve the architecture for the running process.
131 if (!Host::GetProcessInfo(pid, Info)) {
132 return llvm::createStringError("Cannot get process architecture");
133 }
134
135 std::unique_ptr<NativeProcessFreeBSD> process_up(new NativeProcessFreeBSD(
136 pid, -1, native_delegate, Info.GetArchitecture(), m_mainloop));
137
138 Status status = process_up->Attach();
139 if (!status.Success())
140 return status.ToError();
141
142 return std::move(process_up);
143}
144
155
156// Public Instance Methods
157
159 NativeDelegate &delegate,
160 const ArchSpec &arch,
161 MainLoop &mainloop)
162 : NativeProcessELF(pid, terminal_fd, delegate), m_arch(arch),
163 m_main_loop(mainloop) {
164 if (m_terminal_fd != -1) {
166 assert(status.Success());
167 }
168
169 Status status;
171 SIGCHLD, [this](MainLoopBase &) { SigchldHandler(); }, status);
172 assert(m_sigchld_handle && status.Success());
173}
174
175// Handles all waitpid events from the inferior process.
177 switch (signal) {
178 case SIGTRAP:
179 return MonitorSIGTRAP(pid);
180 case SIGSTOP:
181 return MonitorSIGSTOP(pid);
182 default:
183 return MonitorSignal(pid, signal);
184 }
185}
186
189
190 LLDB_LOG(log, "got exit signal({0}) , pid = {1}", status, pid);
191
192 /* Stop Tracking All Threads attached to Process */
193 m_threads.clear();
194
195 SetExitStatus(status, true);
196
197 // Notify delegate that our process has exited.
199}
200
202 /* Stop all Threads attached to Process */
203 for (const auto &thread : m_threads) {
204 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP,
205 nullptr);
206 }
208}
209
212 struct ptrace_lwpinfo info;
213
214 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info));
215 if (siginfo_err.Fail()) {
216 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
217 return;
218 }
219 assert(info.pl_event == PL_EVENT_SIGNAL);
220
221 LLDB_LOG(log, "got SIGTRAP, pid = {0}, lwpid = {1}, flags = {2:x}", pid,
222 info.pl_lwpid, info.pl_flags);
223 NativeThreadFreeBSD *thread = nullptr;
224
225 if (info.pl_flags & (PL_FLAG_BORN | PL_FLAG_EXITED)) {
226 if (info.pl_flags & PL_FLAG_BORN) {
227 LLDB_LOG(log, "monitoring new thread, tid = {0}", info.pl_lwpid);
228 NativeThreadFreeBSD &t = AddThread(info.pl_lwpid);
229
230 // Technically, the FreeBSD kernel copies the debug registers to new
231 // threads. However, there is a non-negligible delay between acquiring
232 // the DR values and reporting the new thread during which the user may
233 // establish a new watchpoint. In order to ensure that watchpoints
234 // established during this period are propagated to new threads,
235 // explicitly copy the DR value at the time the new thread is reported.
236 //
237 // See also: https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=250954
238
239 llvm::Error error = t.CopyWatchpointsFrom(
240 static_cast<NativeThreadFreeBSD &>(*GetCurrentThread()));
241 if (error) {
242 LLDB_LOG_ERROR(log, std::move(error),
243 "failed to copy watchpoints to new thread {1}: {0}",
244 info.pl_lwpid);
246 return;
247 }
248 } else /*if (info.pl_flags & PL_FLAG_EXITED)*/ {
249 LLDB_LOG(log, "thread exited, tid = {0}", info.pl_lwpid);
250 RemoveThread(info.pl_lwpid);
251 }
252
253 Status error =
254 PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
255 if (error.Fail())
257 return;
258 }
259
260 if (info.pl_flags & PL_FLAG_EXEC) {
262 if (error.Fail()) {
264 return;
265 }
266
267 // Let our delegate know we have just exec'd.
269
270 for (const auto &thread : m_threads)
271 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedByExec();
272 SetCurrentThreadID(m_threads.front()->GetID());
274 return;
275 }
276
277 if (info.pl_lwpid > 0) {
278 for (const auto &t : m_threads) {
279 if (t->GetID() == static_cast<lldb::tid_t>(info.pl_lwpid))
280 thread = static_cast<NativeThreadFreeBSD *>(t.get());
281 static_cast<NativeThreadFreeBSD *>(t.get())->SetStoppedWithNoReason();
282 }
283 if (!thread)
284 LLDB_LOG(log, "thread not found in m_threads, pid = {0}, LWP = {1}", pid,
285 info.pl_lwpid);
286 }
287
288 if (info.pl_flags & PL_FLAG_FORKED) {
289 assert(thread);
290 MonitorClone(info.pl_child_pid, info.pl_flags & PL_FLAG_VFORKED, *thread);
291 return;
292 }
293
294 if (info.pl_flags & PL_FLAG_VFORK_DONE) {
295 assert(thread);
297 thread->SetStoppedByVForkDone();
299 } else {
300 Status error =
301 PtraceWrapper(PT_CONTINUE, pid, reinterpret_cast<void *>(1), 0);
302 if (error.Fail())
304 }
305 return;
306 }
307
308 if (info.pl_flags & PL_FLAG_SI) {
309 assert(info.pl_siginfo.si_signo == SIGTRAP);
310 LLDB_LOG(log, "SIGTRAP siginfo: si_code = {0}, pid = {1}",
311 info.pl_siginfo.si_code, info.pl_siginfo.si_pid);
312
313 switch (info.pl_siginfo.si_code) {
314 case TRAP_BRKPT:
315 LLDB_LOG(log, "SIGTRAP/TRAP_BRKPT: si_addr: {0}",
316 info.pl_siginfo.si_addr);
317
318 if (thread) {
319 auto &regctx = static_cast<NativeRegisterContextFreeBSD &>(
320 thread->GetRegisterContext());
321 auto thread_info =
322 m_threads_stepping_with_breakpoint.find(thread->GetID());
323 if (thread_info != m_threads_stepping_with_breakpoint.end() &&
324 llvm::is_contained(thread_info->second, regctx.GetPC())) {
325 thread->SetStoppedByTrace();
326 for (auto &&bp_addr : thread_info->second) {
327 Status brkpt_error = RemoveBreakpoint(bp_addr);
328 if (brkpt_error.Fail())
329 LLDB_LOG(log, "pid = {0} remove stepping breakpoint: {1}",
330 thread_info->first, brkpt_error);
331 }
332 m_threads_stepping_with_breakpoint.erase(thread_info);
333 } else
334 thread->SetStoppedByBreakpoint();
336 SetCurrentThreadID(thread->GetID());
337 }
339 return;
340 case TRAP_TRACE:
341 LLDB_LOG(log, "SIGTRAP/TRAP_TRACE: si_addr: {0}",
342 info.pl_siginfo.si_addr);
343
344 if (thread) {
345 auto &regctx = static_cast<NativeRegisterContextFreeBSD &>(
346 thread->GetRegisterContext());
347 uint32_t wp_index = LLDB_INVALID_INDEX32;
348 Status error = regctx.GetWatchpointHitIndex(
349 wp_index, reinterpret_cast<uintptr_t>(info.pl_siginfo.si_addr));
350 if (error.Fail())
351 LLDB_LOG(log,
352 "received error while checking for watchpoint hits, pid = "
353 "{0}, LWP = {1}, error = {2}",
354 pid, info.pl_lwpid, error);
355 if (wp_index != LLDB_INVALID_INDEX32) {
356 regctx.ClearWatchpointHit(wp_index);
357 thread->SetStoppedByWatchpoint(wp_index);
358 SetCurrentThreadID(thread->GetID());
360 break;
361 }
362
363 thread->SetStoppedByTrace();
364 SetCurrentThreadID(thread->GetID());
365 }
366
368 return;
369 }
370 }
371
372 // Either user-generated SIGTRAP or an unknown event that would
373 // otherwise leave the debugger hanging.
374 LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
376}
377
380 struct ptrace_lwpinfo info;
381
382 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info));
383 if (siginfo_err.Fail()) {
384 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
385 return;
386 }
387 assert(info.pl_event == PL_EVENT_SIGNAL);
388 // TODO: do we need to handle !PL_FLAG_SI?
389 assert(info.pl_flags & PL_FLAG_SI);
390 assert(info.pl_siginfo.si_signo == signal);
391
392 for (const auto &abs_thread : m_threads) {
393 NativeThreadFreeBSD &thread =
394 static_cast<NativeThreadFreeBSD &>(*abs_thread);
395 assert(info.pl_lwpid >= 0);
396 if (info.pl_lwpid == 0 ||
397 static_cast<lldb::tid_t>(info.pl_lwpid) == thread.GetID()) {
398 thread.SetStoppedBySignal(info.pl_siginfo.si_signo, &info.pl_siginfo);
399 SetCurrentThreadID(thread.GetID());
400 } else
401 thread.SetStoppedWithNoReason();
402 }
404}
405
407 int data, int *result) {
410 int ret;
411
412 errno = 0;
413 ret =
414 ptrace(req, static_cast<::pid_t>(pid), static_cast<caddr_t>(addr), data);
415
416 if (ret == -1) {
417 error = CanTrace();
418 if (error.Success())
420 }
421
422 if (result)
423 *result = ret;
424
425 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
426
427 if (error.Fail())
428 LLDB_LOG(log, "ptrace() failed: {0}", error);
429
430 return error;
431}
432
433llvm::Expected<llvm::ArrayRef<uint8_t>>
435 static const uint8_t g_arm_opcode[] = {0xfe, 0xde, 0xff, 0xe7};
436 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
437
438 switch (GetArchitecture().GetMachine()) {
439 case llvm::Triple::arm:
440 switch (size_hint) {
441 case 2:
442 return llvm::ArrayRef(g_thumb_opcode);
443 case 4:
444 return llvm::ArrayRef(g_arm_opcode);
445 default:
446 return llvm::createStringError(llvm::inconvertibleErrorCode(),
447 "Unrecognised trap opcode size hint!");
448 }
449 default:
451 }
452}
453
456 LLDB_LOG(log, "pid {0}", GetID());
457
458 Status ret;
459
460 int signal = 0;
461 for (const auto &abs_thread : m_threads) {
462 assert(abs_thread && "thread list should not contain NULL threads");
463 NativeThreadFreeBSD &thread =
464 static_cast<NativeThreadFreeBSD &>(*abs_thread);
465
466 const ResumeAction *action =
467 resume_actions.GetActionForThread(thread.GetID(), true);
468 // we need to explicit issue suspend requests, so it is simpler to map it
469 // into proper action
470 ResumeAction suspend_action{thread.GetID(), eStateSuspended,
472
473 if (action == nullptr) {
474 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
475 thread.GetID());
476 action = &suspend_action;
477 }
478
479 LLDB_LOG(
480 log,
481 "processing resume action state {0} signal {1} for pid {2} tid {3}",
482 action->state, action->signal, GetID(), thread.GetID());
483
484 switch (action->state) {
485 case eStateRunning:
486 ret = thread.Resume();
487 break;
488 case eStateStepping:
489 ret = thread.SingleStep();
490 break;
491 case eStateSuspended:
492 case eStateStopped:
493 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
495 "Passing signal to suspended thread unsupported");
496
497 ret = thread.Suspend();
498 break;
499
500 default:
502 "NativeProcessFreeBSD::%s (): unexpected state %s specified "
503 "for pid %" PRIu64 ", tid %" PRIu64,
504 __FUNCTION__, StateAsCString(action->state), GetID(), thread.GetID());
505 }
506
507 if (!ret.Success())
508 return ret;
509 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
510 signal = action->signal;
511 }
512
513 ret =
514 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
515 if (ret.Success())
516 SetState(eStateRunning, true);
517 return ret;
518}
519
522
523 // Do not try to stop a process that's already stopped, this may cause
524 // the SIGSTOP to get queued and stop the process again once resumed.
525 if (StateIsStoppedState(m_state, false))
526 return error;
527 if (kill(GetID(), SIGSTOP) != 0)
529 return error;
530}
531
534
535 // Stop monitoring the inferior.
536 m_sigchld_handle.reset();
537
538 // Tell ptrace to detach from the process.
540 return error;
541
542 return PtraceWrapper(PT_DETACH, GetID());
543}
544
547
548 if (kill(GetID(), signo))
550
551 return error;
552}
553
555
558 LLDB_LOG(log, "pid {0}", GetID());
559
561
562 switch (m_state) {
568 // Nothing to do - the process is already dead.
569 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
571 return error;
572
580 // We can try to kill a process in these states.
581 break;
582 }
583
584 return PtraceWrapper(PT_KILL, m_pid);
585}
586
588 MemoryRegionInfo &range_info) {
589
591 // We're done.
592 return Status::FromErrorString("unsupported");
593 }
594
596 if (error.Fail()) {
597 return error;
598 }
599
600 lldb::addr_t prev_base_address = 0;
601 // FIXME start by finding the last region that is <= target address using
602 // binary search. Data is sorted.
603 // There can be a ton of regions on pthreads apps with lots of threads.
604 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
605 ++it) {
606 MemoryRegionInfo &proc_entry_info = it->first;
607 // Sanity check assumption that memory map entries are ascending.
608 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
609 "descending memory map entries detected, unexpected");
610 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
611 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
612 // If the target address comes before this entry, indicate distance to next
613 // region.
614 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
615 range_info.GetRange().SetRangeBase(load_addr);
616 range_info.GetRange().SetByteSize(
617 proc_entry_info.GetRange().GetRangeBase() - load_addr);
622 return error;
623 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
624 // The target address is within the memory region we're processing here.
625 range_info = proc_entry_info;
626 return error;
627 }
628 // The target memory address comes somewhere after the region we just
629 // parsed.
630 }
631 // If we made it here, we didn't find an entry that contained the given
632 // address. Return the load_addr as start and the amount of bytes betwwen
633 // load address and the end of the memory as size.
634 range_info.GetRange().SetRangeBase(load_addr);
640 return error;
641}
642
645 // If our cache is empty, pull the latest. There should always be at least
646 // one memory region if memory region handling is supported.
647 if (!m_mem_region_cache.empty()) {
648 LLDB_LOG(log, "reusing {0} cached memory region entries",
649 m_mem_region_cache.size());
650 return Status();
651 }
652
653 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, static_cast<int>(m_pid)};
654 int ret;
655 size_t len;
656
657 ret = ::sysctl(mib, 4, nullptr, &len, nullptr, 0);
658 if (ret != 0) {
660 return Status::FromErrorString("sysctl() for KERN_PROC_VMMAP failed");
661 }
662
663 std::unique_ptr<WritableMemoryBuffer> buf =
664 llvm::WritableMemoryBuffer::getNewMemBuffer(len);
665 ret = ::sysctl(mib, 4, buf->getBufferStart(), &len, nullptr, 0);
666 if (ret != 0) {
668 return Status::FromErrorString("sysctl() for KERN_PROC_VMMAP failed");
669 }
670
671 char *bp = buf->getBufferStart();
672 char *end = bp + len;
673 while (bp < end) {
674 auto *kv = reinterpret_cast<struct kinfo_vmentry *>(bp);
675 if (kv->kve_structsize == 0)
676 break;
677 bp += kv->kve_structsize;
678
679 MemoryRegionInfo info;
680 info.Clear();
681 info.GetRange().SetRangeBase(kv->kve_start);
682 info.GetRange().SetRangeEnd(kv->kve_end);
684
685 if (kv->kve_protection & VM_PROT_READ)
687 else
689
690 if (kv->kve_protection & VM_PROT_WRITE)
692 else
694
695 if (kv->kve_protection & VM_PROT_EXECUTE)
697 else
699
700 if (kv->kve_path[0])
701 info.SetName(kv->kve_path);
702
703 m_mem_region_cache.emplace_back(info,
704 FileSpec(info.GetName().GetCString()));
705 }
706
707 if (m_mem_region_cache.empty()) {
708 // No entries after attempting to read them. This shouldn't happen. Assume
709 // we don't support map entries.
710 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
711 "for memory region metadata retrieval");
713 return Status::FromErrorString("not supported");
714 }
715 LLDB_LOG(log, "read {0} memory region entries from process {1}",
716 m_mem_region_cache.size(), GetID());
717 // We support memory retrieval, remember that.
719
720 return Status();
721}
722
724
726 bool hardware) {
727 if (hardware)
728 return SetHardwareBreakpoint(addr, size);
729 return SetSoftwareBreakpoint(addr, size);
730}
731
733 FileSpec &file_spec) {
735 if (error.Fail()) {
736 auto status = CanTrace();
737 if (status.Fail())
738 return status;
739 return error;
740 }
741
742 FileSpec module_file_spec(module_path);
743 FileSystem::Instance().Resolve(module_file_spec);
744
745 file_spec.Clear();
746 for (const auto &it : m_mem_region_cache) {
747 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
748 file_spec = it.second;
749 return Status();
750 }
751 }
753 "Module file (%s) not found in process' memory map!",
754 module_file_spec.GetFilename().AsCString());
755}
756
757Status
758NativeProcessFreeBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
759 lldb::addr_t &load_addr) {
760 load_addr = LLDB_INVALID_ADDRESS;
762 if (error.Fail()) {
763 auto status = CanTrace();
764 if (status.Fail())
765 return status;
766 return error;
767 }
768
769 FileSpec file(file_name);
770 for (const auto &it : m_mem_region_cache) {
771 if (it.second == file) {
772 load_addr = it.first.GetRange().GetRangeBase();
773 return Status();
774 }
775 }
776 return Status::FromErrorStringWithFormat("No load address found for file %s.",
777 file_name.str().c_str());
778}
779
782 int status;
783 ::pid_t wait_pid =
784 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WNOHANG);
785
786 if (wait_pid == 0)
787 return;
788
789 if (wait_pid == -1) {
791 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
792 return;
793 }
794
795 WaitStatus wait_status = WaitStatus::Decode(status);
796 bool exited = wait_status.type == WaitStatus::Exit ||
797 (wait_status.type == WaitStatus::Signal &&
798 wait_pid == static_cast<::pid_t>(GetID()));
799
800 LLDB_LOG(log,
801 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
802 GetID(), wait_pid, status, exited);
803
804 if (exited)
805 MonitorExited(wait_pid, wait_status);
806 else {
807 assert(wait_status.type == WaitStatus::Stop);
808 MonitorCallback(wait_pid, wait_status.status);
809 }
810}
811
813 for (const auto &thread : m_threads) {
814 assert(thread && "thread list should not contain NULL threads");
815 if (thread->GetID() == thread_id) {
816 // We have this thread.
817 return true;
818 }
819 }
820
821 // We don't have this thread.
822 return false;
823}
824
827 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
828
829 assert(thread_id > 0);
830 assert(!HasThreadNoLock(thread_id) &&
831 "attempted to add a thread by id that already exists");
832
833 // If this is the first thread, save it as the current thread
834 if (m_threads.empty())
835 SetCurrentThreadID(thread_id);
836
837 m_threads.push_back(std::make_unique<NativeThreadFreeBSD>(*this, thread_id));
838 return static_cast<NativeThreadFreeBSD &>(*m_threads.back());
839}
840
843 LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
844
845 assert(thread_id > 0);
846 assert(HasThreadNoLock(thread_id) &&
847 "attempted to remove a thread that does not exist");
848
849 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
850 if ((*it)->GetID() == thread_id) {
851 m_threads.erase(it);
852 break;
853 }
854 }
855
856 if (GetCurrentThreadID() == thread_id)
857 SetCurrentThreadID(m_threads.front()->GetID());
858}
859
861 // Attach to the requested process.
862 // An attach will cause the thread to stop with a SIGSTOP.
863 Status status = PtraceWrapper(PT_ATTACH, m_pid);
864 if (status.Fail())
865 return status;
866
867 int wstatus;
868 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
869 // point we should have a thread stopped if waitpid succeeds.
870 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr, 0)) <
871 0)
872 return Status(errno, eErrorTypePOSIX);
873
874 // Initialize threads and tracing status
875 // NB: this needs to be called before we set thread state
876 status = SetupTrace();
877 if (status.Fail())
878 return status;
879
880 for (const auto &thread : m_threads)
881 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
882
883 // Let our process instance know the thread has stopped.
884 SetCurrentThreadID(m_threads.front()->GetID());
886 return Status();
887}
888
890 size_t size, size_t &bytes_read) {
891 unsigned char *dst = static_cast<unsigned char *>(buf);
892 struct ptrace_io_desc io;
893
895 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
896
897 bytes_read = 0;
898 io.piod_op = PIOD_READ_D;
899 io.piod_len = size;
900
901 do {
902 io.piod_offs = (void *)(addr + bytes_read);
903 io.piod_addr = dst + bytes_read;
904
906 if (error.Fail() || io.piod_len == 0)
907 return error;
908
909 bytes_read += io.piod_len;
910 io.piod_len = size - bytes_read;
911 } while (bytes_read < size);
912
913 return Status();
914}
915
917 size_t size, size_t &bytes_written) {
918 const unsigned char *src = static_cast<const unsigned char *>(buf);
920 struct ptrace_io_desc io;
921
923 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
924
925 bytes_written = 0;
926 io.piod_op = PIOD_WRITE_D;
927 io.piod_len = size;
928
929 do {
930 io.piod_addr =
931 const_cast<void *>(static_cast<const void *>(src + bytes_written));
932 io.piod_offs = (void *)(addr + bytes_written);
933
935 if (error.Fail() || io.piod_len == 0)
936 return error;
937
938 bytes_written += io.piod_len;
939 io.piod_len = size - bytes_written;
940 } while (bytes_written < size);
941
942 return error;
943}
944
945llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
947 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, static_cast<int>(GetID())};
948 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
949 std::unique_ptr<WritableMemoryBuffer> buf =
950 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
951
952 if (::sysctl(mib, 4, buf->getBufferStart(), &auxv_size, nullptr, 0) != 0)
953 return std::error_code(errno, std::generic_category());
954
955 return buf;
956}
957
959 // Enable event reporting
960 int events;
961 Status status =
962 PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
963 if (status.Fail())
964 return status;
965 events |= PTRACE_LWP | PTRACE_FORK | PTRACE_VFORK;
966 status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
967 if (status.Fail())
968 return status;
969
970 return ReinitializeThreads();
971}
972
974 // Clear old threads
975 m_threads.clear();
976
977 int num_lwps;
978 Status error = PtraceWrapper(PT_GETNUMLWPS, GetID(), nullptr, 0, &num_lwps);
979 if (error.Fail())
980 return error;
981
982 std::vector<lwpid_t> lwp_ids;
983 lwp_ids.resize(num_lwps);
984 error = PtraceWrapper(PT_GETLWPLIST, GetID(), lwp_ids.data(),
985 lwp_ids.size() * sizeof(lwpid_t), &num_lwps);
986 if (error.Fail())
987 return error;
988
989 // Reinitialize from scratch threads and register them in process
990 for (lwpid_t lwp : lwp_ids)
991 AddThread(lwp);
992
993 return error;
994}
995
996void NativeProcessFreeBSD::MonitorClone(::pid_t child_pid, bool is_vfork,
997 NativeThreadFreeBSD &parent_thread) {
999 LLDB_LOG(log, "fork, child_pid={0}", child_pid);
1000
1001 int status;
1002 ::pid_t wait_pid =
1003 llvm::sys::RetryAfterSignal(-1, ::waitpid, child_pid, &status, 0);
1004 if (wait_pid != child_pid) {
1005 LLDB_LOG(log,
1006 "waiting for pid {0} failed. Assuming the pid has "
1007 "disappeared in the meantime",
1008 child_pid);
1009 return;
1010 }
1011 if (WIFEXITED(status)) {
1012 LLDB_LOG(log,
1013 "waiting for pid {0} returned an 'exited' event. Not "
1014 "tracking it.",
1015 child_pid);
1016 return;
1017 }
1018
1019 struct ptrace_lwpinfo info;
1020 const auto siginfo_err =
1021 PtraceWrapper(PT_LWPINFO, child_pid, &info, sizeof(info));
1022 if (siginfo_err.Fail()) {
1023 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
1024 return;
1025 }
1026 assert(info.pl_event == PL_EVENT_SIGNAL);
1027 lldb::tid_t child_tid = info.pl_lwpid;
1028
1029 std::unique_ptr<NativeProcessFreeBSD> child_process{
1030 new NativeProcessFreeBSD(static_cast<::pid_t>(child_pid), m_terminal_fd,
1032 if (!is_vfork)
1033 child_process->m_software_breakpoints = m_software_breakpoints;
1034
1035 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
1036 if ((m_enabled_extensions & expected_ext) == expected_ext) {
1037 child_process->SetupTrace();
1038 for (const auto &thread : child_process->m_threads)
1039 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
1040 child_process->SetState(StateType::eStateStopped, false);
1041
1042 m_delegate.NewSubprocess(this, std::move(child_process));
1043 if (is_vfork)
1044 parent_thread.SetStoppedByVFork(child_pid, child_tid);
1045 else
1046 parent_thread.SetStoppedByFork(child_pid, child_tid);
1048 } else {
1049 child_process->Detach();
1050 Status pt_error =
1051 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 0);
1052 if (pt_error.Fail()) {
1053 LLDB_LOG_ERROR(log, pt_error.ToError(),
1054 "unable to resume parent process {1}: {0}", GetID());
1056 }
1057 }
1058}
1059
1060llvm::Expected<std::string>
1061NativeProcessFreeBSD::SaveCore(llvm::StringRef path_hint) {
1062#if defined(PT_COREDUMP)
1063 using namespace llvm::sys::fs;
1064
1065 llvm::SmallString<128> path{path_hint};
1066 Status error;
1067 struct ptrace_coredump pc = {};
1068
1069 // Try with the suggested path first. If there is no suggested path or it
1070 // failed to open, use a temporary file.
1071 if (path.empty() ||
1072 openFile(path, pc.pc_fd, CD_CreateNew, FA_Write, OF_None)) {
1073 if (std::error_code errc =
1074 createTemporaryFile("lldb", "core", pc.pc_fd, path))
1075 return llvm::createStringError(errc, "Unable to create a temporary file");
1076 }
1077 error = PtraceWrapper(PT_COREDUMP, GetID(), &pc, sizeof(pc));
1078
1079 std::error_code close_err = closeFile(pc.pc_fd);
1080 if (error.Fail())
1081 return error.ToError();
1082 if (close_err)
1083 return llvm::createStringError(
1084 close_err, "Unable to close the core dump after writing");
1085 return path.str().str();
1086#else // !defined(PT_COREDUMP)
1087 return llvm::createStringError(
1088 llvm::inconvertibleErrorCode(),
1089 "PT_COREDUMP not supported in the FreeBSD version used to build LLDB");
1090#endif
1091}
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 CanTrace()
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)
virtual Status RemoveBreakpoint(lldb::addr_t addr, bool hardware=false)
void FixupBreakpointPCAsNeeded(NativeThreadProtocol &thread)
Extension
Extension flag constants, returned by Manager::GetSupportedExtensions() and passed to SetEnabledExten...
virtual Status SetHardwareBreakpoint(lldb::addr_t addr, size_t size)
virtual llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint)
std::unordered_map< lldb::addr_t, SoftwareBreakpoint > m_software_breakpoints
std::map< lldb::tid_t, std::vector< lldb::addr_t > > m_threads_stepping_with_breakpoint
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 > > Launch(ProcessLaunchInfo &launch_info, NativeDelegate &native_delegate) override
Launch a process for debugging.
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.
NativeThreadFreeBSD & AddThread(lldb::tid_t thread_id)
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info) override
Status Resume(const ResumeActionList &resume_actions) override
llvm::Expected< std::string > SaveCore(llvm::StringRef path_hint) override
Write a core dump (without crashing the program).
Status GetFileLoadAddress(const llvm::StringRef &file_name, lldb::addr_t &load_addr) override
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > GetAuxvData() const override
void MonitorClone(::pid_t child_pid, bool is_vfork, NativeThreadFreeBSD &parent_thread)
static Status PtraceWrapper(int req, lldb::pid_t pid, void *addr=nullptr, int data=0, int *result=nullptr)
Status Interrupt() override
Tells a process to interrupt all operations as if by a Ctrl-C.
Status Signal(int signo) override
Sends a process a UNIX signal signal.
Status ReadMemory(lldb::addr_t addr, void *buf, size_t size, size_t &bytes_read) override
Status GetLoadedModuleFileSpec(const char *module_path, FileSpec &file_spec) override
llvm::Expected< llvm::ArrayRef< uint8_t > > GetSoftwareBreakpointTrapOpcode(size_t size_hint) override
void MonitorExited(lldb::pid_t pid, WaitStatus status)
NativeProcessFreeBSD(::pid_t pid, int terminal_fd, NativeDelegate &delegate, const ArchSpec &arch, MainLoop &mainloop)
std::vector< std::pair< MemoryRegionInfo, FileSpec > > m_mem_region_cache
Status WriteMemory(lldb::addr_t addr, const void *buf, size_t size, size_t &bytes_written) override
Status SetBreakpoint(lldb::addr_t addr, uint32_t size, bool hardware) override
llvm::Error CopyWatchpointsFrom(NativeThreadFreeBSD &source)
void SetStoppedByVFork(lldb::pid_t child_pid, lldb::tid_t child_tid)
void SetStoppedByFork(lldb::pid_t child_pid, lldb::tid_t child_tid)
void SetStoppedBySignal(uint32_t signo, const siginfo_t *info=nullptr)
#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
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
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