blob: 1f02385d50d2de22d7cc4ca5a5b0347ed0988ce0 [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
Zachary Turner7d86ee52017-03-08 17:56:08 +000049#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000050#include "llvm/Support/Threading.h"
51
Johnny Chen9ed5b492012-01-05 21:48:15 +000052using namespace lldb;
53using namespace lldb_private;
54
Kate Stoneb9c1b512016-09-06 20:57:50 +000055namespace {
56UnixSignalsSP &GetFreeBSDSignals() {
57 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
58 return s_freebsd_signals_sp;
59}
Todd Fiala4ceced32014-08-29 17:35:57 +000060}
61
Johnny Chen9ed5b492012-01-05 21:48:15 +000062//------------------------------------------------------------------------------
63// Static functions.
64
Greg Clayton29d19302012-02-27 18:40:48 +000065lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000066ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000067 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 const FileSpec *crash_file_path) {
69 lldb::ProcessSP process_sp;
70 if (crash_file_path == NULL)
71 process_sp.reset(
72 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
73 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000074}
75
Kate Stoneb9c1b512016-09-06 20:57:50 +000076void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000077 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000078
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000079 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000080 PluginManager::RegisterPlugin(GetPluginNameStatic(),
81 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000082 });
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));
Pavel Labathaafe0532017-02-06 19:31:05 +0000293 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000294
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000296
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000298 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299
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, true);
329
330 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
331
332 SetID(pid);
333
334 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000335}
336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337Error ProcessFreeBSD::WillLaunch(Module *module) {
338 Error error;
339 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000340}
341
342FileSpec
343ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 const FileSpec &default_file_spec,
345 const FileSpec &dbg_pts_file_spec) {
346 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 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
351 // (/dev/pts). If so, convert to using a different default path
352 // instead to redirect I/O to the debugger console. This should
353 // also handle user overrides to /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;
Ed Mastefe5a6422015-07-28 15:45:57 +0000358}
359
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) {
361 Error error;
362 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000363
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 FileSpec working_dir = launch_info.GetWorkingDirectory();
Zachary Turner7d86ee52017-03-08 17:56:08 +0000365 namespace fs = llvm::sys::fs;
366 if (working_dir && (!working_dir.ResolvePath() ||
367 !fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 error.SetErrorStringWithFormat("No such file or directory: %s",
369 working_dir.GetCString());
370 return error;
371 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 // Default of empty will mean to use existing open file descriptors
378 FileSpec stdin_file_spec{};
379 FileSpec stdout_file_spec{};
380 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
383 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
386 stdin_file_spec =
387 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
390 stdout_file_spec =
391 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
394 stderr_file_spec =
395 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 m_monitor = new ProcessMonitor(
398 this, module, launch_info.GetArguments().GetConstArgumentVector(),
399 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
400 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
401 launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000402
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 if (!error.Success())
406 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 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.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000412#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
414 if (stdio == -1) {
415 error.SetErrorToErrno();
416 return error;
417 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000418#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 // 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 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000430#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 SetSTDIOFileDescriptor(stdio);
432 }
433
434 SetID(m_monitor->GetPID());
435 return error;
436}
437
438void ProcessFreeBSD::DidLaunch() {}
439
440addr_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
450Error ProcessFreeBSD::DoHalt(bool &caused_stop) {
451 Error 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
464Error ProcessFreeBSD::DoSignal(int signal) {
465 Error error;
466
467 if (kill(GetID(), signal))
468 error.SetErrorToErrno();
469
470 return error;
471}
472
473Error ProcessFreeBSD::DoDestroy() {
474 Error 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;
Ed Mastefe5a6422015-07-28 15:45:57 +0000486 }
487
Kate Stoneb9c1b512016-09-06 20:57:50 +0000488 SetPrivateState(eStateExited);
489 }
490
491 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000492}
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494void 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 Error 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, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000513 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000515}
516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517bool 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;
Ed Mastefe5a6422015-07-28 15:45:57 +0000525}
526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
528 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000529}
530
531FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
533 lldb::tid_t tid) {
534 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000535}
536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537void ProcessFreeBSD::RefreshStateAfterStop() {
538 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000539 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 // 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();
Ed Mastefe5a6422015-07-28 15:45:57 +0000548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549 // Resolve the thread this message corresponds to and pass it along.
550 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000551 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
552 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
557 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000558 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 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.
Pavel Labathaafe0532017-02-06 19:31:05 +0000564 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 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 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000574}
575
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576bool ProcessFreeBSD::IsAlive() {
577 StateType state = GetPrivateState();
578 return state != eStateDetached && state != eStateExited &&
579 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000580}
581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
583 Error &error) {
584 assert(m_monitor);
585 return m_monitor->ReadMemory(vm_addr, buf, size, error);
586}
587
588size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
589 size_t size, Error &error) {
590 assert(m_monitor);
591 return m_monitor->WriteMemory(vm_addr, buf, size, error);
592}
593
594addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
595 Error &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
620Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
621 Error 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
633size_t
634ProcessFreeBSD::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
649 // but the 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 = eAddressClassUnknown;
655
656 if (bp_loc_sp)
657 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
658
659 if (addr_class == eAddressClassCodeAlternateISA ||
660 (addr_class == eAddressClassUnknown &&
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
685Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
686 return EnableSoftwareBreakpoint(bp_site);
687}
688
689Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
690 return DisableSoftwareBreakpoint(bp_site);
691}
692
693Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
694 Error error;
695 if (wp) {
696 user_id_t watchID = wp->GetID();
697 addr_t addr = wp->GetLoadAddress();
698 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
699 if (log)
700 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
701 watchID);
702 if (wp->IsEnabled()) {
703 if (log)
704 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
705 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
706 watchID, (uint64_t)addr);
707 return error;
708 }
709
710 // Try to find a vacant watchpoint slot in the inferiors' main thread
711 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000712 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
714 m_thread_list.GetThreadAtIndex(0, false).get());
715
716 if (thread)
717 wp_hw_index = thread->FindVacantWatchpointIndex();
718
719 if (wp_hw_index == LLDB_INVALID_INDEX32) {
720 error.SetErrorString("Setting hardware watchpoint failed.");
721 } else {
722 wp->SetHardwareIndex(wp_hw_index);
723 bool wp_enabled = true;
724 uint32_t thread_count = m_thread_list.GetSize(false);
725 for (uint32_t i = 0; i < thread_count; ++i) {
726 thread = static_cast<FreeBSDThread *>(
727 m_thread_list.GetThreadAtIndex(i, false).get());
728 if (thread)
729 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
730 else
731 wp_enabled = false;
732 }
733 if (wp_enabled) {
734 wp->SetEnabled(true, notify);
735 return error;
736 } else {
737 // Watchpoint enabling failed on at least one
738 // of the threads so roll back all of them
739 DisableWatchpoint(wp, false);
740 error.SetErrorString("Setting hardware watchpoint failed");
741 }
742 }
743 } else
744 error.SetErrorString("Watchpoint argument was NULL.");
745 return error;
746}
747
748Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
749 Error error;
750 if (wp) {
751 user_id_t watchID = wp->GetID();
752 addr_t addr = wp->GetLoadAddress();
753 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
754 if (log)
755 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
756 watchID);
757 if (!wp->IsEnabled()) {
758 if (log)
759 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
760 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
761 watchID, (uint64_t)addr);
762 // This is needed (for now) to keep watchpoints disabled correctly
763 wp->SetEnabled(false, notify);
764 return error;
765 }
766
767 if (wp->IsHardware()) {
768 bool wp_disabled = true;
769 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
770 uint32_t thread_count = m_thread_list.GetSize(false);
771 for (uint32_t i = 0; i < thread_count; ++i) {
772 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
773 m_thread_list.GetThreadAtIndex(i, false).get());
774 if (thread)
775 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
776 else
777 wp_disabled = false;
778 }
779 if (wp_disabled) {
780 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
781 wp->SetEnabled(false, notify);
782 return error;
783 } else
784 error.SetErrorString("Disabling hardware watchpoint failed");
785 }
786 } else
787 error.SetErrorString("Watchpoint argument was NULL.");
788 return error;
789}
790
791Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
792 Error error;
793 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
794 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
795 m_thread_list.GetThreadAtIndex(0, false).get());
796 if (thread)
797 num = thread->NumSupportedHardwareWatchpoints();
798 else
799 error.SetErrorString("Process does not exist.");
800 return error;
801}
802
803Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
804 Error error = GetWatchpointSupportInfo(num);
805 // Watchpoints trigger and halt the inferior after
806 // the corresponding instruction has been executed.
807 after = true;
808 return error;
809}
810
811uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
812 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
813 // Do not allow recursive updates.
814 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000815}
816
817#if 0
818bool
819ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
820{
821 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
822 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
823 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
824
825 bool has_updated = false;
826 // Update the process thread list with this new thread.
827 // FIXME: We should be using tid, not pid.
828 assert(m_monitor);
829 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
830 if (!thread_sp) {
831 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
832 has_updated = true;
833 }
834
835 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
836 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
837 new_thread_list.AddThread(thread_sp);
838
839 return has_updated; // the list has been updated
840}
841#endif
842
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843ByteOrder ProcessFreeBSD::GetByteOrder() const {
844 // FIXME: We should be able to extract this value directly. See comment in
845 // ProcessFreeBSD().
846 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000847}
848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) {
850 ssize_t status;
851 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
852 error.SetErrorToErrno();
853 return 0;
854 }
855 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000856}
857
858//------------------------------------------------------------------------------
859// Utility functions.
860
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861bool ProcessFreeBSD::HasExited() {
862 switch (GetPrivateState()) {
863 default:
864 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 case eStateDetached:
867 case eStateExited:
868 return true;
869 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000870
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000872}
873
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874bool ProcessFreeBSD::IsStopped() {
875 switch (GetPrivateState()) {
876 default:
877 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 case eStateStopped:
880 case eStateCrashed:
881 case eStateSuspended:
882 return true;
883 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000886}
887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888bool ProcessFreeBSD::IsAThreadRunning() {
889 bool is_running = false;
890 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
891 uint32_t thread_count = m_thread_list.GetSize(false);
892 for (uint32_t i = 0; i < thread_count; ++i) {
893 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
894 m_thread_list.GetThreadAtIndex(i, false).get());
895 StateType thread_state = thread->GetState();
896 if (thread_state == eStateRunning || thread_state == eStateStepping) {
897 is_running = true;
898 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000899 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 }
901 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000902}
903
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904const DataBufferSP ProcessFreeBSD::GetAuxvData() {
905 // If we're the local platform, we can ask the host for auxv data.
906 PlatformSP platform_sp = GetTarget().GetPlatform();
907 if (platform_sp && platform_sp->IsHost())
908 return lldb_private::Host::GetAuxvData(this);
Ed Mastefe5a6422015-07-28 15:45:57 +0000909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 // Somewhat unexpected - the process is not running locally or we don't have a
911 // platform.
912 assert(
913 false &&
914 "no platform or not the host - how did we get here with ProcessFreeBSD?");
915 return DataBufferSP();
Ed Mastefe5a6422015-07-28 15:45:57 +0000916}
Ed Maste31f01802017-01-24 14:34:49 +0000917
918struct EmulatorBaton {
919 ProcessFreeBSD *m_process;
920 RegisterContext *m_reg_context;
921
922 // eRegisterKindDWARF -> RegisterValue
923 std::unordered_map<uint32_t, RegisterValue> m_register_values;
924
925 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
926 : m_process(process), m_reg_context(reg_context) {}
927};
928
929static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
930 const EmulateInstruction::Context &context,
931 lldb::addr_t addr, void *dst, size_t length) {
932 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
933
934 Error error;
935 size_t bytes_read =
936 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
937 if (!error.Success())
938 bytes_read = 0;
939 return bytes_read;
940}
941
942static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
943 const RegisterInfo *reg_info,
944 RegisterValue &reg_value) {
945 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
946
947 auto it = emulator_baton->m_register_values.find(
948 reg_info->kinds[eRegisterKindDWARF]);
949 if (it != emulator_baton->m_register_values.end()) {
950 reg_value = it->second;
951 return true;
952 }
953
954 // The emulator only fills in the dwarf register numbers (and in some cases
955 // the generic register numbers). Get the full register info from the
956 // register context based on the dwarf register numbers.
957 const RegisterInfo *full_reg_info =
958 emulator_baton->m_reg_context->GetRegisterInfo(
959 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
960
961 bool error =
962 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
963 return error;
964}
965
966static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
967 const EmulateInstruction::Context &context,
968 const RegisterInfo *reg_info,
969 const RegisterValue &reg_value) {
970 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
971 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
972 reg_value;
973 return true;
974}
975
976static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
977 const EmulateInstruction::Context &context,
978 lldb::addr_t addr, const void *dst,
979 size_t length) {
980 return length;
981}
982
983bool ProcessFreeBSD::SingleStepBreakpointHit(
984 void *baton, lldb_private::StoppointCallbackContext *context,
985 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
986 return false;
987}
988
989Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
990 lldb::addr_t addr) {
991 Error error;
992
993 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
994 if (log) {
995 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
996 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
997 }
998
999 // Validate the address.
1000 if (addr == LLDB_INVALID_ADDRESS)
1001 return Error("ProcessFreeBSD::%s invalid load address specified.",
1002 __FUNCTION__);
1003
1004 Breakpoint *const sw_step_break =
1005 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
1006 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
1007 sw_step_break->SetBreakpointKind("software-signle-step");
1008
1009 if (log)
1010 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1011 __FUNCTION__, addr);
1012
1013 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1014 return Error();
1015}
1016
1017bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1018 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1019 if (!thread)
1020 return false;
1021
1022 assert(thread->GetRegisterContext());
1023 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1024
1025 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1026 if (iter == m_threads_stepping_with_breakpoint.end())
1027 return false;
1028
1029 lldb::break_id_t bp_id = iter->second;
1030 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1031 if (!bp)
1032 return false;
1033
1034 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1035 if (!bp_loc)
1036 return false;
1037
1038 GetTarget().RemoveBreakpointByID(bp_id);
1039 m_threads_stepping_with_breakpoint.erase(tid);
1040 return true;
1041}
1042
1043bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1044 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1045 if (arch.GetMachine() == llvm::Triple::arm ||
1046 arch.GetMachine() == llvm::Triple::mips64 ||
1047 arch.GetMachine() == llvm::Triple::mips64el ||
1048 arch.GetMachine() == llvm::Triple::mips ||
1049 arch.GetMachine() == llvm::Triple::mipsel)
1050 return false;
1051 return true;
1052}
1053
1054Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1055 std::unique_ptr<EmulateInstruction> emulator_ap(
1056 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1057 eInstructionTypePCModifying, nullptr));
1058
1059 if (emulator_ap == nullptr)
1060 return Error("Instruction emulator not found!");
1061
1062 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1063 m_thread_list.FindThreadByID(tid, false).get());
1064 if (thread == NULL)
1065 return Error("Thread not found not found!");
1066
1067 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1068
1069 EmulatorBaton baton(this, register_context_sp.get());
1070 emulator_ap->SetBaton(&baton);
1071 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1072 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1073 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1074 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1075
1076 if (!emulator_ap->ReadInstruction())
1077 return Error("Read instruction failed!");
1078
1079 bool emulation_result =
1080 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1081 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1082 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1083 auto pc_it =
1084 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1085
1086 lldb::addr_t next_pc;
1087 if (emulation_result) {
1088 assert(pc_it != baton.m_register_values.end() &&
1089 "Emulation was successful but PC wasn't updated");
1090 next_pc = pc_it->second.GetAsUInt64();
1091 } else if (pc_it == baton.m_register_values.end()) {
1092 // Emulate instruction failed and it haven't changed PC. Advance PC
1093 // with the size of the current opcode because the emulation of all
1094 // PC modifying instruction should be successful. The failure most
1095 // likely caused by a not supported instruction which don't modify PC.
1096 next_pc =
1097 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1098 } else {
1099 // The instruction emulation failed after it modified the PC. It is an
1100 // unknown error where we can't continue because the next instruction is
1101 // modifying the PC but we don't know how.
1102 return Error("Instruction emulation failed unexpectedly");
1103 }
1104
1105 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1106 return Error();
1107}