blob: 1a3ac23de272d00e59eb9c78c07447173558332f [file] [log] [blame]
Kate Stoneb9c1b512016-09-06 20:57:50 +00001//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++
2//-*-===//
Johnny Chen9ed5b492012-01-05 21:48:15 +00003//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11// C Includes
12#include <errno.h>
13
14// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000015#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000016#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000017
Johnny Chen9ed5b492012-01-05 21:48:15 +000018// Other libraries and framework includes
19#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/State.h"
21#include "lldb/Host/Host.h"
22#include "lldb/Symbol/ObjectFile.h"
23#include "lldb/Target/DynamicLoader.h"
24#include "lldb/Target/Target.h"
25
Ed Maste7fd845c2013-12-09 15:51:17 +000026#include "FreeBSDThread.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000027#include "Plugins/Process/Utility/FreeBSDSignals.h"
28#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
29#include "ProcessFreeBSD.h"
30#include "ProcessMonitor.h"
31#include "ProcessPOSIXLog.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000032
Ed Mastefe5a6422015-07-28 15:45:57 +000033// Other libraries and framework includes
34#include "lldb/Breakpoint/BreakpointLocation.h"
35#include "lldb/Breakpoint/Watchpoint.h"
36#include "lldb/Core/Module.h"
37#include "lldb/Core/ModuleSpec.h"
38#include "lldb/Core/PluginManager.h"
39#include "lldb/Core/State.h"
40#include "lldb/Host/FileSpec.h"
41#include "lldb/Host/Host.h"
42#include "lldb/Symbol/ObjectFile.h"
43#include "lldb/Target/DynamicLoader.h"
44#include "lldb/Target/Platform.h"
45#include "lldb/Target/Target.h"
46
47#include "lldb/Host/posix/Fcntl.h"
48
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000049#include "llvm/Support/Threading.h"
50
Johnny Chen9ed5b492012-01-05 21:48:15 +000051using namespace lldb;
52using namespace lldb_private;
53
Kate Stoneb9c1b512016-09-06 20:57:50 +000054namespace {
55UnixSignalsSP &GetFreeBSDSignals() {
56 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
57 return s_freebsd_signals_sp;
58}
Todd Fiala4ceced32014-08-29 17:35:57 +000059}
60
Johnny Chen9ed5b492012-01-05 21:48:15 +000061//------------------------------------------------------------------------------
62// Static functions.
63
Greg Clayton29d19302012-02-27 18:40:48 +000064lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000065ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000066 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000067 const FileSpec *crash_file_path) {
68 lldb::ProcessSP process_sp;
69 if (crash_file_path == NULL)
70 process_sp.reset(
71 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
72 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000073}
74
Kate Stoneb9c1b512016-09-06 20:57:50 +000075void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000076 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000077
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000078 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000079 PluginManager::RegisterPlugin(GetPluginNameStatic(),
80 GetPluginDescriptionStatic(), CreateInstance);
81 ProcessPOSIXLog::Initialize(GetPluginNameStatic());
82 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000083}
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
86 static ConstString g_name("freebsd");
87 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000088}
89
Kate Stoneb9c1b512016-09-06 20:57:50 +000090const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
91 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000092}
93
94//------------------------------------------------------------------------------
95// ProcessInterface protocol.
96
Kate Stoneb9c1b512016-09-06 20:57:50 +000097lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
98 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +000099}
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000104
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105Error ProcessFreeBSD::DoDetach(bool keep_stopped) {
106 Error error;
107 if (keep_stopped) {
108 error.SetErrorString("Detaching with keep_stopped true is not currently "
109 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000110 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111 }
112
113 error = m_monitor->Detach(GetID());
114
115 if (error.Success())
116 SetPrivateState(eStateDetached);
117
118 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000119}
120
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121Error ProcessFreeBSD::DoResume() {
122 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000123
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000125
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
127 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000128 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
131 t_end = m_run_tids.end();
132 t_pos != t_end; ++t_pos) {
133 m_monitor->ThreadSuspend(*t_pos, false);
134 }
135 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
136 t_end = m_step_tids.end();
137 t_pos != t_end; ++t_pos) {
138 m_monitor->ThreadSuspend(*t_pos, false);
139 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000140 if (software_single_step) {
141 Error error = SetupSoftwareSingleStepping(*t_pos);
142 if (error.Fail())
143 return error;
144 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 }
146 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
147 t_end = m_suspend_tids.end();
148 t_pos != t_end; ++t_pos) {
149 m_monitor->ThreadSuspend(*t_pos, true);
150 // XXX Cannot PT_CONTINUE properly with suspended threads.
151 do_step = true;
152 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 if (log)
155 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
156 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000157 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 m_monitor->SingleStep(GetID(), m_resume_signo);
159 else
160 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000161
Mehdi Amini665be502016-11-11 05:07:57 +0000162 return Error();
Ed Maste7fd845c2013-12-09 15:51:17 +0000163}
164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
166 ThreadList &new_thread_list) {
167 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
168 if (log)
169 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
170 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 std::vector<lldb::pid_t> tds;
173 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
174 return false;
175 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 ThreadList old_thread_list_copy(old_thread_list);
178 for (size_t i = 0; i < tds.size(); ++i) {
179 tid_t tid = tds[i];
180 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
181 if (!thread_sp) {
182 thread_sp.reset(new FreeBSDThread(*this, tid));
183 if (log)
184 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
185 } else {
186 if (log)
187 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
188 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 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 if (log)
196 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000197 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000199
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000201}
Ed Maste7fd845c2013-12-09 15:51:17 +0000202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203Error ProcessFreeBSD::WillResume() {
204 m_resume_signo = 0;
205 m_suspend_tids.clear();
206 m_run_tids.clear();
207 m_step_tids.clear();
208 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000209}
210
Kate Stoneb9c1b512016-09-06 20:57:50 +0000211void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
212 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 switch (message.GetKind()) {
215 case ProcessMessage::eInvalidMessage:
216 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000217
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218 case ProcessMessage::eAttachMessage:
219 SetPrivateState(eStateStopped);
220 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000221
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 case ProcessMessage::eLimboMessage:
223 case ProcessMessage::eExitMessage:
224 SetExitStatus(message.GetExitStatus(), NULL);
225 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 case ProcessMessage::eSignalMessage:
228 case ProcessMessage::eSignalDeliveredMessage:
229 case ProcessMessage::eBreakpointMessage:
230 case ProcessMessage::eTraceMessage:
231 case ProcessMessage::eWatchpointMessage:
232 case ProcessMessage::eCrashMessage:
233 SetPrivateState(eStateStopped);
234 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 case ProcessMessage::eNewThreadMessage:
237 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
238 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 case ProcessMessage::eExecMessage:
241 SetPrivateState(eStateStopped);
242 break;
243 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000246}
Ed Mastefe5a6422015-07-28 15:45:57 +0000247
248//------------------------------------------------------------------------------
249// Constructors and destructors.
250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
252 lldb::ListenerSP listener_sp,
253 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000254 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 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();
Ed Mastefe5a6422015-07-28 15:45:57 +0000263}
264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000266
267//------------------------------------------------------------------------------
268// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000269void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000270 Process::Finalize();
271
272 if (m_monitor)
273 m_monitor->StopMonitor();
274}
275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
277 bool plugin_specified_by_name) {
278 // For now we are just making sure the file exists for a given module
279 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
280 if (exe_module_sp.get())
281 return exe_module_sp->GetFileSpec().Exists();
282 // If there is no executable module, we return true since we might be
283 // preparing to attach.
284 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000285}
286
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287Error ProcessFreeBSD::DoAttachToProcessWithID(
288 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
289 Error error;
290 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000291
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
293 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
294 log->Printf("ProcessFreeBSD::%s(pid = %" PRIi64 ")", __FUNCTION__, GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000299 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300
301 PlatformSP platform_sp(GetTarget().GetPlatform());
302 assert(platform_sp.get());
303 if (!platform_sp)
304 return error; // FIXME: Detatch?
305
306 // Find out what we can about this process
307 ProcessInstanceInfo process_info;
308 platform_sp->GetProcessInfo(pid, process_info);
309
310 // Resolve the executable module
311 ModuleSP exe_module_sp;
312 FileSpecList executable_search_paths(
313 Target::GetDefaultExecutableSearchPaths());
314 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
315 GetTarget().GetArchitecture());
316 error = platform_sp->ResolveExecutable(
317 exe_module_spec, exe_module_sp,
318 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
319 if (!error.Success())
320 return error;
321
322 // Fix the target architecture if necessary
323 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
324 if (module_arch.IsValid() &&
325 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
326 GetTarget().SetArchitecture(module_arch);
327
328 // Initialize the target module list
329 GetTarget().SetExecutableModule(exe_module_sp, true);
330
331 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
332
333 SetID(pid);
334
335 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000336}
337
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338Error ProcessFreeBSD::WillLaunch(Module *module) {
339 Error error;
340 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000341}
342
343FileSpec
344ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 const FileSpec &default_file_spec,
346 const FileSpec &dbg_pts_file_spec) {
347 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
350 file_spec = file_action->GetFileSpec();
351 // By default the stdio paths passed in will be pseudo-terminal
352 // (/dev/pts). If so, convert to using a different default path
353 // instead to redirect I/O to the debugger console. This should
354 // also handle user overrides to /dev/null or a different file.
355 if (!file_spec || file_spec == dbg_pts_file_spec)
356 file_spec = default_file_spec;
357 }
358 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000359}
360
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) {
362 Error error;
363 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000364
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 FileSpec working_dir = launch_info.GetWorkingDirectory();
366 if (working_dir &&
367 (!working_dir.ResolvePath() ||
368 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
369 error.SetErrorStringWithFormat("No such file or directory: %s",
370 working_dir.GetCString());
371 return error;
372 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000377
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 // Default of empty will mean to use existing open file descriptors
379 FileSpec stdin_file_spec{};
380 FileSpec stdout_file_spec{};
381 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
384 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
387 stdin_file_spec =
388 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000389
Kate Stoneb9c1b512016-09-06 20:57:50 +0000390 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
391 stdout_file_spec =
392 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
395 stderr_file_spec =
396 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 m_monitor = new ProcessMonitor(
399 this, module, launch_info.GetArguments().GetConstArgumentVector(),
400 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
401 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
402 launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 if (!error.Success())
407 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 int terminal = m_monitor->GetTerminalFD();
410 if (terminal >= 0) {
411// The reader thread will close the file descriptor when done, so we pass it a
412// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000413#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
415 if (stdio == -1) {
416 error.SetErrorToErrno();
417 return error;
418 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000419#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
421 int stdio = fcntl(terminal, F_DUPFD, 0);
422 if (stdio == -1) {
423 error.SetErrorToErrno();
424 return error;
425 }
426 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
427 if (stdio == -1) {
428 error.SetErrorToErrno();
429 return error;
430 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000431#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 SetSTDIOFileDescriptor(stdio);
433 }
434
435 SetID(m_monitor->GetPID());
436 return error;
437}
438
439void ProcessFreeBSD::DidLaunch() {}
440
441addr_t ProcessFreeBSD::GetImageInfoAddress() {
442 Target *target = &GetTarget();
443 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
444 Address addr = obj_file->GetImageInfoAddress(target);
445
446 if (addr.IsValid())
447 return addr.GetLoadAddress(target);
448 return LLDB_INVALID_ADDRESS;
449}
450
451Error ProcessFreeBSD::DoHalt(bool &caused_stop) {
452 Error error;
453
454 if (IsStopped()) {
455 caused_stop = false;
456 } else if (kill(GetID(), SIGSTOP)) {
457 caused_stop = false;
458 error.SetErrorToErrno();
459 } else {
460 caused_stop = true;
461 }
462 return error;
463}
464
465Error ProcessFreeBSD::DoSignal(int signal) {
466 Error error;
467
468 if (kill(GetID(), signal))
469 error.SetErrorToErrno();
470
471 return error;
472}
473
474Error ProcessFreeBSD::DoDestroy() {
475 Error error;
476
477 if (!HasExited()) {
478 assert(m_monitor);
479 m_exit_now = true;
480 if (GetID() == LLDB_INVALID_PROCESS_ID) {
481 error.SetErrorString("invalid process id");
482 return error;
483 }
484 if (!m_monitor->Kill()) {
485 error.SetErrorToErrno();
486 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000487 }
488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489 SetPrivateState(eStateExited);
490 }
491
492 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000493}
494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495void ProcessFreeBSD::DoDidExec() {
496 Target *target = &GetTarget();
497 if (target) {
498 PlatformSP platform_sp(target->GetPlatform());
499 assert(platform_sp.get());
500 if (platform_sp) {
501 ProcessInstanceInfo process_info;
502 platform_sp->GetProcessInfo(GetID(), process_info);
503 ModuleSP exe_module_sp;
504 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
505 target->GetArchitecture());
506 FileSpecList executable_search_paths(
507 Target::GetDefaultExecutableSearchPaths());
508 Error error = platform_sp->ResolveExecutable(
509 exe_module_spec, exe_module_sp,
510 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
511 if (!error.Success())
512 return;
513 target->SetExecutableModule(exe_module_sp, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000514 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000516}
517
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
519 bool added_to_set = false;
520 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
521 if (it == m_seen_initial_stop.end()) {
522 m_seen_initial_stop.insert(stop_tid);
523 added_to_set = true;
524 }
525 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000526}
527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
529 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000530}
531
532FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
534 lldb::tid_t tid) {
535 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000536}
537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538void ProcessFreeBSD::RefreshStateAfterStop() {
539 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
540 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
541 log->Printf("ProcessFreeBSD::%s(), message_queue size = %d", __FUNCTION__,
542 (int)m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 // This method used to only handle one message. Changing it to loop allows
547 // it to handle the case where we hit a breakpoint while handling a different
548 // breakpoint.
549 while (!m_message_queue.empty()) {
550 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 // Resolve the thread this message corresponds to and pass it along.
553 lldb::tid_t tid = message.GetTID();
554 if (log)
555 log->Printf(
556 "ProcessFreeBSD::%s(), message_queue size = %d, pid = %" PRIi64,
557 __FUNCTION__, (int)m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
562 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000563 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 thread->Notify(message);
565
566 if (message.GetKind() == ProcessMessage::eExitMessage) {
567 // FIXME: We should tell the user about this, but the limbo message is
568 // probably better for that.
569 if (log)
570 log->Printf("ProcessFreeBSD::%s() removing thread, tid = %" PRIi64,
571 __FUNCTION__, tid);
572
573 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
574
575 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
576 thread_sp.reset();
577 m_seen_initial_stop.erase(tid);
578 }
579
580 m_message_queue.pop();
581 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000582}
583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584bool ProcessFreeBSD::IsAlive() {
585 StateType state = GetPrivateState();
586 return state != eStateDetached && state != eStateExited &&
587 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000588}
589
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
591 Error &error) {
592 assert(m_monitor);
593 return m_monitor->ReadMemory(vm_addr, buf, size, error);
594}
595
596size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
597 size_t size, Error &error) {
598 assert(m_monitor);
599 return m_monitor->WriteMemory(vm_addr, buf, size, error);
600}
601
602addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
603 Error &error) {
604 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
605
606 unsigned prot = 0;
607 if (permissions & lldb::ePermissionsReadable)
608 prot |= eMmapProtRead;
609 if (permissions & lldb::ePermissionsWritable)
610 prot |= eMmapProtWrite;
611 if (permissions & lldb::ePermissionsExecutable)
612 prot |= eMmapProtExec;
613
614 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
615 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
616 m_addr_to_mmap_size[allocated_addr] = size;
617 error.Clear();
618 } else {
619 allocated_addr = LLDB_INVALID_ADDRESS;
620 error.SetErrorStringWithFormat(
621 "unable to allocate %zu bytes of memory with permissions %s", size,
622 GetPermissionsAsCString(permissions));
623 }
624
625 return allocated_addr;
626}
627
628Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
629 Error error;
630 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
631 if (pos != m_addr_to_mmap_size.end() &&
632 InferiorCallMunmap(this, addr, pos->second))
633 m_addr_to_mmap_size.erase(pos);
634 else
635 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
636 addr);
637
638 return error;
639}
640
641size_t
642ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
643 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
644 static const uint8_t g_i386_opcode[] = {0xCC};
645
646 ArchSpec arch = GetTarget().GetArchitecture();
647 const uint8_t *opcode = NULL;
648 size_t opcode_size = 0;
649
650 switch (arch.GetMachine()) {
651 default:
652 assert(false && "CPU type not supported!");
653 break;
654
655 case llvm::Triple::arm: {
656 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
657 // but the linux kernel does otherwise.
658 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
659 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
660
661 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
662 AddressClass addr_class = eAddressClassUnknown;
663
664 if (bp_loc_sp)
665 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
666
667 if (addr_class == eAddressClassCodeAlternateISA ||
668 (addr_class == eAddressClassUnknown &&
669 bp_loc_sp->GetAddress().GetOffset() & 1)) {
670 opcode = g_thumb_breakpoint_opcode;
671 opcode_size = sizeof(g_thumb_breakpoint_opcode);
672 } else {
673 opcode = g_arm_breakpoint_opcode;
674 opcode_size = sizeof(g_arm_breakpoint_opcode);
675 }
676 } break;
677 case llvm::Triple::aarch64:
678 opcode = g_aarch64_opcode;
679 opcode_size = sizeof(g_aarch64_opcode);
680 break;
681
682 case llvm::Triple::x86:
683 case llvm::Triple::x86_64:
684 opcode = g_i386_opcode;
685 opcode_size = sizeof(g_i386_opcode);
686 break;
687 }
688
689 bp_site->SetTrapOpcode(opcode, opcode_size);
690 return opcode_size;
691}
692
693Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
694 return EnableSoftwareBreakpoint(bp_site);
695}
696
697Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
698 return DisableSoftwareBreakpoint(bp_site);
699}
700
701Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
702 Error error;
703 if (wp) {
704 user_id_t watchID = wp->GetID();
705 addr_t addr = wp->GetLoadAddress();
706 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
707 if (log)
708 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
709 watchID);
710 if (wp->IsEnabled()) {
711 if (log)
712 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
713 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
714 watchID, (uint64_t)addr);
715 return error;
716 }
717
718 // Try to find a vacant watchpoint slot in the inferiors' main thread
719 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000720 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
722 m_thread_list.GetThreadAtIndex(0, false).get());
723
724 if (thread)
725 wp_hw_index = thread->FindVacantWatchpointIndex();
726
727 if (wp_hw_index == LLDB_INVALID_INDEX32) {
728 error.SetErrorString("Setting hardware watchpoint failed.");
729 } else {
730 wp->SetHardwareIndex(wp_hw_index);
731 bool wp_enabled = true;
732 uint32_t thread_count = m_thread_list.GetSize(false);
733 for (uint32_t i = 0; i < thread_count; ++i) {
734 thread = static_cast<FreeBSDThread *>(
735 m_thread_list.GetThreadAtIndex(i, false).get());
736 if (thread)
737 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
738 else
739 wp_enabled = false;
740 }
741 if (wp_enabled) {
742 wp->SetEnabled(true, notify);
743 return error;
744 } else {
745 // Watchpoint enabling failed on at least one
746 // of the threads so roll back all of them
747 DisableWatchpoint(wp, false);
748 error.SetErrorString("Setting hardware watchpoint failed");
749 }
750 }
751 } else
752 error.SetErrorString("Watchpoint argument was NULL.");
753 return error;
754}
755
756Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
757 Error error;
758 if (wp) {
759 user_id_t watchID = wp->GetID();
760 addr_t addr = wp->GetLoadAddress();
761 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
762 if (log)
763 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
764 watchID);
765 if (!wp->IsEnabled()) {
766 if (log)
767 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
768 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
769 watchID, (uint64_t)addr);
770 // This is needed (for now) to keep watchpoints disabled correctly
771 wp->SetEnabled(false, notify);
772 return error;
773 }
774
775 if (wp->IsHardware()) {
776 bool wp_disabled = true;
777 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
778 uint32_t thread_count = m_thread_list.GetSize(false);
779 for (uint32_t i = 0; i < thread_count; ++i) {
780 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
781 m_thread_list.GetThreadAtIndex(i, false).get());
782 if (thread)
783 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
784 else
785 wp_disabled = false;
786 }
787 if (wp_disabled) {
788 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
789 wp->SetEnabled(false, notify);
790 return error;
791 } else
792 error.SetErrorString("Disabling hardware watchpoint failed");
793 }
794 } else
795 error.SetErrorString("Watchpoint argument was NULL.");
796 return error;
797}
798
799Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
800 Error error;
801 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
802 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
803 m_thread_list.GetThreadAtIndex(0, false).get());
804 if (thread)
805 num = thread->NumSupportedHardwareWatchpoints();
806 else
807 error.SetErrorString("Process does not exist.");
808 return error;
809}
810
811Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
812 Error error = GetWatchpointSupportInfo(num);
813 // Watchpoints trigger and halt the inferior after
814 // the corresponding instruction has been executed.
815 after = true;
816 return error;
817}
818
819uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
820 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
821 // Do not allow recursive updates.
822 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000823}
824
825#if 0
826bool
827ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
828{
829 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
830 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
831 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
832
833 bool has_updated = false;
834 // Update the process thread list with this new thread.
835 // FIXME: We should be using tid, not pid.
836 assert(m_monitor);
837 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
838 if (!thread_sp) {
839 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
840 has_updated = true;
841 }
842
843 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
844 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
845 new_thread_list.AddThread(thread_sp);
846
847 return has_updated; // the list has been updated
848}
849#endif
850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851ByteOrder ProcessFreeBSD::GetByteOrder() const {
852 // FIXME: We should be able to extract this value directly. See comment in
853 // ProcessFreeBSD().
854 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000855}
856
Kate Stoneb9c1b512016-09-06 20:57:50 +0000857size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) {
858 ssize_t status;
859 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
860 error.SetErrorToErrno();
861 return 0;
862 }
863 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000864}
865
866//------------------------------------------------------------------------------
867// Utility functions.
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869bool ProcessFreeBSD::HasExited() {
870 switch (GetPrivateState()) {
871 default:
872 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000873
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 case eStateDetached:
875 case eStateExited:
876 return true;
877 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000880}
881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882bool ProcessFreeBSD::IsStopped() {
883 switch (GetPrivateState()) {
884 default:
885 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 case eStateStopped:
888 case eStateCrashed:
889 case eStateSuspended:
890 return true;
891 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000892
Kate Stoneb9c1b512016-09-06 20:57:50 +0000893 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000894}
895
Kate Stoneb9c1b512016-09-06 20:57:50 +0000896bool ProcessFreeBSD::IsAThreadRunning() {
897 bool is_running = false;
898 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
899 uint32_t thread_count = m_thread_list.GetSize(false);
900 for (uint32_t i = 0; i < thread_count; ++i) {
901 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
902 m_thread_list.GetThreadAtIndex(i, false).get());
903 StateType thread_state = thread->GetState();
904 if (thread_state == eStateRunning || thread_state == eStateStepping) {
905 is_running = true;
906 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000907 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 }
909 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000910}
911
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912const DataBufferSP ProcessFreeBSD::GetAuxvData() {
913 // If we're the local platform, we can ask the host for auxv data.
914 PlatformSP platform_sp = GetTarget().GetPlatform();
915 if (platform_sp && platform_sp->IsHost())
916 return lldb_private::Host::GetAuxvData(this);
Ed Mastefe5a6422015-07-28 15:45:57 +0000917
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 // Somewhat unexpected - the process is not running locally or we don't have a
919 // platform.
920 assert(
921 false &&
922 "no platform or not the host - how did we get here with ProcessFreeBSD?");
923 return DataBufferSP();
Ed Mastefe5a6422015-07-28 15:45:57 +0000924}
Ed Maste31f01802017-01-24 14:34:49 +0000925
926struct EmulatorBaton {
927 ProcessFreeBSD *m_process;
928 RegisterContext *m_reg_context;
929
930 // eRegisterKindDWARF -> RegisterValue
931 std::unordered_map<uint32_t, RegisterValue> m_register_values;
932
933 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
934 : m_process(process), m_reg_context(reg_context) {}
935};
936
937static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
938 const EmulateInstruction::Context &context,
939 lldb::addr_t addr, void *dst, size_t length) {
940 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
941
942 Error error;
943 size_t bytes_read =
944 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
945 if (!error.Success())
946 bytes_read = 0;
947 return bytes_read;
948}
949
950static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
951 const RegisterInfo *reg_info,
952 RegisterValue &reg_value) {
953 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
954
955 auto it = emulator_baton->m_register_values.find(
956 reg_info->kinds[eRegisterKindDWARF]);
957 if (it != emulator_baton->m_register_values.end()) {
958 reg_value = it->second;
959 return true;
960 }
961
962 // The emulator only fills in the dwarf register numbers (and in some cases
963 // the generic register numbers). Get the full register info from the
964 // register context based on the dwarf register numbers.
965 const RegisterInfo *full_reg_info =
966 emulator_baton->m_reg_context->GetRegisterInfo(
967 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
968
969 bool error =
970 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
971 return error;
972}
973
974static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
975 const EmulateInstruction::Context &context,
976 const RegisterInfo *reg_info,
977 const RegisterValue &reg_value) {
978 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
979 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
980 reg_value;
981 return true;
982}
983
984static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
985 const EmulateInstruction::Context &context,
986 lldb::addr_t addr, const void *dst,
987 size_t length) {
988 return length;
989}
990
991bool ProcessFreeBSD::SingleStepBreakpointHit(
992 void *baton, lldb_private::StoppointCallbackContext *context,
993 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
994 return false;
995}
996
997Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
998 lldb::addr_t addr) {
999 Error error;
1000
1001 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1002 if (log) {
1003 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1004 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1005 }
1006
1007 // Validate the address.
1008 if (addr == LLDB_INVALID_ADDRESS)
1009 return Error("ProcessFreeBSD::%s invalid load address specified.",
1010 __FUNCTION__);
1011
1012 Breakpoint *const sw_step_break =
1013 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
1014 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
1015 sw_step_break->SetBreakpointKind("software-signle-step");
1016
1017 if (log)
1018 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1019 __FUNCTION__, addr);
1020
1021 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1022 return Error();
1023}
1024
1025bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1026 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1027 if (!thread)
1028 return false;
1029
1030 assert(thread->GetRegisterContext());
1031 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1032
1033 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1034 if (iter == m_threads_stepping_with_breakpoint.end())
1035 return false;
1036
1037 lldb::break_id_t bp_id = iter->second;
1038 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1039 if (!bp)
1040 return false;
1041
1042 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1043 if (!bp_loc)
1044 return false;
1045
1046 GetTarget().RemoveBreakpointByID(bp_id);
1047 m_threads_stepping_with_breakpoint.erase(tid);
1048 return true;
1049}
1050
1051bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1052 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1053 if (arch.GetMachine() == llvm::Triple::arm ||
1054 arch.GetMachine() == llvm::Triple::mips64 ||
1055 arch.GetMachine() == llvm::Triple::mips64el ||
1056 arch.GetMachine() == llvm::Triple::mips ||
1057 arch.GetMachine() == llvm::Triple::mipsel)
1058 return false;
1059 return true;
1060}
1061
1062Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1063 std::unique_ptr<EmulateInstruction> emulator_ap(
1064 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1065 eInstructionTypePCModifying, nullptr));
1066
1067 if (emulator_ap == nullptr)
1068 return Error("Instruction emulator not found!");
1069
1070 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1071 m_thread_list.FindThreadByID(tid, false).get());
1072 if (thread == NULL)
1073 return Error("Thread not found not found!");
1074
1075 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1076
1077 EmulatorBaton baton(this, register_context_sp.get());
1078 emulator_ap->SetBaton(&baton);
1079 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1080 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1081 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1082 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1083
1084 if (!emulator_ap->ReadInstruction())
1085 return Error("Read instruction failed!");
1086
1087 bool emulation_result =
1088 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1089 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1090 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1091 auto pc_it =
1092 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1093
1094 lldb::addr_t next_pc;
1095 if (emulation_result) {
1096 assert(pc_it != baton.m_register_values.end() &&
1097 "Emulation was successful but PC wasn't updated");
1098 next_pc = pc_it->second.GetAsUInt64();
1099 } else if (pc_it == baton.m_register_values.end()) {
1100 // Emulate instruction failed and it haven't changed PC. Advance PC
1101 // with the size of the current opcode because the emulation of all
1102 // PC modifying instruction should be successful. The failure most
1103 // likely caused by a not supported instruction which don't modify PC.
1104 next_pc =
1105 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1106 } else {
1107 // The instruction emulation failed after it modified the PC. It is an
1108 // unknown error where we can't continue because the next instruction is
1109 // modifying the PC but we don't know how.
1110 return Error("Instruction emulation failed unexpectedly");
1111 }
1112
1113 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1114 return Error();
1115}