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