1 //===-- ProcessFreeBSD.cpp ----------------------------------------*- C++
2 //-*-===//
3 //
4 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5 // See https://llvm.org/LICENSE.txt for license information.
6 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include <errno.h>
11 #include <pthread.h>
12 #include <pthread_np.h>
13 #include <stdlib.h>
14 #include <sys/sysctl.h>
15 #include <sys/types.h>
16 #include <sys/user.h>
17 #include <machine/elf.h>
18
19 #include <mutex>
20 #include <unordered_map>
21
22 #include "lldb/Core/PluginManager.h"
23 #include "lldb/Host/FileSystem.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/Symbol/ObjectFile.h"
26 #include "lldb/Target/DynamicLoader.h"
27 #include "lldb/Target/Target.h"
28 #include "lldb/Utility/RegisterValue.h"
29 #include "lldb/Utility/State.h"
30
31 #include "FreeBSDThread.h"
32 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
33 #include "Plugins/Process/Utility/FreeBSDSignals.h"
34 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
35 #include "ProcessFreeBSD.h"
36 #include "ProcessMonitor.h"
37
38 #include "lldb/Breakpoint/BreakpointLocation.h"
39 #include "lldb/Breakpoint/Watchpoint.h"
40 #include "lldb/Core/Module.h"
41 #include "lldb/Core/ModuleSpec.h"
42 #include "lldb/Core/PluginManager.h"
43 #include "lldb/Host/Host.h"
44 #include "lldb/Symbol/ObjectFile.h"
45 #include "lldb/Target/DynamicLoader.h"
46 #include "lldb/Target/Platform.h"
47 #include "lldb/Target/Target.h"
48 #include "lldb/Utility/DataBufferHeap.h"
49 #include "lldb/Utility/FileSpec.h"
50 #include "lldb/Utility/State.h"
51
52 #include "lldb/Host/posix/Fcntl.h"
53
54 #include "llvm/Support/FileSystem.h"
55 #include "llvm/Support/Threading.h"
56
57 using namespace lldb;
58 using namespace lldb_private;
59
60 namespace {
GetFreeBSDSignals()61 UnixSignalsSP &GetFreeBSDSignals() {
62 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
63 return s_freebsd_signals_sp;
64 }
65 }
66
67 // Static functions.
68
69 lldb::ProcessSP
CreateInstance(lldb::TargetSP target_sp,lldb::ListenerSP listener_sp,const FileSpec * crash_file_path)70 ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
71 lldb::ListenerSP listener_sp,
72 const FileSpec *crash_file_path) {
73 lldb::ProcessSP process_sp;
74 if (crash_file_path == NULL)
75 process_sp.reset(
76 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
77 return process_sp;
78 }
79
Initialize()80 void ProcessFreeBSD::Initialize() {
81 static llvm::once_flag g_once_flag;
82
83 llvm::call_once(g_once_flag, []() {
84 PluginManager::RegisterPlugin(GetPluginNameStatic(),
85 GetPluginDescriptionStatic(), CreateInstance);
86 });
87 }
88
GetPluginNameStatic()89 lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
90 static ConstString g_name("freebsd");
91 return g_name;
92 }
93
GetPluginDescriptionStatic()94 const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
95 return "Process plugin for FreeBSD";
96 }
97
98 // ProcessInterface protocol.
99
GetPluginName()100 lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
101 return GetPluginNameStatic();
102 }
103
GetPluginVersion()104 uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
105
Terminate()106 void ProcessFreeBSD::Terminate() {}
107
DoDetach(bool keep_stopped)108 Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
109 Status error;
110 if (keep_stopped) {
111 error.SetErrorString("Detaching with keep_stopped true is not currently "
112 "supported on FreeBSD.");
113 return error;
114 }
115
116 error = m_monitor->Detach(GetID());
117
118 if (error.Success())
119 SetPrivateState(eStateDetached);
120
121 return error;
122 }
123
DoResume()124 Status ProcessFreeBSD::DoResume() {
125 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
126
127 SetPrivateState(eStateRunning);
128
129 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
130 bool do_step = false;
131 bool software_single_step = !SupportHardwareSingleStepping();
132
133 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
134 t_end = m_run_tids.end();
135 t_pos != t_end; ++t_pos) {
136 m_monitor->ThreadSuspend(*t_pos, false);
137 }
138 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
139 t_end = m_step_tids.end();
140 t_pos != t_end; ++t_pos) {
141 m_monitor->ThreadSuspend(*t_pos, false);
142 do_step = true;
143 if (software_single_step) {
144 Status error = SetupSoftwareSingleStepping(*t_pos);
145 if (error.Fail())
146 return error;
147 }
148 }
149 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
150 t_end = m_suspend_tids.end();
151 t_pos != t_end; ++t_pos) {
152 m_monitor->ThreadSuspend(*t_pos, true);
153 // XXX Cannot PT_CONTINUE properly with suspended threads.
154 do_step = true;
155 }
156
157 LLDB_LOGF(log, "process %" PRIu64 " resuming (%s)", GetID(),
158 do_step ? "step" : "continue");
159 if (do_step && !software_single_step)
160 m_monitor->SingleStep(GetID(), m_resume_signo);
161 else
162 m_monitor->Resume(GetID(), m_resume_signo);
163
164 return Status();
165 }
166
UpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)167 bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
168 ThreadList &new_thread_list) {
169 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
170 LLDB_LOGF(log, "ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
171 GetID());
172
173 std::vector<lldb::pid_t> tds;
174 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
175 return false;
176 }
177
178 ThreadList old_thread_list_copy(old_thread_list);
179 for (size_t i = 0; i < tds.size(); ++i) {
180 tid_t tid = tds[i];
181 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
182 if (!thread_sp) {
183 thread_sp.reset(new FreeBSDThread(*this, tid));
184 LLDB_LOGF(log, "ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__,
185 tid);
186 } else {
187 LLDB_LOGF(log, "ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
188 tid);
189 }
190 new_thread_list.AddThread(thread_sp);
191 }
192 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
193 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
194 if (old_thread_sp) {
195 LLDB_LOGF(log, "ProcessFreeBSD::%s remove tid", __FUNCTION__);
196 }
197 }
198
199 return true;
200 }
201
WillResume()202 Status ProcessFreeBSD::WillResume() {
203 m_resume_signo = 0;
204 m_suspend_tids.clear();
205 m_run_tids.clear();
206 m_step_tids.clear();
207 return Process::WillResume();
208 }
209
SendMessage(const ProcessMessage & message)210 void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
211 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
212
213 switch (message.GetKind()) {
214 case ProcessMessage::eInvalidMessage:
215 return;
216
217 case ProcessMessage::eAttachMessage:
218 SetPrivateState(eStateStopped);
219 return;
220
221 case ProcessMessage::eLimboMessage:
222 case ProcessMessage::eExitMessage:
223 SetExitStatus(message.GetExitStatus(), NULL);
224 break;
225
226 case ProcessMessage::eSignalMessage:
227 case ProcessMessage::eSignalDeliveredMessage:
228 case ProcessMessage::eBreakpointMessage:
229 case ProcessMessage::eTraceMessage:
230 case ProcessMessage::eWatchpointMessage:
231 case ProcessMessage::eCrashMessage:
232 SetPrivateState(eStateStopped);
233 break;
234
235 case ProcessMessage::eNewThreadMessage:
236 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
237 break;
238
239 case ProcessMessage::eExecMessage:
240 SetPrivateState(eStateStopped);
241 break;
242 }
243
244 m_message_queue.push(message);
245 }
246
247 // Constructors and destructors.
248
ProcessFreeBSD(lldb::TargetSP target_sp,lldb::ListenerSP listener_sp,UnixSignalsSP & unix_signals_sp)249 ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
250 lldb::ListenerSP listener_sp,
251 UnixSignalsSP &unix_signals_sp)
252 : Process(target_sp, listener_sp, unix_signals_sp),
253 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
254 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
255 m_resume_signo(0) {
256 // FIXME: Putting this code in the ctor and saving the byte order in a
257 // member variable is a hack to avoid const qual issues in GetByteOrder.
258 lldb::ModuleSP module = GetTarget().GetExecutableModule();
259 if (module && module->GetObjectFile())
260 m_byte_order = module->GetObjectFile()->GetByteOrder();
261 }
262
~ProcessFreeBSD()263 ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
264
265 // Process protocol.
Finalize()266 void ProcessFreeBSD::Finalize() {
267 Process::Finalize();
268
269 if (m_monitor)
270 m_monitor->StopMonitor();
271 }
272
CanDebug(lldb::TargetSP target_sp,bool plugin_specified_by_name)273 bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
274 bool plugin_specified_by_name) {
275 // For now we are just making sure the file exists for a given module
276 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
277 if (exe_module_sp.get())
278 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
279 // If there is no executable module, we return true since we might be
280 // preparing to attach.
281 return true;
282 }
283
284 Status
DoAttachToProcessWithID(lldb::pid_t pid,const ProcessAttachInfo & attach_info)285 ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
286 const ProcessAttachInfo &attach_info) {
287 Status error;
288 assert(m_monitor == NULL);
289
290 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
291 LLDB_LOGV(log, "pid = {0}", GetID());
292
293 m_monitor = new ProcessMonitor(this, pid, error);
294
295 if (!error.Success())
296 return error;
297
298 PlatformSP platform_sp(GetTarget().GetPlatform());
299 assert(platform_sp.get());
300 if (!platform_sp)
301 return error; // FIXME: Detatch?
302
303 // Find out what we can about this process
304 ProcessInstanceInfo process_info;
305 platform_sp->GetProcessInfo(pid, process_info);
306
307 // Resolve the executable module
308 ModuleSP exe_module_sp;
309 FileSpecList executable_search_paths(
310 Target::GetDefaultExecutableSearchPaths());
311 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
312 GetTarget().GetArchitecture());
313 error = platform_sp->ResolveExecutable(
314 exe_module_spec, exe_module_sp,
315 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
316 if (!error.Success())
317 return error;
318
319 // Fix the target architecture if necessary
320 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
321 if (module_arch.IsValid() &&
322 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
323 GetTarget().SetArchitecture(module_arch);
324
325 // Initialize the target module list
326 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
327
328 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
329
330 SetID(pid);
331
332 return error;
333 }
334
WillLaunch(Module * module)335 Status ProcessFreeBSD::WillLaunch(Module *module) {
336 Status error;
337 return error;
338 }
339
340 FileSpec
GetFileSpec(const lldb_private::FileAction * file_action,const FileSpec & default_file_spec,const FileSpec & dbg_pts_file_spec)341 ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
342 const FileSpec &default_file_spec,
343 const FileSpec &dbg_pts_file_spec) {
344 FileSpec file_spec{};
345
346 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
347 file_spec = file_action->GetFileSpec();
348 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
349 // If so, convert to using a different default path instead to redirect I/O
350 // to the debugger console. This should also handle user overrides to
351 // /dev/null or a different file.
352 if (!file_spec || file_spec == dbg_pts_file_spec)
353 file_spec = default_file_spec;
354 }
355 return file_spec;
356 }
357
DoLaunch(Module * module,ProcessLaunchInfo & launch_info)358 Status ProcessFreeBSD::DoLaunch(Module *module,
359 ProcessLaunchInfo &launch_info) {
360 Status error;
361 assert(m_monitor == NULL);
362
363 FileSpec working_dir = launch_info.GetWorkingDirectory();
364 if (working_dir) {
365 FileSystem::Instance().Resolve(working_dir);
366 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) {
367 error.SetErrorStringWithFormat("No such file or directory: %s",
368 working_dir.GetCString());
369 return error;
370 }
371 }
372
373 SetPrivateState(eStateLaunching);
374
375 const lldb_private::FileAction *file_action;
376
377 // Default of empty will mean to use existing open file descriptors
378 FileSpec stdin_file_spec{};
379 FileSpec stdout_file_spec{};
380 FileSpec stderr_file_spec{};
381
382 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)};
383
384 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
385 stdin_file_spec =
386 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
387
388 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
389 stdout_file_spec =
390 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
391
392 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
393 stderr_file_spec =
394 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
395
396 m_monitor = new ProcessMonitor(
397 this, module, launch_info.GetArguments().GetConstArgumentVector(),
398 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
399 stderr_file_spec, working_dir, launch_info, error);
400
401 m_module = module;
402
403 if (!error.Success())
404 return error;
405
406 int terminal = m_monitor->GetTerminalFD();
407 if (terminal >= 0) {
408 // The reader thread will close the file descriptor when done, so we pass it a
409 // copy.
410 #ifdef F_DUPFD_CLOEXEC
411 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
412 if (stdio == -1) {
413 error.SetErrorToErrno();
414 return error;
415 }
416 #else
417 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
418 int stdio = fcntl(terminal, F_DUPFD, 0);
419 if (stdio == -1) {
420 error.SetErrorToErrno();
421 return error;
422 }
423 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
424 if (stdio == -1) {
425 error.SetErrorToErrno();
426 return error;
427 }
428 #endif
429 SetSTDIOFileDescriptor(stdio);
430 }
431
432 SetID(m_monitor->GetPID());
433 return error;
434 }
435
DidLaunch()436 void ProcessFreeBSD::DidLaunch() {}
437
GetImageInfoAddress()438 addr_t ProcessFreeBSD::GetImageInfoAddress() {
439 Target *target = &GetTarget();
440 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
441 Address addr = obj_file->GetImageInfoAddress(target);
442
443 if (addr.IsValid())
444 return addr.GetLoadAddress(target);
445 return LLDB_INVALID_ADDRESS;
446 }
447
DoHalt(bool & caused_stop)448 Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
449 Status error;
450
451 if (IsStopped()) {
452 caused_stop = false;
453 } else if (kill(GetID(), SIGSTOP)) {
454 caused_stop = false;
455 error.SetErrorToErrno();
456 } else {
457 caused_stop = true;
458 }
459 return error;
460 }
461
DoSignal(int signal)462 Status ProcessFreeBSD::DoSignal(int signal) {
463 Status error;
464
465 if (kill(GetID(), signal))
466 error.SetErrorToErrno();
467
468 return error;
469 }
470
DoDestroy()471 Status ProcessFreeBSD::DoDestroy() {
472 Status error;
473
474 if (!HasExited()) {
475 assert(m_monitor);
476 m_exit_now = true;
477 if (GetID() == LLDB_INVALID_PROCESS_ID) {
478 error.SetErrorString("invalid process id");
479 return error;
480 }
481 if (!m_monitor->Kill()) {
482 error.SetErrorToErrno();
483 return error;
484 }
485
486 SetPrivateState(eStateExited);
487 }
488
489 return error;
490 }
491
DoDidExec()492 void ProcessFreeBSD::DoDidExec() {
493 Target *target = &GetTarget();
494 if (target) {
495 PlatformSP platform_sp(target->GetPlatform());
496 assert(platform_sp.get());
497 if (platform_sp) {
498 ProcessInstanceInfo process_info;
499 platform_sp->GetProcessInfo(GetID(), process_info);
500 ModuleSP exe_module_sp;
501 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
502 target->GetArchitecture());
503 FileSpecList executable_search_paths(
504 Target::GetDefaultExecutableSearchPaths());
505 Status error = platform_sp->ResolveExecutable(
506 exe_module_spec, exe_module_sp,
507 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
508 if (!error.Success())
509 return;
510 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
511 }
512 }
513 }
514
AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid)515 bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
516 bool added_to_set = false;
517 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
518 if (it == m_seen_initial_stop.end()) {
519 m_seen_initial_stop.insert(stop_tid);
520 added_to_set = true;
521 }
522 return added_to_set;
523 }
524
WaitingForInitialStop(lldb::tid_t stop_tid)525 bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
526 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
527 }
528
529 FreeBSDThread *
CreateNewFreeBSDThread(lldb_private::Process & process,lldb::tid_t tid)530 ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
531 lldb::tid_t tid) {
532 return new FreeBSDThread(process, tid);
533 }
534
RefreshStateAfterStop()535 void ProcessFreeBSD::RefreshStateAfterStop() {
536 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
537 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
538
539 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
540
541 // This method used to only handle one message. Changing it to loop allows
542 // it to handle the case where we hit a breakpoint while handling a different
543 // breakpoint.
544 while (!m_message_queue.empty()) {
545 ProcessMessage &message = m_message_queue.front();
546
547 // Resolve the thread this message corresponds to and pass it along.
548 lldb::tid_t tid = message.GetTID();
549 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
550 m_message_queue.size(), tid);
551
552 m_thread_list.RefreshStateAfterStop();
553
554 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
555 GetThreadList().FindThreadByID(tid, false).get());
556 if (thread)
557 thread->Notify(message);
558
559 if (message.GetKind() == ProcessMessage::eExitMessage) {
560 // FIXME: We should tell the user about this, but the limbo message is
561 // probably better for that.
562 LLDB_LOG(log, "removing thread, tid = {0}", tid);
563 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
564
565 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
566 thread_sp.reset();
567 m_seen_initial_stop.erase(tid);
568 }
569
570 m_message_queue.pop();
571 }
572 }
573
IsAlive()574 bool ProcessFreeBSD::IsAlive() {
575 StateType state = GetPrivateState();
576 return state != eStateDetached && state != eStateExited &&
577 state != eStateInvalid && state != eStateUnloaded;
578 }
579
DoReadMemory(addr_t vm_addr,void * buf,size_t size,Status & error)580 size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
581 Status &error) {
582 assert(m_monitor);
583 return m_monitor->ReadMemory(vm_addr, buf, size, error);
584 }
585
DoWriteMemory(addr_t vm_addr,const void * buf,size_t size,Status & error)586 size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
587 size_t size, Status &error) {
588 assert(m_monitor);
589 return m_monitor->WriteMemory(vm_addr, buf, size, error);
590 }
591
DoAllocateMemory(size_t size,uint32_t permissions,Status & error)592 addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
593 Status &error) {
594 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
595
596 unsigned prot = 0;
597 if (permissions & lldb::ePermissionsReadable)
598 prot |= eMmapProtRead;
599 if (permissions & lldb::ePermissionsWritable)
600 prot |= eMmapProtWrite;
601 if (permissions & lldb::ePermissionsExecutable)
602 prot |= eMmapProtExec;
603
604 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
605 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
606 m_addr_to_mmap_size[allocated_addr] = size;
607 error.Clear();
608 } else {
609 allocated_addr = LLDB_INVALID_ADDRESS;
610 error.SetErrorStringWithFormat(
611 "unable to allocate %zu bytes of memory with permissions %s", size,
612 GetPermissionsAsCString(permissions));
613 }
614
615 return allocated_addr;
616 }
617
DoDeallocateMemory(lldb::addr_t addr)618 Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
619 Status error;
620 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
621 if (pos != m_addr_to_mmap_size.end() &&
622 InferiorCallMunmap(this, addr, pos->second))
623 m_addr_to_mmap_size.erase(pos);
624 else
625 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
626 addr);
627
628 return error;
629 }
630
631 size_t
GetSoftwareBreakpointTrapOpcode(BreakpointSite * bp_site)632 ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
633 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
634 static const uint8_t g_i386_opcode[] = {0xCC};
635
636 ArchSpec arch = GetTarget().GetArchitecture();
637 const uint8_t *opcode = NULL;
638 size_t opcode_size = 0;
639
640 switch (arch.GetMachine()) {
641 default:
642 assert(false && "CPU type not supported!");
643 break;
644
645 case llvm::Triple::arm: {
646 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
647 // linux kernel does otherwise.
648 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
649 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
650
651 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
652 AddressClass addr_class = AddressClass::eUnknown;
653
654 if (bp_loc_sp)
655 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
656
657 if (addr_class == AddressClass::eCodeAlternateISA ||
658 (addr_class == AddressClass::eUnknown &&
659 bp_loc_sp->GetAddress().GetOffset() & 1)) {
660 opcode = g_thumb_breakpoint_opcode;
661 opcode_size = sizeof(g_thumb_breakpoint_opcode);
662 } else {
663 opcode = g_arm_breakpoint_opcode;
664 opcode_size = sizeof(g_arm_breakpoint_opcode);
665 }
666 } break;
667 case llvm::Triple::aarch64:
668 opcode = g_aarch64_opcode;
669 opcode_size = sizeof(g_aarch64_opcode);
670 break;
671
672 case llvm::Triple::x86:
673 case llvm::Triple::x86_64:
674 opcode = g_i386_opcode;
675 opcode_size = sizeof(g_i386_opcode);
676 break;
677 }
678
679 bp_site->SetTrapOpcode(opcode, opcode_size);
680 return opcode_size;
681 }
682
EnableBreakpointSite(BreakpointSite * bp_site)683 Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
684 return EnableSoftwareBreakpoint(bp_site);
685 }
686
DisableBreakpointSite(BreakpointSite * bp_site)687 Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
688 return DisableSoftwareBreakpoint(bp_site);
689 }
690
EnableWatchpoint(Watchpoint * wp,bool notify)691 Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
692 Status error;
693 if (wp) {
694 user_id_t watchID = wp->GetID();
695 addr_t addr = wp->GetLoadAddress();
696 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
697 LLDB_LOGF(log, "ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
698 watchID);
699 if (wp->IsEnabled()) {
700 LLDB_LOGF(log,
701 "ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
702 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
703 watchID, (uint64_t)addr);
704 return error;
705 }
706
707 // Try to find a vacant watchpoint slot in the inferiors' main thread
708 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
709 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
710 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
711 m_thread_list.GetThreadAtIndex(0, false).get());
712
713 if (thread)
714 wp_hw_index = thread->FindVacantWatchpointIndex();
715
716 if (wp_hw_index == LLDB_INVALID_INDEX32) {
717 error.SetErrorString("Setting hardware watchpoint failed.");
718 } else {
719 wp->SetHardwareIndex(wp_hw_index);
720 bool wp_enabled = true;
721 uint32_t thread_count = m_thread_list.GetSize(false);
722 for (uint32_t i = 0; i < thread_count; ++i) {
723 thread = static_cast<FreeBSDThread *>(
724 m_thread_list.GetThreadAtIndex(i, false).get());
725 if (thread)
726 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
727 else
728 wp_enabled = false;
729 }
730 if (wp_enabled) {
731 wp->SetEnabled(true, notify);
732 return error;
733 } else {
734 // Watchpoint enabling failed on at least one of the threads so roll
735 // back all of them
736 DisableWatchpoint(wp, false);
737 error.SetErrorString("Setting hardware watchpoint failed");
738 }
739 }
740 } else
741 error.SetErrorString("Watchpoint argument was NULL.");
742 return error;
743 }
744
DisableWatchpoint(Watchpoint * wp,bool notify)745 Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
746 Status error;
747 if (wp) {
748 user_id_t watchID = wp->GetID();
749 addr_t addr = wp->GetLoadAddress();
750 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
751 LLDB_LOGF(log, "ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
752 watchID);
753 if (!wp->IsEnabled()) {
754 LLDB_LOGF(log,
755 "ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
756 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
757 watchID, (uint64_t)addr);
758 // This is needed (for now) to keep watchpoints disabled correctly
759 wp->SetEnabled(false, notify);
760 return error;
761 }
762
763 if (wp->IsHardware()) {
764 bool wp_disabled = true;
765 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
766 uint32_t thread_count = m_thread_list.GetSize(false);
767 for (uint32_t i = 0; i < thread_count; ++i) {
768 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
769 m_thread_list.GetThreadAtIndex(i, false).get());
770 if (thread)
771 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
772 else
773 wp_disabled = false;
774 }
775 if (wp_disabled) {
776 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
777 wp->SetEnabled(false, notify);
778 return error;
779 } else
780 error.SetErrorString("Disabling hardware watchpoint failed");
781 }
782 } else
783 error.SetErrorString("Watchpoint argument was NULL.");
784 return error;
785 }
786
GetWatchpointSupportInfo(uint32_t & num)787 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
788 Status error;
789 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
790 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
791 m_thread_list.GetThreadAtIndex(0, false).get());
792 if (thread)
793 num = thread->NumSupportedHardwareWatchpoints();
794 else
795 error.SetErrorString("Process does not exist.");
796 return error;
797 }
798
GetWatchpointSupportInfo(uint32_t & num,bool & after)799 Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
800 Status error = GetWatchpointSupportInfo(num);
801 // Watchpoints trigger and halt the inferior after the corresponding
802 // instruction has been executed.
803 after = true;
804 return error;
805 }
806
UpdateThreadListIfNeeded()807 uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
808 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
809 // Do not allow recursive updates.
810 return m_thread_list.GetSize(false);
811 }
812
GetByteOrder() const813 ByteOrder ProcessFreeBSD::GetByteOrder() const {
814 // FIXME: We should be able to extract this value directly. See comment in
815 // ProcessFreeBSD().
816 return m_byte_order;
817 }
818
PutSTDIN(const char * buf,size_t len,Status & error)819 size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
820 ssize_t status;
821 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
822 error.SetErrorToErrno();
823 return 0;
824 }
825 return status;
826 }
827
828 // Utility functions.
829
HasExited()830 bool ProcessFreeBSD::HasExited() {
831 switch (GetPrivateState()) {
832 default:
833 break;
834
835 case eStateDetached:
836 case eStateExited:
837 return true;
838 }
839
840 return false;
841 }
842
IsStopped()843 bool ProcessFreeBSD::IsStopped() {
844 switch (GetPrivateState()) {
845 default:
846 break;
847
848 case eStateStopped:
849 case eStateCrashed:
850 case eStateSuspended:
851 return true;
852 }
853
854 return false;
855 }
856
IsAThreadRunning()857 bool ProcessFreeBSD::IsAThreadRunning() {
858 bool is_running = false;
859 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
860 uint32_t thread_count = m_thread_list.GetSize(false);
861 for (uint32_t i = 0; i < thread_count; ++i) {
862 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
863 m_thread_list.GetThreadAtIndex(i, false).get());
864 StateType thread_state = thread->GetState();
865 if (thread_state == eStateRunning || thread_state == eStateStepping) {
866 is_running = true;
867 break;
868 }
869 }
870 return is_running;
871 }
872
GetAuxvData()873 lldb_private::DataExtractor ProcessFreeBSD::GetAuxvData() {
874 // If we're the local platform, we can ask the host for auxv data.
875 PlatformSP platform_sp = GetTarget().GetPlatform();
876 assert(platform_sp && platform_sp->IsHost());
877
878 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
879 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
880 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
881
882 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
883 perror("sysctl failed on auxv");
884 buf_sp.reset();
885 }
886
887 return DataExtractor(buf_sp, GetByteOrder(), GetAddressByteSize());
888 }
889
890 struct EmulatorBaton {
891 ProcessFreeBSD *m_process;
892 RegisterContext *m_reg_context;
893
894 // eRegisterKindDWARF -> RegisterValue
895 std::unordered_map<uint32_t, RegisterValue> m_register_values;
896
EmulatorBatonEmulatorBaton897 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
898 : m_process(process), m_reg_context(reg_context) {}
899 };
900
ReadMemoryCallback(EmulateInstruction * instruction,void * baton,const EmulateInstruction::Context & context,lldb::addr_t addr,void * dst,size_t length)901 static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
902 const EmulateInstruction::Context &context,
903 lldb::addr_t addr, void *dst, size_t length) {
904 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
905
906 Status error;
907 size_t bytes_read =
908 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
909 if (!error.Success())
910 bytes_read = 0;
911 return bytes_read;
912 }
913
ReadRegisterCallback(EmulateInstruction * instruction,void * baton,const RegisterInfo * reg_info,RegisterValue & reg_value)914 static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
915 const RegisterInfo *reg_info,
916 RegisterValue ®_value) {
917 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
918
919 auto it = emulator_baton->m_register_values.find(
920 reg_info->kinds[eRegisterKindDWARF]);
921 if (it != emulator_baton->m_register_values.end()) {
922 reg_value = it->second;
923 return true;
924 }
925
926 // The emulator only fills in the dwarf register numbers (and in some cases
927 // the generic register numbers). Get the full register info from the
928 // register context based on the dwarf register numbers.
929 const RegisterInfo *full_reg_info =
930 emulator_baton->m_reg_context->GetRegisterInfo(
931 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
932
933 bool error =
934 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
935 return error;
936 }
937
WriteRegisterCallback(EmulateInstruction * instruction,void * baton,const EmulateInstruction::Context & context,const RegisterInfo * reg_info,const RegisterValue & reg_value)938 static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
939 const EmulateInstruction::Context &context,
940 const RegisterInfo *reg_info,
941 const RegisterValue ®_value) {
942 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
943 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
944 reg_value;
945 return true;
946 }
947
WriteMemoryCallback(EmulateInstruction * instruction,void * baton,const EmulateInstruction::Context & context,lldb::addr_t addr,const void * dst,size_t length)948 static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
949 const EmulateInstruction::Context &context,
950 lldb::addr_t addr, const void *dst,
951 size_t length) {
952 return length;
953 }
954
SingleStepBreakpointHit(void * baton,lldb_private::StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)955 bool ProcessFreeBSD::SingleStepBreakpointHit(
956 void *baton, lldb_private::StoppointCallbackContext *context,
957 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
958 return false;
959 }
960
SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,lldb::addr_t addr)961 Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
962 lldb::addr_t addr) {
963 Status error;
964
965 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
966 if (log) {
967 LLDB_LOGF(log, "ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
968 LLDB_LOGF(log, "SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__,
969 addr);
970 }
971
972 // Validate the address.
973 if (addr == LLDB_INVALID_ADDRESS)
974 return Status("ProcessFreeBSD::%s invalid load address specified.",
975 __FUNCTION__);
976
977 Breakpoint *const sw_step_break =
978 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
979 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
980 sw_step_break->SetBreakpointKind("software-single-step");
981
982 LLDB_LOGF(log, "ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
983 __FUNCTION__, addr);
984
985 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
986 return Status();
987 }
988
IsSoftwareStepBreakpoint(lldb::tid_t tid)989 bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
990 ThreadSP thread = GetThreadList().FindThreadByID(tid);
991 if (!thread)
992 return false;
993
994 assert(thread->GetRegisterContext());
995 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
996
997 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
998 if (iter == m_threads_stepping_with_breakpoint.end())
999 return false;
1000
1001 lldb::break_id_t bp_id = iter->second;
1002 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1003 if (!bp)
1004 return false;
1005
1006 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1007 if (!bp_loc)
1008 return false;
1009
1010 GetTarget().RemoveBreakpointByID(bp_id);
1011 m_threads_stepping_with_breakpoint.erase(tid);
1012 return true;
1013 }
1014
SupportHardwareSingleStepping() const1015 bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1016 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1017 if (arch.GetMachine() == llvm::Triple::arm || arch.IsMIPS())
1018 return false;
1019 return true;
1020 }
1021
SetupSoftwareSingleStepping(lldb::tid_t tid)1022 Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1023 std::unique_ptr<EmulateInstruction> emulator_up(
1024 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1025 eInstructionTypePCModifying, nullptr));
1026
1027 if (emulator_up == nullptr)
1028 return Status("Instruction emulator not found!");
1029
1030 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1031 m_thread_list.FindThreadByID(tid, false).get());
1032 if (thread == NULL)
1033 return Status("Thread not found not found!");
1034
1035 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1036
1037 EmulatorBaton baton(this, register_context_sp.get());
1038 emulator_up->SetBaton(&baton);
1039 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
1040 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
1041 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
1042 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
1043
1044 if (!emulator_up->ReadInstruction())
1045 return Status("Read instruction failed!");
1046
1047 bool emulation_result =
1048 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1049 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1050 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1051 auto pc_it =
1052 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1053
1054 lldb::addr_t next_pc;
1055 if (emulation_result) {
1056 assert(pc_it != baton.m_register_values.end() &&
1057 "Emulation was successful but PC wasn't updated");
1058 next_pc = pc_it->second.GetAsUInt64();
1059 } else if (pc_it == baton.m_register_values.end()) {
1060 // Emulate instruction failed and it haven't changed PC. Advance PC with
1061 // the size of the current opcode because the emulation of all
1062 // PC modifying instruction should be successful. The failure most
1063 // likely caused by a not supported instruction which don't modify PC.
1064 next_pc =
1065 register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize();
1066 } else {
1067 // The instruction emulation failed after it modified the PC. It is an
1068 // unknown error where we can't continue because the next instruction is
1069 // modifying the PC but we don't know how.
1070 return Status("Instruction emulation failed unexpectedly");
1071 }
1072
1073 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1074 return Status();
1075 }
1076