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