blob: f95599b853710199cc654c6c4ae5d083a8ab1a9e [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>
Pavel Labathb7f0f452017-03-17 11:08:40 +000013#include <pthread.h>
14#include <pthread_np.h>
15#include <stdlib.h>
16#include <sys/sysctl.h>
17#include <sys/types.h>
18#include <sys/user.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000019
20// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000021#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000022#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000023
Johnny Chen9ed5b492012-01-05 21:48:15 +000024// Other libraries and framework includes
25#include "lldb/Core/PluginManager.h"
26#include "lldb/Core/State.h"
27#include "lldb/Host/Host.h"
28#include "lldb/Symbol/ObjectFile.h"
29#include "lldb/Target/DynamicLoader.h"
30#include "lldb/Target/Target.h"
31
Ed Maste7fd845c2013-12-09 15:51:17 +000032#include "FreeBSDThread.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000033#include "Plugins/Process/Utility/FreeBSDSignals.h"
34#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
35#include "ProcessFreeBSD.h"
36#include "ProcessMonitor.h"
37#include "ProcessPOSIXLog.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000038
Ed Mastefe5a6422015-07-28 15:45:57 +000039// Other libraries and framework includes
40#include "lldb/Breakpoint/BreakpointLocation.h"
41#include "lldb/Breakpoint/Watchpoint.h"
42#include "lldb/Core/Module.h"
43#include "lldb/Core/ModuleSpec.h"
44#include "lldb/Core/PluginManager.h"
45#include "lldb/Core/State.h"
46#include "lldb/Host/FileSpec.h"
47#include "lldb/Host/Host.h"
48#include "lldb/Symbol/ObjectFile.h"
49#include "lldb/Target/DynamicLoader.h"
50#include "lldb/Target/Platform.h"
51#include "lldb/Target/Target.h"
52
53#include "lldb/Host/posix/Fcntl.h"
54
Zachary Turner7d86ee52017-03-08 17:56:08 +000055#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000056#include "llvm/Support/Threading.h"
57
Johnny Chen9ed5b492012-01-05 21:48:15 +000058using namespace lldb;
59using namespace lldb_private;
60
Kate Stoneb9c1b512016-09-06 20:57:50 +000061namespace {
62UnixSignalsSP &GetFreeBSDSignals() {
63 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
64 return s_freebsd_signals_sp;
65}
Todd Fiala4ceced32014-08-29 17:35:57 +000066}
67
Johnny Chen9ed5b492012-01-05 21:48:15 +000068//------------------------------------------------------------------------------
69// Static functions.
70
Greg Clayton29d19302012-02-27 18:40:48 +000071lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000072ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000073 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 const FileSpec *crash_file_path) {
75 lldb::ProcessSP process_sp;
76 if (crash_file_path == NULL)
77 process_sp.reset(
78 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
79 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000080}
81
Kate Stoneb9c1b512016-09-06 20:57:50 +000082void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000083 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000084
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000085 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 PluginManager::RegisterPlugin(GetPluginNameStatic(),
87 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000089}
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
92 static ConstString g_name("freebsd");
93 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000094}
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
97 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000098}
99
100//------------------------------------------------------------------------------
101// ProcessInterface protocol.
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
104 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111Error ProcessFreeBSD::DoDetach(bool keep_stopped) {
112 Error error;
113 if (keep_stopped) {
114 error.SetErrorString("Detaching with keep_stopped true is not currently "
115 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000116 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 }
118
119 error = m_monitor->Detach(GetID());
120
121 if (error.Success())
122 SetPrivateState(eStateDetached);
123
124 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000125}
126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127Error ProcessFreeBSD::DoResume() {
128 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
133 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000134 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
137 t_end = m_run_tids.end();
138 t_pos != t_end; ++t_pos) {
139 m_monitor->ThreadSuspend(*t_pos, false);
140 }
141 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
142 t_end = m_step_tids.end();
143 t_pos != t_end; ++t_pos) {
144 m_monitor->ThreadSuspend(*t_pos, false);
145 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000146 if (software_single_step) {
147 Error error = SetupSoftwareSingleStepping(*t_pos);
148 if (error.Fail())
149 return error;
150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 }
152 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
153 t_end = m_suspend_tids.end();
154 t_pos != t_end; ++t_pos) {
155 m_monitor->ThreadSuspend(*t_pos, true);
156 // XXX Cannot PT_CONTINUE properly with suspended threads.
157 do_step = true;
158 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 if (log)
161 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
162 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000163 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 m_monitor->SingleStep(GetID(), m_resume_signo);
165 else
166 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000167
Mehdi Amini665be502016-11-11 05:07:57 +0000168 return Error();
Ed Maste7fd845c2013-12-09 15:51:17 +0000169}
170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
172 ThreadList &new_thread_list) {
173 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
174 if (log)
175 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
176 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000177
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 std::vector<lldb::pid_t> tds;
179 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
180 return false;
181 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 ThreadList old_thread_list_copy(old_thread_list);
184 for (size_t i = 0; i < tds.size(); ++i) {
185 tid_t tid = tds[i];
186 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
187 if (!thread_sp) {
188 thread_sp.reset(new FreeBSDThread(*this, tid));
189 if (log)
190 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
191 } else {
192 if (log)
193 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
194 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000195 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 new_thread_list.AddThread(thread_sp);
197 }
198 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
199 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
200 if (old_thread_sp) {
201 if (log)
202 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000203 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000207}
Ed Maste7fd845c2013-12-09 15:51:17 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209Error ProcessFreeBSD::WillResume() {
210 m_resume_signo = 0;
211 m_suspend_tids.clear();
212 m_run_tids.clear();
213 m_step_tids.clear();
214 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000215}
216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
218 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 switch (message.GetKind()) {
221 case ProcessMessage::eInvalidMessage:
222 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 case ProcessMessage::eAttachMessage:
225 SetPrivateState(eStateStopped);
226 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 case ProcessMessage::eLimboMessage:
229 case ProcessMessage::eExitMessage:
230 SetExitStatus(message.GetExitStatus(), NULL);
231 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 case ProcessMessage::eSignalMessage:
234 case ProcessMessage::eSignalDeliveredMessage:
235 case ProcessMessage::eBreakpointMessage:
236 case ProcessMessage::eTraceMessage:
237 case ProcessMessage::eWatchpointMessage:
238 case ProcessMessage::eCrashMessage:
239 SetPrivateState(eStateStopped);
240 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 case ProcessMessage::eNewThreadMessage:
243 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
244 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 case ProcessMessage::eExecMessage:
247 SetPrivateState(eStateStopped);
248 break;
249 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000252}
Ed Mastefe5a6422015-07-28 15:45:57 +0000253
254//------------------------------------------------------------------------------
255// Constructors and destructors.
256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
258 lldb::ListenerSP listener_sp,
259 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000260 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
262 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
263 m_resume_signo(0) {
264 // FIXME: Putting this code in the ctor and saving the byte order in a
265 // member variable is a hack to avoid const qual issues in GetByteOrder.
266 lldb::ModuleSP module = GetTarget().GetExecutableModule();
267 if (module && module->GetObjectFile())
268 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000269}
270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000272
273//------------------------------------------------------------------------------
274// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000276 Process::Finalize();
277
278 if (m_monitor)
279 m_monitor->StopMonitor();
280}
281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
283 bool plugin_specified_by_name) {
284 // For now we are just making sure the file exists for a given module
285 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
286 if (exe_module_sp.get())
287 return exe_module_sp->GetFileSpec().Exists();
288 // If there is no executable module, we return true since we might be
289 // preparing to attach.
290 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000291}
292
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293Error ProcessFreeBSD::DoAttachToProcessWithID(
294 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
295 Error error;
296 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000299 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000300
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000304 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305
306 PlatformSP platform_sp(GetTarget().GetPlatform());
307 assert(platform_sp.get());
308 if (!platform_sp)
309 return error; // FIXME: Detatch?
310
311 // Find out what we can about this process
312 ProcessInstanceInfo process_info;
313 platform_sp->GetProcessInfo(pid, process_info);
314
315 // Resolve the executable module
316 ModuleSP exe_module_sp;
317 FileSpecList executable_search_paths(
318 Target::GetDefaultExecutableSearchPaths());
319 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
320 GetTarget().GetArchitecture());
321 error = platform_sp->ResolveExecutable(
322 exe_module_spec, exe_module_sp,
323 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
324 if (!error.Success())
325 return error;
326
327 // Fix the target architecture if necessary
328 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
329 if (module_arch.IsValid() &&
330 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
331 GetTarget().SetArchitecture(module_arch);
332
333 // Initialize the target module list
334 GetTarget().SetExecutableModule(exe_module_sp, true);
335
336 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
337
338 SetID(pid);
339
340 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000341}
342
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343Error ProcessFreeBSD::WillLaunch(Module *module) {
344 Error error;
345 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000346}
347
348FileSpec
349ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 const FileSpec &default_file_spec,
351 const FileSpec &dbg_pts_file_spec) {
352 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
355 file_spec = file_action->GetFileSpec();
356 // By default the stdio paths passed in will be pseudo-terminal
357 // (/dev/pts). If so, convert to using a different default path
358 // instead to redirect I/O to the debugger console. This should
359 // also handle user overrides to /dev/null or a different file.
360 if (!file_spec || file_spec == dbg_pts_file_spec)
361 file_spec = default_file_spec;
362 }
363 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000364}
365
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) {
367 Error error;
368 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000369
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 FileSpec working_dir = launch_info.GetWorkingDirectory();
Zachary Turner7d86ee52017-03-08 17:56:08 +0000371 namespace fs = llvm::sys::fs;
372 if (working_dir && (!working_dir.ResolvePath() ||
373 !fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 error.SetErrorStringWithFormat("No such file or directory: %s",
375 working_dir.GetCString());
376 return error;
377 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 // Default of empty will mean to use existing open file descriptors
384 FileSpec stdin_file_spec{};
385 FileSpec stdout_file_spec{};
386 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
389 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
392 stdin_file_spec =
393 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
396 stdout_file_spec =
397 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
400 stderr_file_spec =
401 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000402
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 m_monitor = new ProcessMonitor(
404 this, module, launch_info.GetArguments().GetConstArgumentVector(),
405 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
406 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
407 launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 if (!error.Success())
412 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 int terminal = m_monitor->GetTerminalFD();
415 if (terminal >= 0) {
416// The reader thread will close the file descriptor when done, so we pass it a
417// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000418#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
420 if (stdio == -1) {
421 error.SetErrorToErrno();
422 return error;
423 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000424#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
426 int stdio = fcntl(terminal, F_DUPFD, 0);
427 if (stdio == -1) {
428 error.SetErrorToErrno();
429 return error;
430 }
431 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
432 if (stdio == -1) {
433 error.SetErrorToErrno();
434 return error;
435 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000436#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 SetSTDIOFileDescriptor(stdio);
438 }
439
440 SetID(m_monitor->GetPID());
441 return error;
442}
443
444void ProcessFreeBSD::DidLaunch() {}
445
446addr_t ProcessFreeBSD::GetImageInfoAddress() {
447 Target *target = &GetTarget();
448 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
449 Address addr = obj_file->GetImageInfoAddress(target);
450
451 if (addr.IsValid())
452 return addr.GetLoadAddress(target);
453 return LLDB_INVALID_ADDRESS;
454}
455
456Error ProcessFreeBSD::DoHalt(bool &caused_stop) {
457 Error error;
458
459 if (IsStopped()) {
460 caused_stop = false;
461 } else if (kill(GetID(), SIGSTOP)) {
462 caused_stop = false;
463 error.SetErrorToErrno();
464 } else {
465 caused_stop = true;
466 }
467 return error;
468}
469
470Error ProcessFreeBSD::DoSignal(int signal) {
471 Error error;
472
473 if (kill(GetID(), signal))
474 error.SetErrorToErrno();
475
476 return error;
477}
478
479Error ProcessFreeBSD::DoDestroy() {
480 Error error;
481
482 if (!HasExited()) {
483 assert(m_monitor);
484 m_exit_now = true;
485 if (GetID() == LLDB_INVALID_PROCESS_ID) {
486 error.SetErrorString("invalid process id");
487 return error;
488 }
489 if (!m_monitor->Kill()) {
490 error.SetErrorToErrno();
491 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000492 }
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 SetPrivateState(eStateExited);
495 }
496
497 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000498}
499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500void ProcessFreeBSD::DoDidExec() {
501 Target *target = &GetTarget();
502 if (target) {
503 PlatformSP platform_sp(target->GetPlatform());
504 assert(platform_sp.get());
505 if (platform_sp) {
506 ProcessInstanceInfo process_info;
507 platform_sp->GetProcessInfo(GetID(), process_info);
508 ModuleSP exe_module_sp;
509 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
510 target->GetArchitecture());
511 FileSpecList executable_search_paths(
512 Target::GetDefaultExecutableSearchPaths());
513 Error error = platform_sp->ResolveExecutable(
514 exe_module_spec, exe_module_sp,
515 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
516 if (!error.Success())
517 return;
518 target->SetExecutableModule(exe_module_sp, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000519 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000521}
522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
524 bool added_to_set = false;
525 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
526 if (it == m_seen_initial_stop.end()) {
527 m_seen_initial_stop.insert(stop_tid);
528 added_to_set = true;
529 }
530 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000531}
532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
534 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000535}
536
537FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
539 lldb::tid_t tid) {
540 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000541}
542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543void ProcessFreeBSD::RefreshStateAfterStop() {
544 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000545 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549 // This method used to only handle one message. Changing it to loop allows
550 // it to handle the case where we hit a breakpoint while handling a different
551 // breakpoint.
552 while (!m_message_queue.empty()) {
553 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 // Resolve the thread this message corresponds to and pass it along.
556 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000557 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
558 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
563 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000564 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 thread->Notify(message);
566
567 if (message.GetKind() == ProcessMessage::eExitMessage) {
568 // FIXME: We should tell the user about this, but the limbo message is
569 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000570 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
572
573 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
574 thread_sp.reset();
575 m_seen_initial_stop.erase(tid);
576 }
577
578 m_message_queue.pop();
579 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000580}
581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582bool ProcessFreeBSD::IsAlive() {
583 StateType state = GetPrivateState();
584 return state != eStateDetached && state != eStateExited &&
585 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000586}
587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
589 Error &error) {
590 assert(m_monitor);
591 return m_monitor->ReadMemory(vm_addr, buf, size, error);
592}
593
594size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
595 size_t size, Error &error) {
596 assert(m_monitor);
597 return m_monitor->WriteMemory(vm_addr, buf, size, error);
598}
599
600addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
601 Error &error) {
602 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
603
604 unsigned prot = 0;
605 if (permissions & lldb::ePermissionsReadable)
606 prot |= eMmapProtRead;
607 if (permissions & lldb::ePermissionsWritable)
608 prot |= eMmapProtWrite;
609 if (permissions & lldb::ePermissionsExecutable)
610 prot |= eMmapProtExec;
611
612 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
613 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
614 m_addr_to_mmap_size[allocated_addr] = size;
615 error.Clear();
616 } else {
617 allocated_addr = LLDB_INVALID_ADDRESS;
618 error.SetErrorStringWithFormat(
619 "unable to allocate %zu bytes of memory with permissions %s", size,
620 GetPermissionsAsCString(permissions));
621 }
622
623 return allocated_addr;
624}
625
626Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
627 Error error;
628 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
629 if (pos != m_addr_to_mmap_size.end() &&
630 InferiorCallMunmap(this, addr, pos->second))
631 m_addr_to_mmap_size.erase(pos);
632 else
633 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
634 addr);
635
636 return error;
637}
638
639size_t
640ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
641 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
642 static const uint8_t g_i386_opcode[] = {0xCC};
643
644 ArchSpec arch = GetTarget().GetArchitecture();
645 const uint8_t *opcode = NULL;
646 size_t opcode_size = 0;
647
648 switch (arch.GetMachine()) {
649 default:
650 assert(false && "CPU type not supported!");
651 break;
652
653 case llvm::Triple::arm: {
654 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
655 // but the linux kernel does otherwise.
656 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
657 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
658
659 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
660 AddressClass addr_class = eAddressClassUnknown;
661
662 if (bp_loc_sp)
663 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
664
665 if (addr_class == eAddressClassCodeAlternateISA ||
666 (addr_class == eAddressClassUnknown &&
667 bp_loc_sp->GetAddress().GetOffset() & 1)) {
668 opcode = g_thumb_breakpoint_opcode;
669 opcode_size = sizeof(g_thumb_breakpoint_opcode);
670 } else {
671 opcode = g_arm_breakpoint_opcode;
672 opcode_size = sizeof(g_arm_breakpoint_opcode);
673 }
674 } break;
675 case llvm::Triple::aarch64:
676 opcode = g_aarch64_opcode;
677 opcode_size = sizeof(g_aarch64_opcode);
678 break;
679
680 case llvm::Triple::x86:
681 case llvm::Triple::x86_64:
682 opcode = g_i386_opcode;
683 opcode_size = sizeof(g_i386_opcode);
684 break;
685 }
686
687 bp_site->SetTrapOpcode(opcode, opcode_size);
688 return opcode_size;
689}
690
691Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
692 return EnableSoftwareBreakpoint(bp_site);
693}
694
695Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
696 return DisableSoftwareBreakpoint(bp_site);
697}
698
699Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
700 Error error;
701 if (wp) {
702 user_id_t watchID = wp->GetID();
703 addr_t addr = wp->GetLoadAddress();
704 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
705 if (log)
706 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
707 watchID);
708 if (wp->IsEnabled()) {
709 if (log)
710 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
711 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
712 watchID, (uint64_t)addr);
713 return error;
714 }
715
716 // Try to find a vacant watchpoint slot in the inferiors' main thread
717 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000718 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
720 m_thread_list.GetThreadAtIndex(0, false).get());
721
722 if (thread)
723 wp_hw_index = thread->FindVacantWatchpointIndex();
724
725 if (wp_hw_index == LLDB_INVALID_INDEX32) {
726 error.SetErrorString("Setting hardware watchpoint failed.");
727 } else {
728 wp->SetHardwareIndex(wp_hw_index);
729 bool wp_enabled = true;
730 uint32_t thread_count = m_thread_list.GetSize(false);
731 for (uint32_t i = 0; i < thread_count; ++i) {
732 thread = static_cast<FreeBSDThread *>(
733 m_thread_list.GetThreadAtIndex(i, false).get());
734 if (thread)
735 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
736 else
737 wp_enabled = false;
738 }
739 if (wp_enabled) {
740 wp->SetEnabled(true, notify);
741 return error;
742 } else {
743 // Watchpoint enabling failed on at least one
744 // of the threads so roll back all of them
745 DisableWatchpoint(wp, false);
746 error.SetErrorString("Setting hardware watchpoint failed");
747 }
748 }
749 } else
750 error.SetErrorString("Watchpoint argument was NULL.");
751 return error;
752}
753
754Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
755 Error error;
756 if (wp) {
757 user_id_t watchID = wp->GetID();
758 addr_t addr = wp->GetLoadAddress();
759 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
760 if (log)
761 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
762 watchID);
763 if (!wp->IsEnabled()) {
764 if (log)
765 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
766 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
767 watchID, (uint64_t)addr);
768 // This is needed (for now) to keep watchpoints disabled correctly
769 wp->SetEnabled(false, notify);
770 return error;
771 }
772
773 if (wp->IsHardware()) {
774 bool wp_disabled = true;
775 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
776 uint32_t thread_count = m_thread_list.GetSize(false);
777 for (uint32_t i = 0; i < thread_count; ++i) {
778 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
779 m_thread_list.GetThreadAtIndex(i, false).get());
780 if (thread)
781 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
782 else
783 wp_disabled = false;
784 }
785 if (wp_disabled) {
786 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
787 wp->SetEnabled(false, notify);
788 return error;
789 } else
790 error.SetErrorString("Disabling hardware watchpoint failed");
791 }
792 } else
793 error.SetErrorString("Watchpoint argument was NULL.");
794 return error;
795}
796
797Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
798 Error error;
799 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
800 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
801 m_thread_list.GetThreadAtIndex(0, false).get());
802 if (thread)
803 num = thread->NumSupportedHardwareWatchpoints();
804 else
805 error.SetErrorString("Process does not exist.");
806 return error;
807}
808
809Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
810 Error error = GetWatchpointSupportInfo(num);
811 // Watchpoints trigger and halt the inferior after
812 // the corresponding instruction has been executed.
813 after = true;
814 return error;
815}
816
817uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
818 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
819 // Do not allow recursive updates.
820 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000821}
822
823#if 0
824bool
825ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
826{
827 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
828 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
829 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
830
831 bool has_updated = false;
832 // Update the process thread list with this new thread.
833 // FIXME: We should be using tid, not pid.
834 assert(m_monitor);
835 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
836 if (!thread_sp) {
837 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
838 has_updated = true;
839 }
840
841 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
842 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
843 new_thread_list.AddThread(thread_sp);
844
845 return has_updated; // the list has been updated
846}
847#endif
848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849ByteOrder ProcessFreeBSD::GetByteOrder() const {
850 // FIXME: We should be able to extract this value directly. See comment in
851 // ProcessFreeBSD().
852 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000853}
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) {
856 ssize_t status;
857 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
858 error.SetErrorToErrno();
859 return 0;
860 }
861 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000862}
863
864//------------------------------------------------------------------------------
865// Utility functions.
866
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867bool ProcessFreeBSD::HasExited() {
868 switch (GetPrivateState()) {
869 default:
870 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 case eStateDetached:
873 case eStateExited:
874 return true;
875 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000876
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000878}
879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880bool ProcessFreeBSD::IsStopped() {
881 switch (GetPrivateState()) {
882 default:
883 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 case eStateStopped:
886 case eStateCrashed:
887 case eStateSuspended:
888 return true;
889 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000890
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000892}
893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894bool ProcessFreeBSD::IsAThreadRunning() {
895 bool is_running = false;
896 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
897 uint32_t thread_count = m_thread_list.GetSize(false);
898 for (uint32_t i = 0; i < thread_count; ++i) {
899 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
900 m_thread_list.GetThreadAtIndex(i, false).get());
901 StateType thread_state = thread->GetState();
902 if (thread_state == eStateRunning || thread_state == eStateStepping) {
903 is_running = true;
904 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000905 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000906 }
907 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000908}
909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910const DataBufferSP ProcessFreeBSD::GetAuxvData() {
911 // If we're the local platform, we can ask the host for auxv data.
912 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000913 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000914
Pavel Labathb7f0f452017-03-17 11:08:40 +0000915 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, process->GetID()};
916 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
917 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
918
919 if (::sysctl(mib, 4, buf_ap->GetBytes(), &auxv_size, NULL, 0) != 0) {
920 perror("sysctl failed on auxv");
921 buf_sp.reset();
922 }
923
924 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000925}
Ed Maste31f01802017-01-24 14:34:49 +0000926
927struct EmulatorBaton {
928 ProcessFreeBSD *m_process;
929 RegisterContext *m_reg_context;
930
931 // eRegisterKindDWARF -> RegisterValue
932 std::unordered_map<uint32_t, RegisterValue> m_register_values;
933
934 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
935 : m_process(process), m_reg_context(reg_context) {}
936};
937
938static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
939 const EmulateInstruction::Context &context,
940 lldb::addr_t addr, void *dst, size_t length) {
941 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
942
943 Error error;
944 size_t bytes_read =
945 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
946 if (!error.Success())
947 bytes_read = 0;
948 return bytes_read;
949}
950
951static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
952 const RegisterInfo *reg_info,
953 RegisterValue &reg_value) {
954 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
955
956 auto it = emulator_baton->m_register_values.find(
957 reg_info->kinds[eRegisterKindDWARF]);
958 if (it != emulator_baton->m_register_values.end()) {
959 reg_value = it->second;
960 return true;
961 }
962
963 // The emulator only fills in the dwarf register numbers (and in some cases
964 // the generic register numbers). Get the full register info from the
965 // register context based on the dwarf register numbers.
966 const RegisterInfo *full_reg_info =
967 emulator_baton->m_reg_context->GetRegisterInfo(
968 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
969
970 bool error =
971 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
972 return error;
973}
974
975static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
976 const EmulateInstruction::Context &context,
977 const RegisterInfo *reg_info,
978 const RegisterValue &reg_value) {
979 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
980 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
981 reg_value;
982 return true;
983}
984
985static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
986 const EmulateInstruction::Context &context,
987 lldb::addr_t addr, const void *dst,
988 size_t length) {
989 return length;
990}
991
992bool ProcessFreeBSD::SingleStepBreakpointHit(
993 void *baton, lldb_private::StoppointCallbackContext *context,
994 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
995 return false;
996}
997
998Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
999 lldb::addr_t addr) {
1000 Error error;
1001
1002 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1003 if (log) {
1004 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1005 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1006 }
1007
1008 // Validate the address.
1009 if (addr == LLDB_INVALID_ADDRESS)
1010 return Error("ProcessFreeBSD::%s invalid load address specified.",
1011 __FUNCTION__);
1012
1013 Breakpoint *const sw_step_break =
1014 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
1015 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
1016 sw_step_break->SetBreakpointKind("software-signle-step");
1017
1018 if (log)
1019 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1020 __FUNCTION__, addr);
1021
1022 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1023 return Error();
1024}
1025
1026bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1027 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1028 if (!thread)
1029 return false;
1030
1031 assert(thread->GetRegisterContext());
1032 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1033
1034 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1035 if (iter == m_threads_stepping_with_breakpoint.end())
1036 return false;
1037
1038 lldb::break_id_t bp_id = iter->second;
1039 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1040 if (!bp)
1041 return false;
1042
1043 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1044 if (!bp_loc)
1045 return false;
1046
1047 GetTarget().RemoveBreakpointByID(bp_id);
1048 m_threads_stepping_with_breakpoint.erase(tid);
1049 return true;
1050}
1051
1052bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1053 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1054 if (arch.GetMachine() == llvm::Triple::arm ||
1055 arch.GetMachine() == llvm::Triple::mips64 ||
1056 arch.GetMachine() == llvm::Triple::mips64el ||
1057 arch.GetMachine() == llvm::Triple::mips ||
1058 arch.GetMachine() == llvm::Triple::mipsel)
1059 return false;
1060 return true;
1061}
1062
1063Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1064 std::unique_ptr<EmulateInstruction> emulator_ap(
1065 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1066 eInstructionTypePCModifying, nullptr));
1067
1068 if (emulator_ap == nullptr)
1069 return Error("Instruction emulator not found!");
1070
1071 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1072 m_thread_list.FindThreadByID(tid, false).get());
1073 if (thread == NULL)
1074 return Error("Thread not found not found!");
1075
1076 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1077
1078 EmulatorBaton baton(this, register_context_sp.get());
1079 emulator_ap->SetBaton(&baton);
1080 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1081 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1082 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1083 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1084
1085 if (!emulator_ap->ReadInstruction())
1086 return Error("Read instruction failed!");
1087
1088 bool emulation_result =
1089 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1090 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1091 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1092 auto pc_it =
1093 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1094
1095 lldb::addr_t next_pc;
1096 if (emulation_result) {
1097 assert(pc_it != baton.m_register_values.end() &&
1098 "Emulation was successful but PC wasn't updated");
1099 next_pc = pc_it->second.GetAsUInt64();
1100 } else if (pc_it == baton.m_register_values.end()) {
1101 // Emulate instruction failed and it haven't changed PC. Advance PC
1102 // with the size of the current opcode because the emulation of all
1103 // PC modifying instruction should be successful. The failure most
1104 // likely caused by a not supported instruction which don't modify PC.
1105 next_pc =
1106 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1107 } else {
1108 // The instruction emulation failed after it modified the PC. It is an
1109 // unknown error where we can't continue because the next instruction is
1110 // modifying the PC but we don't know how.
1111 return Error("Instruction emulation failed unexpectedly");
1112 }
1113
1114 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1115 return Error();
1116}