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 thread->SetStoppedByBreakpoint();
321 SetCurrentThreadID(thread->GetID());
322 }
324 return;
325 case TRAP_TRACE:
326 LLDB_LOG(log, "SIGTRAP/TRAP_TRACE: si_addr: {0}",
327 info.pl_siginfo.si_addr);
328
329 if (thread) {
330 auto &regctx = static_cast<NativeRegisterContextFreeBSD &>(
331 thread->GetRegisterContext());
332 uint32_t wp_index = LLDB_INVALID_INDEX32;
333 Status error = regctx.GetWatchpointHitIndex(
334 wp_index, reinterpret_cast<uintptr_t>(info.pl_siginfo.si_addr));
335 if (error.Fail())
336 LLDB_LOG(log,
337 "received error while checking for watchpoint hits, pid = "
338 "{0}, LWP = {1}, error = {2}",
339 pid, info.pl_lwpid, error);
340 if (wp_index != LLDB_INVALID_INDEX32) {
341 regctx.ClearWatchpointHit(wp_index);
342 thread->SetStoppedByWatchpoint(wp_index);
343 SetCurrentThreadID(thread->GetID());
345 break;
346 }
347
348 thread->SetStoppedByTrace();
349 SetCurrentThreadID(thread->GetID());
350 }
351
353 return;
354 }
355 }
356
357 // Either user-generated SIGTRAP or an unknown event that would
358 // otherwise leave the debugger hanging.
359 LLDB_LOG(log, "unknown SIGTRAP, passing to generic handler");
361}
362
365 struct ptrace_lwpinfo info;
366
367 const auto siginfo_err = PtraceWrapper(PT_LWPINFO, pid, &info, sizeof(info));
368 if (siginfo_err.Fail()) {
369 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
370 return;
371 }
372 assert(info.pl_event == PL_EVENT_SIGNAL);
373 // TODO: do we need to handle !PL_FLAG_SI?
374 assert(info.pl_flags & PL_FLAG_SI);
375 assert(info.pl_siginfo.si_signo == signal);
376
377 for (const auto &abs_thread : m_threads) {
378 NativeThreadFreeBSD &thread =
379 static_cast<NativeThreadFreeBSD &>(*abs_thread);
380 assert(info.pl_lwpid >= 0);
381 if (info.pl_lwpid == 0 ||
382 static_cast<lldb::tid_t>(info.pl_lwpid) == thread.GetID()) {
383 thread.SetStoppedBySignal(info.pl_siginfo.si_signo, &info.pl_siginfo);
384 SetCurrentThreadID(thread.GetID());
385 } else
386 thread.SetStoppedWithNoReason();
387 }
389}
390
392 int data, int *result) {
395 int ret;
396
397 errno = 0;
398 ret =
399 ptrace(req, static_cast<::pid_t>(pid), static_cast<caddr_t>(addr), data);
400
401 if (ret == -1) {
402 error = CanTrace();
403 if (error.Success())
405 }
406
407 if (result)
408 *result = ret;
409
410 LLDB_LOG(log, "ptrace({0}, {1}, {2}, {3})={4:x}", req, pid, addr, data, ret);
411
412 if (error.Fail())
413 LLDB_LOG(log, "ptrace() failed: {0}", error);
414
415 return error;
416}
417
418llvm::Expected<llvm::ArrayRef<uint8_t>>
420 static const uint8_t g_arm_opcode[] = {0xfe, 0xde, 0xff, 0xe7};
421 static const uint8_t g_thumb_opcode[] = {0x01, 0xde};
422
423 switch (GetArchitecture().GetMachine()) {
424 case llvm::Triple::arm:
425 switch (size_hint) {
426 case 2:
427 return llvm::ArrayRef(g_thumb_opcode);
428 case 4:
429 return llvm::ArrayRef(g_arm_opcode);
430 default:
431 return llvm::createStringError(llvm::inconvertibleErrorCode(),
432 "Unrecognised trap opcode size hint!");
433 }
434 default:
436 }
437}
438
441 LLDB_LOG(log, "pid {0}", GetID());
442
443 Status ret;
444
445 int signal = 0;
446 for (const auto &abs_thread : m_threads) {
447 assert(abs_thread && "thread list should not contain NULL threads");
448 NativeThreadFreeBSD &thread =
449 static_cast<NativeThreadFreeBSD &>(*abs_thread);
450
451 const ResumeAction *action =
452 resume_actions.GetActionForThread(thread.GetID(), true);
453 // we need to explicit issue suspend requests, so it is simpler to map it
454 // into proper action
455 ResumeAction suspend_action{thread.GetID(), eStateSuspended,
457
458 if (action == nullptr) {
459 LLDB_LOG(log, "no action specified for pid {0} tid {1}", GetID(),
460 thread.GetID());
461 action = &suspend_action;
462 }
463
464 LLDB_LOG(
465 log,
466 "processing resume action state {0} signal {1} for pid {2} tid {3}",
467 action->state, action->signal, GetID(), thread.GetID());
468
469 switch (action->state) {
470 case eStateRunning:
471 ret = thread.Resume();
472 break;
473 case eStateStepping:
474 ret = thread.SingleStep();
475 break;
476 case eStateSuspended:
477 case eStateStopped:
478 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
480 "Passing signal to suspended thread unsupported");
481
482 ret = thread.Suspend();
483 break;
484
485 default:
487 "NativeProcessFreeBSD::%s (): unexpected state %s specified "
488 "for pid %" PRIu64 ", tid %" PRIu64,
489 __FUNCTION__, StateAsCString(action->state), GetID(), thread.GetID());
490 }
491
492 if (!ret.Success())
493 return ret;
494 if (action->signal != LLDB_INVALID_SIGNAL_NUMBER)
495 signal = action->signal;
496 }
497
498 ret =
499 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), signal);
500 if (ret.Success())
501 SetState(eStateRunning, true);
502 return ret;
503}
504
507
508 // Do not try to stop a process that's already stopped, this may cause
509 // the SIGSTOP to get queued and stop the process again once resumed.
510 if (StateIsStoppedState(m_state, false))
511 return error;
512 if (kill(GetID(), SIGSTOP) != 0)
514 return error;
515}
516
519
520 // Stop monitoring the inferior.
521 m_sigchld_handle.reset();
522
523 // Tell ptrace to detach from the process.
525 return error;
526
527 return PtraceWrapper(PT_DETACH, GetID());
528}
529
532
533 if (kill(GetID(), signo))
535
536 return error;
537}
538
540
543 LLDB_LOG(log, "pid {0}", GetID());
544
546
547 switch (m_state) {
553 // Nothing to do - the process is already dead.
554 LLDB_LOG(log, "ignored for PID {0} due to current state: {1}", GetID(),
556 return error;
557
565 // We can try to kill a process in these states.
566 break;
567 }
568
569 return PtraceWrapper(PT_KILL, m_pid);
570}
571
573 MemoryRegionInfo &range_info) {
574
576 // We're done.
577 return Status::FromErrorString("unsupported");
578 }
579
581 if (error.Fail()) {
582 return error;
583 }
584
585 lldb::addr_t prev_base_address = 0;
586 // FIXME start by finding the last region that is <= target address using
587 // binary search. Data is sorted.
588 // There can be a ton of regions on pthreads apps with lots of threads.
589 for (auto it = m_mem_region_cache.begin(); it != m_mem_region_cache.end();
590 ++it) {
591 MemoryRegionInfo &proc_entry_info = it->first;
592 // Sanity check assumption that memory map entries are ascending.
593 assert((proc_entry_info.GetRange().GetRangeBase() >= prev_base_address) &&
594 "descending memory map entries detected, unexpected");
595 prev_base_address = proc_entry_info.GetRange().GetRangeBase();
596 UNUSED_IF_ASSERT_DISABLED(prev_base_address);
597 // If the target address comes before this entry, indicate distance to next
598 // region.
599 if (load_addr < proc_entry_info.GetRange().GetRangeBase()) {
600 range_info.GetRange().SetRangeBase(load_addr);
601 range_info.GetRange().SetByteSize(
602 proc_entry_info.GetRange().GetRangeBase() - load_addr);
603 range_info.SetReadable(eLazyBoolNo);
604 range_info.SetWritable(eLazyBoolNo);
605 range_info.SetExecutable(eLazyBoolNo);
606 range_info.SetMapped(eLazyBoolNo);
607 return error;
608 } else if (proc_entry_info.GetRange().Contains(load_addr)) {
609 // The target address is within the memory region we're processing here.
610 range_info = proc_entry_info;
611 return error;
612 }
613 // The target memory address comes somewhere after the region we just
614 // parsed.
615 }
616 // If we made it here, we didn't find an entry that contained the given
617 // address. Return the load_addr as start and the amount of bytes betwwen
618 // load address and the end of the memory as size.
619 range_info.GetRange().SetRangeBase(load_addr);
621 range_info.SetReadable(eLazyBoolNo);
622 range_info.SetWritable(eLazyBoolNo);
623 range_info.SetExecutable(eLazyBoolNo);
624 range_info.SetMapped(eLazyBoolNo);
625 return error;
626}
627
630 // If our cache is empty, pull the latest. There should always be at least
631 // one memory region if memory region handling is supported.
632 if (!m_mem_region_cache.empty()) {
633 LLDB_LOG(log, "reusing {0} cached memory region entries",
634 m_mem_region_cache.size());
635 return Status();
636 }
637
638 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_VMMAP, static_cast<int>(m_pid)};
639 int ret;
640 size_t len;
641
642 ret = ::sysctl(mib, 4, nullptr, &len, nullptr, 0);
643 if (ret != 0) {
645 return Status::FromErrorString("sysctl() for KERN_PROC_VMMAP failed");
646 }
647
648 std::unique_ptr<WritableMemoryBuffer> buf =
649 llvm::WritableMemoryBuffer::getNewMemBuffer(len);
650 ret = ::sysctl(mib, 4, buf->getBufferStart(), &len, nullptr, 0);
651 if (ret != 0) {
653 return Status::FromErrorString("sysctl() for KERN_PROC_VMMAP failed");
654 }
655
656 char *bp = buf->getBufferStart();
657 char *end = bp + len;
658 while (bp < end) {
659 auto *kv = reinterpret_cast<struct kinfo_vmentry *>(bp);
660 if (kv->kve_structsize == 0)
661 break;
662 bp += kv->kve_structsize;
663
664 MemoryRegionInfo info;
665 info.Clear();
666 info.GetRange().SetRangeBase(kv->kve_start);
667 info.GetRange().SetRangeEnd(kv->kve_end);
669
670 if (kv->kve_protection & VM_PROT_READ)
672 else
674
675 if (kv->kve_protection & VM_PROT_WRITE)
677 else
679
680 if (kv->kve_protection & VM_PROT_EXECUTE)
682 else
684
685 if (kv->kve_path[0])
686 info.SetName(kv->kve_path);
687
688 m_mem_region_cache.emplace_back(info,
689 FileSpec(info.GetName().GetCString()));
690 }
691
692 if (m_mem_region_cache.empty()) {
693 // No entries after attempting to read them. This shouldn't happen. Assume
694 // we don't support map entries.
695 LLDB_LOG(log, "failed to find any vmmap entries, assuming no support "
696 "for memory region metadata retrieval");
698 return Status::FromErrorString("not supported");
699 }
700 LLDB_LOG(log, "read {0} memory region entries from process {1}",
701 m_mem_region_cache.size(), GetID());
702 // We support memory retrieval, remember that.
704
705 return Status();
706}
707
709
711 bool hardware) {
712 if (hardware)
713 return SetHardwareBreakpoint(addr, size);
714 return SetSoftwareBreakpoint(addr, size);
715}
716
718 FileSpec &file_spec) {
720 if (error.Fail()) {
721 auto status = CanTrace();
722 if (status.Fail())
723 return status;
724 return error;
725 }
726
727 FileSpec module_file_spec(module_path);
728 FileSystem::Instance().Resolve(module_file_spec);
729
730 file_spec.Clear();
731 for (const auto &it : m_mem_region_cache) {
732 if (it.second.GetFilename() == module_file_spec.GetFilename()) {
733 file_spec = it.second;
734 return Status();
735 }
736 }
738 "Module file ({0}) not found in process' memory map!",
739 module_file_spec.GetFilename());
740}
741
742Status
743NativeProcessFreeBSD::GetFileLoadAddress(const llvm::StringRef &file_name,
744 lldb::addr_t &load_addr) {
745 load_addr = LLDB_INVALID_ADDRESS;
747 if (error.Fail()) {
748 auto status = CanTrace();
749 if (status.Fail())
750 return status;
751 return error;
752 }
753
754 FileSpec file(file_name);
755 for (const auto &it : m_mem_region_cache) {
756 if (it.second == file) {
757 load_addr = it.first.GetRange().GetRangeBase();
758 return Status();
759 }
760 }
761 return Status::FromErrorStringWithFormat("No load address found for file %s.",
762 file_name.str().c_str());
763}
764
767 int status;
768 ::pid_t wait_pid =
769 llvm::sys::RetryAfterSignal(-1, waitpid, GetID(), &status, WNOHANG);
770
771 if (wait_pid == 0)
772 return;
773
774 if (wait_pid == -1) {
776 LLDB_LOG(log, "waitpid ({0}, &status, _) failed: {1}", GetID(), error);
777 return;
778 }
779
780 WaitStatus wait_status = WaitStatus::Decode(status);
781 bool exited = wait_status.type == WaitStatus::Exit ||
782 (wait_status.type == WaitStatus::Signal &&
783 wait_pid == static_cast<::pid_t>(GetID()));
784
785 LLDB_LOG(log,
786 "waitpid ({0}, &status, _) => pid = {1}, status = {2}, exited = {3}",
787 GetID(), wait_pid, status, exited);
788
789 if (exited)
790 MonitorExited(wait_pid, wait_status);
791 else {
792 assert(wait_status.type == WaitStatus::Stop);
793 MonitorCallback(wait_pid, wait_status.status);
794 }
795}
796
798 for (const auto &thread : m_threads) {
799 assert(thread && "thread list should not contain NULL threads");
800 if (thread->GetID() == thread_id) {
801 // We have this thread.
802 return true;
803 }
804 }
805
806 // We don't have this thread.
807 return false;
808}
809
812 LLDB_LOG(log, "pid {0} adding thread with tid {1}", GetID(), thread_id);
813
814 assert(thread_id > 0);
815 assert(!HasThreadNoLock(thread_id) &&
816 "attempted to add a thread by id that already exists");
817
818 // If this is the first thread, save it as the current thread
819 if (m_threads.empty())
820 SetCurrentThreadID(thread_id);
821
822 m_threads.push_back(std::make_unique<NativeThreadFreeBSD>(*this, thread_id));
823 return static_cast<NativeThreadFreeBSD &>(*m_threads.back());
824}
825
828 LLDB_LOG(log, "pid {0} removing thread with tid {1}", GetID(), thread_id);
829
830 assert(thread_id > 0);
831 assert(HasThreadNoLock(thread_id) &&
832 "attempted to remove a thread that does not exist");
833
834 for (auto it = m_threads.begin(); it != m_threads.end(); ++it) {
835 if ((*it)->GetID() == thread_id) {
836 m_threads.erase(it);
837 break;
838 }
839 }
840
841 if (GetCurrentThreadID() == thread_id)
842 SetCurrentThreadID(m_threads.front()->GetID());
843}
844
846 // Attach to the requested process.
847 // An attach will cause the thread to stop with a SIGSTOP.
848 Status status = PtraceWrapper(PT_ATTACH, m_pid);
849 if (status.Fail())
850 return status;
851
852 int wstatus;
853 // Need to use WALLSIG otherwise we receive an error with errno=ECHLD At this
854 // point we should have a thread stopped if waitpid succeeds.
855 if ((wstatus = llvm::sys::RetryAfterSignal(-1, waitpid, m_pid, nullptr, 0)) <
856 0)
857 return Status(errno, eErrorTypePOSIX);
858
859 // Initialize threads and tracing status
860 // NB: this needs to be called before we set thread state
861 status = SetupTrace();
862 if (status.Fail())
863 return status;
864
865 for (const auto &thread : m_threads)
866 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
867
868 // Let our process instance know the thread has stopped.
869 SetCurrentThreadID(m_threads.front()->GetID());
871 return Status();
872}
873
875 size_t size, size_t &bytes_read) {
876 unsigned char *dst = static_cast<unsigned char *>(buf);
877 struct ptrace_io_desc io;
878
880 LLDB_LOG(log, "addr = {0}, buf = {1}, size = {2}", addr, buf, size);
881
882 bytes_read = 0;
883 io.piod_op = PIOD_READ_D;
884 io.piod_len = size;
885
886 do {
887 io.piod_offs = (void *)(addr + bytes_read);
888 io.piod_addr = dst + bytes_read;
889
891 if (error.Fail() || io.piod_len == 0)
892 return error;
893
894 bytes_read += io.piod_len;
895 io.piod_len = size - bytes_read;
896 } while (bytes_read < size);
897
898 return Status();
899}
900
902 size_t size, size_t &bytes_written) {
903 const unsigned char *src = static_cast<const 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_written = 0;
911 io.piod_op = PIOD_WRITE_D;
912 io.piod_len = size;
913
914 do {
915 io.piod_addr =
916 const_cast<void *>(static_cast<const void *>(src + bytes_written));
917 io.piod_offs = (void *)(addr + bytes_written);
918
920 if (error.Fail() || io.piod_len == 0)
921 return error;
922
923 bytes_written += io.piod_len;
924 io.piod_len = size - bytes_written;
925 } while (bytes_written < size);
926
927 return error;
928}
929
930llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
932 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, static_cast<int>(GetID())};
933 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
934 std::unique_ptr<WritableMemoryBuffer> buf =
935 llvm::WritableMemoryBuffer::getNewMemBuffer(auxv_size);
936
937 if (::sysctl(mib, 4, buf->getBufferStart(), &auxv_size, nullptr, 0) != 0)
938 return std::error_code(errno, std::generic_category());
939
940 return buf;
941}
942
944 // Enable event reporting
945 int events;
946 Status status =
947 PtraceWrapper(PT_GET_EVENT_MASK, GetID(), &events, sizeof(events));
948 if (status.Fail())
949 return status;
950 events |= PTRACE_LWP | PTRACE_FORK | PTRACE_VFORK;
951 status = PtraceWrapper(PT_SET_EVENT_MASK, GetID(), &events, sizeof(events));
952 if (status.Fail())
953 return status;
954
955 return ReinitializeThreads();
956}
957
959 // Clear old threads
960 m_threads.clear();
961
962 int num_lwps;
963 Status error = PtraceWrapper(PT_GETNUMLWPS, GetID(), nullptr, 0, &num_lwps);
964 if (error.Fail())
965 return error;
966
967 std::vector<lwpid_t> lwp_ids;
968 lwp_ids.resize(num_lwps);
969 error = PtraceWrapper(PT_GETLWPLIST, GetID(), lwp_ids.data(),
970 lwp_ids.size() * sizeof(lwpid_t), &num_lwps);
971 if (error.Fail())
972 return error;
973
974 // Reinitialize from scratch threads and register them in process
975 for (lwpid_t lwp : lwp_ids)
976 AddThread(lwp);
977
978 return error;
979}
980
981void NativeProcessFreeBSD::MonitorClone(::pid_t child_pid, bool is_vfork,
982 NativeThreadFreeBSD &parent_thread) {
984 LLDB_LOG(log, "fork, child_pid={0}", child_pid);
985
986 int status;
987 ::pid_t wait_pid =
988 llvm::sys::RetryAfterSignal(-1, ::waitpid, child_pid, &status, 0);
989 if (wait_pid != child_pid) {
990 LLDB_LOG(log,
991 "waiting for pid {0} failed. Assuming the pid has "
992 "disappeared in the meantime",
993 child_pid);
994 return;
995 }
996 if (WIFEXITED(status)) {
997 LLDB_LOG(log,
998 "waiting for pid {0} returned an 'exited' event. Not "
999 "tracking it.",
1000 child_pid);
1001 return;
1002 }
1003
1004 struct ptrace_lwpinfo info;
1005 const auto siginfo_err =
1006 PtraceWrapper(PT_LWPINFO, child_pid, &info, sizeof(info));
1007 if (siginfo_err.Fail()) {
1008 LLDB_LOG(log, "PT_LWPINFO failed {0}", siginfo_err);
1009 return;
1010 }
1011 assert(info.pl_event == PL_EVENT_SIGNAL);
1012 lldb::tid_t child_tid = info.pl_lwpid;
1013
1014 std::unique_ptr<NativeProcessFreeBSD> child_process{
1015 new NativeProcessFreeBSD(static_cast<::pid_t>(child_pid), m_terminal_fd,
1017 if (!is_vfork)
1018 child_process->m_software_breakpoints = m_software_breakpoints;
1019
1020 Extension expected_ext = is_vfork ? Extension::vfork : Extension::fork;
1021 if ((m_enabled_extensions & expected_ext) == expected_ext) {
1022 child_process->SetupTrace();
1023 for (const auto &thread : child_process->m_threads)
1024 static_cast<NativeThreadFreeBSD &>(*thread).SetStoppedBySignal(SIGSTOP);
1025 child_process->SetState(StateType::eStateStopped, false);
1026
1027 m_delegate.NewSubprocess(this, std::move(child_process));
1028 if (is_vfork)
1029 parent_thread.SetStoppedByVFork(child_pid, child_tid);
1030 else
1031 parent_thread.SetStoppedByFork(child_pid, child_tid);
1033 } else {
1034 child_process->Detach();
1035 Status pt_error =
1036 PtraceWrapper(PT_CONTINUE, GetID(), reinterpret_cast<void *>(1), 0);
1037 if (pt_error.Fail()) {
1038 LLDB_LOG_ERROR(log, pt_error.ToError(),
1039 "unable to resume parent process {1}: {0}", GetID());
1041 }
1042 }
1043}
1044
1045llvm::Expected<std::string>
1046NativeProcessFreeBSD::SaveCore(llvm::StringRef path_hint) {
1047#if defined(PT_COREDUMP)
1048 using namespace llvm::sys::fs;
1049
1050 llvm::SmallString<128> path{path_hint};
1051 Status error;
1052 struct ptrace_coredump pc = {};
1053
1054 // Try with the suggested path first. If there is no suggested path or it
1055 // failed to open, use a temporary file.
1056 if (path.empty() ||
1057 openFile(path, pc.pc_fd, CD_CreateNew, FA_Write, OF_None)) {
1058 if (std::error_code errc =
1059 createTemporaryFile("lldb", "core", pc.pc_fd, path))
1060 return llvm::createStringError(errc, "unable to create a temporary file");
1061 }
1062 error = PtraceWrapper(PT_COREDUMP, GetID(), &pc, sizeof(pc));
1063
1064 std::error_code close_err = closeFile(pc.pc_fd);
1065 if (error.Fail())
1066 return error.ToError();
1067 if (close_err)
1068 return llvm::createStringError(
1069 close_err, "Unable to close the core dump after writing");
1070 return path.str().str();
1071#else // !defined(PT_COREDUMP)
1072 return llvm::createStringError(
1073 llvm::inconvertibleErrorCode(),
1074 "PT_COREDUMP not supported in the FreeBSD version used to build LLDB");
1075#endif
1076}
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:364
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
static Status EnsureFDFlags(int fd, int flags)
static Status CanTrace()
An architecture specification class.
Definition ArchSpec.h:32
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:211
SignalHandleUP RegisterSignal(int signo, const Callback &callback, Status &error)
void SetName(const char *name)
Abstract class that extends NativeProcessProtocol with ELF specific logic.
std::vector< std::pair< MemoryRegionInfo, FileSpec > > m_mem_region_cache
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...
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
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
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
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)
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:327
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