blob: f0a62e85458f70f2509e418c640d609c5a2a4979 [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);
Kate Stoneb9c1b512016-09-06 20:57:50 +000081 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000082}
83
Kate Stoneb9c1b512016-09-06 20:57:50 +000084lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
85 static ConstString g_name("freebsd");
86 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000087}
88
Kate Stoneb9c1b512016-09-06 20:57:50 +000089const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
90 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000091}
92
93//------------------------------------------------------------------------------
94// ProcessInterface protocol.
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
97 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +000098}
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104Error ProcessFreeBSD::DoDetach(bool keep_stopped) {
105 Error error;
106 if (keep_stopped) {
107 error.SetErrorString("Detaching with keep_stopped true is not currently "
108 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000109 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 }
111
112 error = m_monitor->Detach(GetID());
113
114 if (error.Success())
115 SetPrivateState(eStateDetached);
116
117 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000118}
119
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120Error ProcessFreeBSD::DoResume() {
121 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000122
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
126 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000127 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
130 t_end = m_run_tids.end();
131 t_pos != t_end; ++t_pos) {
132 m_monitor->ThreadSuspend(*t_pos, false);
133 }
134 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
135 t_end = m_step_tids.end();
136 t_pos != t_end; ++t_pos) {
137 m_monitor->ThreadSuspend(*t_pos, false);
138 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000139 if (software_single_step) {
140 Error error = SetupSoftwareSingleStepping(*t_pos);
141 if (error.Fail())
142 return error;
143 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 }
145 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
146 t_end = m_suspend_tids.end();
147 t_pos != t_end; ++t_pos) {
148 m_monitor->ThreadSuspend(*t_pos, true);
149 // XXX Cannot PT_CONTINUE properly with suspended threads.
150 do_step = true;
151 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 if (log)
154 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
155 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000156 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 m_monitor->SingleStep(GetID(), m_resume_signo);
158 else
159 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000160
Mehdi Amini665be502016-11-11 05:07:57 +0000161 return Error();
Ed Maste7fd845c2013-12-09 15:51:17 +0000162}
163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
165 ThreadList &new_thread_list) {
166 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
167 if (log)
168 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
169 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171 std::vector<lldb::pid_t> tds;
172 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
173 return false;
174 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000175
Kate Stoneb9c1b512016-09-06 20:57:50 +0000176 ThreadList old_thread_list_copy(old_thread_list);
177 for (size_t i = 0; i < tds.size(); ++i) {
178 tid_t tid = tds[i];
179 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
180 if (!thread_sp) {
181 thread_sp.reset(new FreeBSDThread(*this, tid));
182 if (log)
183 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
184 } else {
185 if (log)
186 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
187 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000188 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189 new_thread_list.AddThread(thread_sp);
190 }
191 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
192 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
193 if (old_thread_sp) {
194 if (log)
195 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000196 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000200}
Ed Maste7fd845c2013-12-09 15:51:17 +0000201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202Error 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();
Ed Maste7fd845c2013-12-09 15:51:17 +0000208}
209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
211 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 switch (message.GetKind()) {
214 case ProcessMessage::eInvalidMessage:
215 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 case ProcessMessage::eAttachMessage:
218 SetPrivateState(eStateStopped);
219 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 case ProcessMessage::eLimboMessage:
222 case ProcessMessage::eExitMessage:
223 SetExitStatus(message.GetExitStatus(), NULL);
224 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 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;
Ed Maste7fd845c2013-12-09 15:51:17 +0000234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235 case ProcessMessage::eNewThreadMessage:
236 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
237 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 case ProcessMessage::eExecMessage:
240 SetPrivateState(eStateStopped);
241 break;
242 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000245}
Ed Mastefe5a6422015-07-28 15:45:57 +0000246
247//------------------------------------------------------------------------------
248// Constructors and destructors.
249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
251 lldb::ListenerSP listener_sp,
252 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000253 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
255 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
256 m_resume_signo(0) {
257 // FIXME: Putting this code in the ctor and saving the byte order in a
258 // member variable is a hack to avoid const qual issues in GetByteOrder.
259 lldb::ModuleSP module = GetTarget().GetExecutableModule();
260 if (module && module->GetObjectFile())
261 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000262}
263
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000265
266//------------------------------------------------------------------------------
267// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000269 Process::Finalize();
270
271 if (m_monitor)
272 m_monitor->StopMonitor();
273}
274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275bool 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 exe_module_sp->GetFileSpec().Exists();
281 // If there is no executable module, we return true since we might be
282 // preparing to attach.
283 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000284}
285
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286Error ProcessFreeBSD::DoAttachToProcessWithID(
287 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
288 Error error;
289 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000290
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000292 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000297 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298
299 PlatformSP platform_sp(GetTarget().GetPlatform());
300 assert(platform_sp.get());
301 if (!platform_sp)
302 return error; // FIXME: Detatch?
303
304 // Find out what we can about this process
305 ProcessInstanceInfo process_info;
306 platform_sp->GetProcessInfo(pid, process_info);
307
308 // Resolve the executable module
309 ModuleSP exe_module_sp;
310 FileSpecList executable_search_paths(
311 Target::GetDefaultExecutableSearchPaths());
312 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
313 GetTarget().GetArchitecture());
314 error = platform_sp->ResolveExecutable(
315 exe_module_spec, exe_module_sp,
316 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
317 if (!error.Success())
318 return error;
319
320 // Fix the target architecture if necessary
321 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
322 if (module_arch.IsValid() &&
323 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
324 GetTarget().SetArchitecture(module_arch);
325
326 // Initialize the target module list
327 GetTarget().SetExecutableModule(exe_module_sp, true);
328
329 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
330
331 SetID(pid);
332
333 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000334}
335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336Error ProcessFreeBSD::WillLaunch(Module *module) {
337 Error error;
338 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000339}
340
341FileSpec
342ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 const FileSpec &default_file_spec,
344 const FileSpec &dbg_pts_file_spec) {
345 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
348 file_spec = file_action->GetFileSpec();
349 // By default the stdio paths passed in will be pseudo-terminal
350 // (/dev/pts). If so, convert to using a different default path
351 // instead to redirect I/O to the debugger console. This should
352 // also handle user overrides to /dev/null or a different file.
353 if (!file_spec || file_spec == dbg_pts_file_spec)
354 file_spec = default_file_spec;
355 }
356 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000357}
358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) {
360 Error error;
361 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000362
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 FileSpec working_dir = launch_info.GetWorkingDirectory();
Pavel Labath30e6cbf2017-03-07 13:19:15 +0000364 if (working_dir &&
365 (!working_dir.ResolvePath() ||
366 working_dir.GetFileType() != FileSpec::eFileTypeDirectory)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 error.SetErrorStringWithFormat("No such file or directory: %s",
368 working_dir.GetCString());
369 return error;
370 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000373
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 // Default of empty will mean to use existing open file descriptors
377 FileSpec stdin_file_spec{};
378 FileSpec stdout_file_spec{};
379 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
382 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
385 stdin_file_spec =
386 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
389 stdout_file_spec =
390 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
393 stderr_file_spec =
394 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 m_monitor = new ProcessMonitor(
397 this, module, launch_info.GetArguments().GetConstArgumentVector(),
398 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
399 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
400 launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 if (!error.Success())
405 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 int terminal = m_monitor->GetTerminalFD();
408 if (terminal >= 0) {
409// The reader thread will close the file descriptor when done, so we pass it a
410// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000411#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
413 if (stdio == -1) {
414 error.SetErrorToErrno();
415 return error;
416 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000417#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
419 int stdio = fcntl(terminal, F_DUPFD, 0);
420 if (stdio == -1) {
421 error.SetErrorToErrno();
422 return error;
423 }
424 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
425 if (stdio == -1) {
426 error.SetErrorToErrno();
427 return error;
428 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000429#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 SetSTDIOFileDescriptor(stdio);
431 }
432
433 SetID(m_monitor->GetPID());
434 return error;
435}
436
437void ProcessFreeBSD::DidLaunch() {}
438
439addr_t ProcessFreeBSD::GetImageInfoAddress() {
440 Target *target = &GetTarget();
441 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
442 Address addr = obj_file->GetImageInfoAddress(target);
443
444 if (addr.IsValid())
445 return addr.GetLoadAddress(target);
446 return LLDB_INVALID_ADDRESS;
447}
448
449Error ProcessFreeBSD::DoHalt(bool &caused_stop) {
450 Error error;
451
452 if (IsStopped()) {
453 caused_stop = false;
454 } else if (kill(GetID(), SIGSTOP)) {
455 caused_stop = false;
456 error.SetErrorToErrno();
457 } else {
458 caused_stop = true;
459 }
460 return error;
461}
462
463Error ProcessFreeBSD::DoSignal(int signal) {
464 Error error;
465
466 if (kill(GetID(), signal))
467 error.SetErrorToErrno();
468
469 return error;
470}
471
472Error ProcessFreeBSD::DoDestroy() {
473 Error error;
474
475 if (!HasExited()) {
476 assert(m_monitor);
477 m_exit_now = true;
478 if (GetID() == LLDB_INVALID_PROCESS_ID) {
479 error.SetErrorString("invalid process id");
480 return error;
481 }
482 if (!m_monitor->Kill()) {
483 error.SetErrorToErrno();
484 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000485 }
486
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487 SetPrivateState(eStateExited);
488 }
489
490 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000491}
492
Kate Stoneb9c1b512016-09-06 20:57:50 +0000493void ProcessFreeBSD::DoDidExec() {
494 Target *target = &GetTarget();
495 if (target) {
496 PlatformSP platform_sp(target->GetPlatform());
497 assert(platform_sp.get());
498 if (platform_sp) {
499 ProcessInstanceInfo process_info;
500 platform_sp->GetProcessInfo(GetID(), process_info);
501 ModuleSP exe_module_sp;
502 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
503 target->GetArchitecture());
504 FileSpecList executable_search_paths(
505 Target::GetDefaultExecutableSearchPaths());
506 Error error = platform_sp->ResolveExecutable(
507 exe_module_spec, exe_module_sp,
508 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
509 if (!error.Success())
510 return;
511 target->SetExecutableModule(exe_module_sp, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000512 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000513 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000514}
515
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
517 bool added_to_set = false;
518 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
519 if (it == m_seen_initial_stop.end()) {
520 m_seen_initial_stop.insert(stop_tid);
521 added_to_set = true;
522 }
523 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000524}
525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
527 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000528}
529
530FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000531ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
532 lldb::tid_t tid) {
533 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000534}
535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536void ProcessFreeBSD::RefreshStateAfterStop() {
537 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000538 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000539
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000541
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542 // This method used to only handle one message. Changing it to loop allows
543 // it to handle the case where we hit a breakpoint while handling a different
544 // breakpoint.
545 while (!m_message_queue.empty()) {
546 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 // Resolve the thread this message corresponds to and pass it along.
549 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000550 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
551 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
556 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000557 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 thread->Notify(message);
559
560 if (message.GetKind() == ProcessMessage::eExitMessage) {
561 // FIXME: We should tell the user about this, but the limbo message is
562 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000563 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
565
566 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
567 thread_sp.reset();
568 m_seen_initial_stop.erase(tid);
569 }
570
571 m_message_queue.pop();
572 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000573}
574
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575bool ProcessFreeBSD::IsAlive() {
576 StateType state = GetPrivateState();
577 return state != eStateDetached && state != eStateExited &&
578 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000579}
580
Kate Stoneb9c1b512016-09-06 20:57:50 +0000581size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
582 Error &error) {
583 assert(m_monitor);
584 return m_monitor->ReadMemory(vm_addr, buf, size, error);
585}
586
587size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
588 size_t size, Error &error) {
589 assert(m_monitor);
590 return m_monitor->WriteMemory(vm_addr, buf, size, error);
591}
592
593addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
594 Error &error) {
595 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
596
597 unsigned prot = 0;
598 if (permissions & lldb::ePermissionsReadable)
599 prot |= eMmapProtRead;
600 if (permissions & lldb::ePermissionsWritable)
601 prot |= eMmapProtWrite;
602 if (permissions & lldb::ePermissionsExecutable)
603 prot |= eMmapProtExec;
604
605 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
606 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
607 m_addr_to_mmap_size[allocated_addr] = size;
608 error.Clear();
609 } else {
610 allocated_addr = LLDB_INVALID_ADDRESS;
611 error.SetErrorStringWithFormat(
612 "unable to allocate %zu bytes of memory with permissions %s", size,
613 GetPermissionsAsCString(permissions));
614 }
615
616 return allocated_addr;
617}
618
619Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
620 Error error;
621 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
622 if (pos != m_addr_to_mmap_size.end() &&
623 InferiorCallMunmap(this, addr, pos->second))
624 m_addr_to_mmap_size.erase(pos);
625 else
626 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
627 addr);
628
629 return error;
630}
631
632size_t
633ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
634 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
635 static const uint8_t g_i386_opcode[] = {0xCC};
636
637 ArchSpec arch = GetTarget().GetArchitecture();
638 const uint8_t *opcode = NULL;
639 size_t opcode_size = 0;
640
641 switch (arch.GetMachine()) {
642 default:
643 assert(false && "CPU type not supported!");
644 break;
645
646 case llvm::Triple::arm: {
647 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
648 // but the linux kernel does otherwise.
649 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
650 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
651
652 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
653 AddressClass addr_class = eAddressClassUnknown;
654
655 if (bp_loc_sp)
656 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
657
658 if (addr_class == eAddressClassCodeAlternateISA ||
659 (addr_class == eAddressClassUnknown &&
660 bp_loc_sp->GetAddress().GetOffset() & 1)) {
661 opcode = g_thumb_breakpoint_opcode;
662 opcode_size = sizeof(g_thumb_breakpoint_opcode);
663 } else {
664 opcode = g_arm_breakpoint_opcode;
665 opcode_size = sizeof(g_arm_breakpoint_opcode);
666 }
667 } break;
668 case llvm::Triple::aarch64:
669 opcode = g_aarch64_opcode;
670 opcode_size = sizeof(g_aarch64_opcode);
671 break;
672
673 case llvm::Triple::x86:
674 case llvm::Triple::x86_64:
675 opcode = g_i386_opcode;
676 opcode_size = sizeof(g_i386_opcode);
677 break;
678 }
679
680 bp_site->SetTrapOpcode(opcode, opcode_size);
681 return opcode_size;
682}
683
684Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
685 return EnableSoftwareBreakpoint(bp_site);
686}
687
688Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
689 return DisableSoftwareBreakpoint(bp_site);
690}
691
692Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
693 Error error;
694 if (wp) {
695 user_id_t watchID = wp->GetID();
696 addr_t addr = wp->GetLoadAddress();
697 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
698 if (log)
699 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
700 watchID);
701 if (wp->IsEnabled()) {
702 if (log)
703 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
704 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
705 watchID, (uint64_t)addr);
706 return error;
707 }
708
709 // Try to find a vacant watchpoint slot in the inferiors' main thread
710 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000711 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
713 m_thread_list.GetThreadAtIndex(0, false).get());
714
715 if (thread)
716 wp_hw_index = thread->FindVacantWatchpointIndex();
717
718 if (wp_hw_index == LLDB_INVALID_INDEX32) {
719 error.SetErrorString("Setting hardware watchpoint failed.");
720 } else {
721 wp->SetHardwareIndex(wp_hw_index);
722 bool wp_enabled = true;
723 uint32_t thread_count = m_thread_list.GetSize(false);
724 for (uint32_t i = 0; i < thread_count; ++i) {
725 thread = static_cast<FreeBSDThread *>(
726 m_thread_list.GetThreadAtIndex(i, false).get());
727 if (thread)
728 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
729 else
730 wp_enabled = false;
731 }
732 if (wp_enabled) {
733 wp->SetEnabled(true, notify);
734 return error;
735 } else {
736 // Watchpoint enabling failed on at least one
737 // of the threads so roll back all of them
738 DisableWatchpoint(wp, false);
739 error.SetErrorString("Setting hardware watchpoint failed");
740 }
741 }
742 } else
743 error.SetErrorString("Watchpoint argument was NULL.");
744 return error;
745}
746
747Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
748 Error error;
749 if (wp) {
750 user_id_t watchID = wp->GetID();
751 addr_t addr = wp->GetLoadAddress();
752 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
753 if (log)
754 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
755 watchID);
756 if (!wp->IsEnabled()) {
757 if (log)
758 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
759 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
760 watchID, (uint64_t)addr);
761 // This is needed (for now) to keep watchpoints disabled correctly
762 wp->SetEnabled(false, notify);
763 return error;
764 }
765
766 if (wp->IsHardware()) {
767 bool wp_disabled = true;
768 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
769 uint32_t thread_count = m_thread_list.GetSize(false);
770 for (uint32_t i = 0; i < thread_count; ++i) {
771 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
772 m_thread_list.GetThreadAtIndex(i, false).get());
773 if (thread)
774 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
775 else
776 wp_disabled = false;
777 }
778 if (wp_disabled) {
779 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
780 wp->SetEnabled(false, notify);
781 return error;
782 } else
783 error.SetErrorString("Disabling hardware watchpoint failed");
784 }
785 } else
786 error.SetErrorString("Watchpoint argument was NULL.");
787 return error;
788}
789
790Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
791 Error error;
792 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
793 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
794 m_thread_list.GetThreadAtIndex(0, false).get());
795 if (thread)
796 num = thread->NumSupportedHardwareWatchpoints();
797 else
798 error.SetErrorString("Process does not exist.");
799 return error;
800}
801
802Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
803 Error error = GetWatchpointSupportInfo(num);
804 // Watchpoints trigger and halt the inferior after
805 // the corresponding instruction has been executed.
806 after = true;
807 return error;
808}
809
810uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
811 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
812 // Do not allow recursive updates.
813 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000814}
815
816#if 0
817bool
818ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
819{
820 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
821 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
822 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
823
824 bool has_updated = false;
825 // Update the process thread list with this new thread.
826 // FIXME: We should be using tid, not pid.
827 assert(m_monitor);
828 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
829 if (!thread_sp) {
830 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
831 has_updated = true;
832 }
833
834 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
835 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
836 new_thread_list.AddThread(thread_sp);
837
838 return has_updated; // the list has been updated
839}
840#endif
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842ByteOrder ProcessFreeBSD::GetByteOrder() const {
843 // FIXME: We should be able to extract this value directly. See comment in
844 // ProcessFreeBSD().
845 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000846}
847
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) {
849 ssize_t status;
850 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
851 error.SetErrorToErrno();
852 return 0;
853 }
854 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000855}
856
857//------------------------------------------------------------------------------
858// Utility functions.
859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860bool ProcessFreeBSD::HasExited() {
861 switch (GetPrivateState()) {
862 default:
863 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000864
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 case eStateDetached:
866 case eStateExited:
867 return true;
868 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000871}
872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873bool ProcessFreeBSD::IsStopped() {
874 switch (GetPrivateState()) {
875 default:
876 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000877
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 case eStateStopped:
879 case eStateCrashed:
880 case eStateSuspended:
881 return true;
882 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000885}
886
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887bool ProcessFreeBSD::IsAThreadRunning() {
888 bool is_running = false;
889 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
890 uint32_t thread_count = m_thread_list.GetSize(false);
891 for (uint32_t i = 0; i < thread_count; ++i) {
892 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
893 m_thread_list.GetThreadAtIndex(i, false).get());
894 StateType thread_state = thread->GetState();
895 if (thread_state == eStateRunning || thread_state == eStateStepping) {
896 is_running = true;
897 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000898 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 }
900 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000901}
902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903const DataBufferSP ProcessFreeBSD::GetAuxvData() {
904 // If we're the local platform, we can ask the host for auxv data.
905 PlatformSP platform_sp = GetTarget().GetPlatform();
906 if (platform_sp && platform_sp->IsHost())
907 return lldb_private::Host::GetAuxvData(this);
Ed Mastefe5a6422015-07-28 15:45:57 +0000908
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 // Somewhat unexpected - the process is not running locally or we don't have a
910 // platform.
911 assert(
912 false &&
913 "no platform or not the host - how did we get here with ProcessFreeBSD?");
914 return DataBufferSP();
Ed Mastefe5a6422015-07-28 15:45:57 +0000915}
Ed Maste31f01802017-01-24 14:34:49 +0000916
917struct EmulatorBaton {
918 ProcessFreeBSD *m_process;
919 RegisterContext *m_reg_context;
920
921 // eRegisterKindDWARF -> RegisterValue
922 std::unordered_map<uint32_t, RegisterValue> m_register_values;
923
924 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
925 : m_process(process), m_reg_context(reg_context) {}
926};
927
928static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
929 const EmulateInstruction::Context &context,
930 lldb::addr_t addr, void *dst, size_t length) {
931 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
932
933 Error error;
934 size_t bytes_read =
935 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
936 if (!error.Success())
937 bytes_read = 0;
938 return bytes_read;
939}
940
941static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
942 const RegisterInfo *reg_info,
943 RegisterValue &reg_value) {
944 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
945
946 auto it = emulator_baton->m_register_values.find(
947 reg_info->kinds[eRegisterKindDWARF]);
948 if (it != emulator_baton->m_register_values.end()) {
949 reg_value = it->second;
950 return true;
951 }
952
953 // The emulator only fills in the dwarf register numbers (and in some cases
954 // the generic register numbers). Get the full register info from the
955 // register context based on the dwarf register numbers.
956 const RegisterInfo *full_reg_info =
957 emulator_baton->m_reg_context->GetRegisterInfo(
958 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
959
960 bool error =
961 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
962 return error;
963}
964
965static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
966 const EmulateInstruction::Context &context,
967 const RegisterInfo *reg_info,
968 const RegisterValue &reg_value) {
969 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
970 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
971 reg_value;
972 return true;
973}
974
975static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
976 const EmulateInstruction::Context &context,
977 lldb::addr_t addr, const void *dst,
978 size_t length) {
979 return length;
980}
981
982bool ProcessFreeBSD::SingleStepBreakpointHit(
983 void *baton, lldb_private::StoppointCallbackContext *context,
984 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
985 return false;
986}
987
988Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
989 lldb::addr_t addr) {
990 Error error;
991
992 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
993 if (log) {
994 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
995 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
996 }
997
998 // Validate the address.
999 if (addr == LLDB_INVALID_ADDRESS)
1000 return Error("ProcessFreeBSD::%s invalid load address specified.",
1001 __FUNCTION__);
1002
1003 Breakpoint *const sw_step_break =
1004 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
1005 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
1006 sw_step_break->SetBreakpointKind("software-signle-step");
1007
1008 if (log)
1009 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1010 __FUNCTION__, addr);
1011
1012 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1013 return Error();
1014}
1015
1016bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1017 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1018 if (!thread)
1019 return false;
1020
1021 assert(thread->GetRegisterContext());
1022 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1023
1024 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1025 if (iter == m_threads_stepping_with_breakpoint.end())
1026 return false;
1027
1028 lldb::break_id_t bp_id = iter->second;
1029 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1030 if (!bp)
1031 return false;
1032
1033 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1034 if (!bp_loc)
1035 return false;
1036
1037 GetTarget().RemoveBreakpointByID(bp_id);
1038 m_threads_stepping_with_breakpoint.erase(tid);
1039 return true;
1040}
1041
1042bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1043 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1044 if (arch.GetMachine() == llvm::Triple::arm ||
1045 arch.GetMachine() == llvm::Triple::mips64 ||
1046 arch.GetMachine() == llvm::Triple::mips64el ||
1047 arch.GetMachine() == llvm::Triple::mips ||
1048 arch.GetMachine() == llvm::Triple::mipsel)
1049 return false;
1050 return true;
1051}
1052
1053Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1054 std::unique_ptr<EmulateInstruction> emulator_ap(
1055 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1056 eInstructionTypePCModifying, nullptr));
1057
1058 if (emulator_ap == nullptr)
1059 return Error("Instruction emulator not found!");
1060
1061 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1062 m_thread_list.FindThreadByID(tid, false).get());
1063 if (thread == NULL)
1064 return Error("Thread not found not found!");
1065
1066 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1067
1068 EmulatorBaton baton(this, register_context_sp.get());
1069 emulator_ap->SetBaton(&baton);
1070 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1071 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1072 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1073 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1074
1075 if (!emulator_ap->ReadInstruction())
1076 return Error("Read instruction failed!");
1077
1078 bool emulation_result =
1079 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1080 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1081 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1082 auto pc_it =
1083 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1084
1085 lldb::addr_t next_pc;
1086 if (emulation_result) {
1087 assert(pc_it != baton.m_register_values.end() &&
1088 "Emulation was successful but PC wasn't updated");
1089 next_pc = pc_it->second.GetAsUInt64();
1090 } else if (pc_it == baton.m_register_values.end()) {
1091 // Emulate instruction failed and it haven't changed PC. Advance PC
1092 // with the size of the current opcode because the emulation of all
1093 // PC modifying instruction should be successful. The failure most
1094 // likely caused by a not supported instruction which don't modify PC.
1095 next_pc =
1096 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1097 } else {
1098 // The instruction emulation failed after it modified the PC. It is an
1099 // unknown error where we can't continue because the next instruction is
1100 // modifying the PC but we don't know how.
1101 return Error("Instruction emulation failed unexpectedly");
1102 }
1103
1104 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1105 return Error();
1106}