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

source code of lldb/source/Plugins/Process/FreeBSD/NativeProcessFreeBSD.cpp