blob: b3365315f80280684d68b0c11c7cdf618152081d [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>
Pavel Labath5b116232017-03-17 11:33:57 +000019#include <machine/elf.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000020
21// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000022#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000023#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000024
Johnny Chen9ed5b492012-01-05 21:48:15 +000025// Other libraries and framework includes
26#include "lldb/Core/PluginManager.h"
Zachary Turner813de712017-04-06 22:18:59 +000027#include "lldb/Core/RegisterValue.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000028#include "lldb/Core/State.h"
29#include "lldb/Host/Host.h"
30#include "lldb/Symbol/ObjectFile.h"
31#include "lldb/Target/DynamicLoader.h"
32#include "lldb/Target/Target.h"
33
Ed Maste7fd845c2013-12-09 15:51:17 +000034#include "FreeBSDThread.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000035#include "Plugins/Process/Utility/FreeBSDSignals.h"
36#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
37#include "ProcessFreeBSD.h"
38#include "ProcessMonitor.h"
39#include "ProcessPOSIXLog.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000040
Ed Mastefe5a6422015-07-28 15:45:57 +000041// Other libraries and framework includes
42#include "lldb/Breakpoint/BreakpointLocation.h"
43#include "lldb/Breakpoint/Watchpoint.h"
44#include "lldb/Core/Module.h"
45#include "lldb/Core/ModuleSpec.h"
46#include "lldb/Core/PluginManager.h"
47#include "lldb/Core/State.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000048#include "lldb/Host/Host.h"
49#include "lldb/Symbol/ObjectFile.h"
50#include "lldb/Target/DynamicLoader.h"
51#include "lldb/Target/Platform.h"
52#include "lldb/Target/Target.h"
Pavel Labath5b116232017-03-17 11:33:57 +000053#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner5713a052017-03-22 18:40:07 +000054#include "lldb/Utility/FileSpec.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000055
56#include "lldb/Host/posix/Fcntl.h"
57
Zachary Turner7d86ee52017-03-08 17:56:08 +000058#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000059#include "llvm/Support/Threading.h"
60
Johnny Chen9ed5b492012-01-05 21:48:15 +000061using namespace lldb;
62using namespace lldb_private;
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064namespace {
65UnixSignalsSP &GetFreeBSDSignals() {
66 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
67 return s_freebsd_signals_sp;
68}
Todd Fiala4ceced32014-08-29 17:35:57 +000069}
70
Johnny Chen9ed5b492012-01-05 21:48:15 +000071//------------------------------------------------------------------------------
72// Static functions.
73
Greg Clayton29d19302012-02-27 18:40:48 +000074lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000075ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000076 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 const FileSpec *crash_file_path) {
78 lldb::ProcessSP process_sp;
79 if (crash_file_path == NULL)
80 process_sp.reset(
81 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
82 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000083}
84
Kate Stoneb9c1b512016-09-06 20:57:50 +000085void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000086 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000087
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000088 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000089 PluginManager::RegisterPlugin(GetPluginNameStatic(),
90 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000092}
93
Kate Stoneb9c1b512016-09-06 20:57:50 +000094lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
95 static ConstString g_name("freebsd");
96 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000097}
98
Kate Stoneb9c1b512016-09-06 20:57:50 +000099const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
100 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +0000101}
102
103//------------------------------------------------------------------------------
104// ProcessInterface protocol.
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
107 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000111
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000113
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114Error ProcessFreeBSD::DoDetach(bool keep_stopped) {
115 Error error;
116 if (keep_stopped) {
117 error.SetErrorString("Detaching with keep_stopped true is not currently "
118 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000119 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000120 }
121
122 error = m_monitor->Detach(GetID());
123
124 if (error.Success())
125 SetPrivateState(eStateDetached);
126
127 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000128}
129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130Error ProcessFreeBSD::DoResume() {
131 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
136 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000137 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
140 t_end = m_run_tids.end();
141 t_pos != t_end; ++t_pos) {
142 m_monitor->ThreadSuspend(*t_pos, false);
143 }
144 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
145 t_end = m_step_tids.end();
146 t_pos != t_end; ++t_pos) {
147 m_monitor->ThreadSuspend(*t_pos, false);
148 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000149 if (software_single_step) {
150 Error error = SetupSoftwareSingleStepping(*t_pos);
151 if (error.Fail())
152 return error;
153 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 }
155 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
156 t_end = m_suspend_tids.end();
157 t_pos != t_end; ++t_pos) {
158 m_monitor->ThreadSuspend(*t_pos, true);
159 // XXX Cannot PT_CONTINUE properly with suspended threads.
160 do_step = true;
161 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 if (log)
164 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
165 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000166 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 m_monitor->SingleStep(GetID(), m_resume_signo);
168 else
169 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000170
Mehdi Amini665be502016-11-11 05:07:57 +0000171 return Error();
Ed Maste7fd845c2013-12-09 15:51:17 +0000172}
173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
175 ThreadList &new_thread_list) {
176 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
177 if (log)
178 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
179 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181 std::vector<lldb::pid_t> tds;
182 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
183 return false;
184 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000185
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 ThreadList old_thread_list_copy(old_thread_list);
187 for (size_t i = 0; i < tds.size(); ++i) {
188 tid_t tid = tds[i];
189 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
190 if (!thread_sp) {
191 thread_sp.reset(new FreeBSDThread(*this, tid));
192 if (log)
193 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
194 } else {
195 if (log)
196 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
197 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000198 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 new_thread_list.AddThread(thread_sp);
200 }
201 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
202 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
203 if (old_thread_sp) {
204 if (log)
205 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000206 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000210}
Ed Maste7fd845c2013-12-09 15:51:17 +0000211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212Error ProcessFreeBSD::WillResume() {
213 m_resume_signo = 0;
214 m_suspend_tids.clear();
215 m_run_tids.clear();
216 m_step_tids.clear();
217 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
221 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 switch (message.GetKind()) {
224 case ProcessMessage::eInvalidMessage:
225 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 case ProcessMessage::eAttachMessage:
228 SetPrivateState(eStateStopped);
229 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000230
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231 case ProcessMessage::eLimboMessage:
232 case ProcessMessage::eExitMessage:
233 SetExitStatus(message.GetExitStatus(), NULL);
234 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000235
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 case ProcessMessage::eSignalMessage:
237 case ProcessMessage::eSignalDeliveredMessage:
238 case ProcessMessage::eBreakpointMessage:
239 case ProcessMessage::eTraceMessage:
240 case ProcessMessage::eWatchpointMessage:
241 case ProcessMessage::eCrashMessage:
242 SetPrivateState(eStateStopped);
243 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 case ProcessMessage::eNewThreadMessage:
246 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
247 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000248
Kate Stoneb9c1b512016-09-06 20:57:50 +0000249 case ProcessMessage::eExecMessage:
250 SetPrivateState(eStateStopped);
251 break;
252 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000253
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000255}
Ed Mastefe5a6422015-07-28 15:45:57 +0000256
257//------------------------------------------------------------------------------
258// Constructors and destructors.
259
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
261 lldb::ListenerSP listener_sp,
262 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000263 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
265 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
266 m_resume_signo(0) {
267 // FIXME: Putting this code in the ctor and saving the byte order in a
268 // member variable is a hack to avoid const qual issues in GetByteOrder.
269 lldb::ModuleSP module = GetTarget().GetExecutableModule();
270 if (module && module->GetObjectFile())
271 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000272}
273
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000275
276//------------------------------------------------------------------------------
277// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000279 Process::Finalize();
280
281 if (m_monitor)
282 m_monitor->StopMonitor();
283}
284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
286 bool plugin_specified_by_name) {
287 // For now we are just making sure the file exists for a given module
288 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
289 if (exe_module_sp.get())
290 return exe_module_sp->GetFileSpec().Exists();
291 // If there is no executable module, we return true since we might be
292 // preparing to attach.
293 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000294}
295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296Error ProcessFreeBSD::DoAttachToProcessWithID(
297 lldb::pid_t pid, const ProcessAttachInfo &attach_info) {
298 Error error;
299 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000300
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000302 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000305
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000307 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308
309 PlatformSP platform_sp(GetTarget().GetPlatform());
310 assert(platform_sp.get());
311 if (!platform_sp)
312 return error; // FIXME: Detatch?
313
314 // Find out what we can about this process
315 ProcessInstanceInfo process_info;
316 platform_sp->GetProcessInfo(pid, process_info);
317
318 // Resolve the executable module
319 ModuleSP exe_module_sp;
320 FileSpecList executable_search_paths(
321 Target::GetDefaultExecutableSearchPaths());
322 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
323 GetTarget().GetArchitecture());
324 error = platform_sp->ResolveExecutable(
325 exe_module_spec, exe_module_sp,
326 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
327 if (!error.Success())
328 return error;
329
330 // Fix the target architecture if necessary
331 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
332 if (module_arch.IsValid() &&
333 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
334 GetTarget().SetArchitecture(module_arch);
335
336 // Initialize the target module list
337 GetTarget().SetExecutableModule(exe_module_sp, true);
338
339 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
340
341 SetID(pid);
342
343 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000344}
345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346Error ProcessFreeBSD::WillLaunch(Module *module) {
347 Error error;
348 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000349}
350
351FileSpec
352ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 const FileSpec &default_file_spec,
354 const FileSpec &dbg_pts_file_spec) {
355 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000356
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
358 file_spec = file_action->GetFileSpec();
359 // By default the stdio paths passed in will be pseudo-terminal
360 // (/dev/pts). If so, convert to using a different default path
361 // instead to redirect I/O to the debugger console. This should
362 // also handle user overrides to /dev/null or a different file.
363 if (!file_spec || file_spec == dbg_pts_file_spec)
364 file_spec = default_file_spec;
365 }
366 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369Error ProcessFreeBSD::DoLaunch(Module *module, ProcessLaunchInfo &launch_info) {
370 Error error;
371 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 FileSpec working_dir = launch_info.GetWorkingDirectory();
Zachary Turner7d86ee52017-03-08 17:56:08 +0000374 namespace fs = llvm::sys::fs;
375 if (working_dir && (!working_dir.ResolvePath() ||
376 !fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 error.SetErrorStringWithFormat("No such file or directory: %s",
378 working_dir.GetCString());
379 return error;
380 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 // Default of empty will mean to use existing open file descriptors
387 FileSpec stdin_file_spec{};
388 FileSpec stdout_file_spec{};
389 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000390
Kate Stoneb9c1b512016-09-06 20:57:50 +0000391 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
392 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
395 stdin_file_spec =
396 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
399 stdout_file_spec =
400 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
403 stderr_file_spec =
404 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000405
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 m_monitor = new ProcessMonitor(
407 this, module, launch_info.GetArguments().GetConstArgumentVector(),
408 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
409 stdin_file_spec, stdout_file_spec, stderr_file_spec, working_dir,
410 launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 if (!error.Success())
415 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 int terminal = m_monitor->GetTerminalFD();
418 if (terminal >= 0) {
419// The reader thread will close the file descriptor when done, so we pass it a
420// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000421#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
423 if (stdio == -1) {
424 error.SetErrorToErrno();
425 return error;
426 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000427#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
429 int stdio = fcntl(terminal, F_DUPFD, 0);
430 if (stdio == -1) {
431 error.SetErrorToErrno();
432 return error;
433 }
434 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
435 if (stdio == -1) {
436 error.SetErrorToErrno();
437 return error;
438 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000439#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 SetSTDIOFileDescriptor(stdio);
441 }
442
443 SetID(m_monitor->GetPID());
444 return error;
445}
446
447void ProcessFreeBSD::DidLaunch() {}
448
449addr_t ProcessFreeBSD::GetImageInfoAddress() {
450 Target *target = &GetTarget();
451 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
452 Address addr = obj_file->GetImageInfoAddress(target);
453
454 if (addr.IsValid())
455 return addr.GetLoadAddress(target);
456 return LLDB_INVALID_ADDRESS;
457}
458
459Error ProcessFreeBSD::DoHalt(bool &caused_stop) {
460 Error error;
461
462 if (IsStopped()) {
463 caused_stop = false;
464 } else if (kill(GetID(), SIGSTOP)) {
465 caused_stop = false;
466 error.SetErrorToErrno();
467 } else {
468 caused_stop = true;
469 }
470 return error;
471}
472
473Error ProcessFreeBSD::DoSignal(int signal) {
474 Error error;
475
476 if (kill(GetID(), signal))
477 error.SetErrorToErrno();
478
479 return error;
480}
481
482Error ProcessFreeBSD::DoDestroy() {
483 Error error;
484
485 if (!HasExited()) {
486 assert(m_monitor);
487 m_exit_now = true;
488 if (GetID() == LLDB_INVALID_PROCESS_ID) {
489 error.SetErrorString("invalid process id");
490 return error;
491 }
492 if (!m_monitor->Kill()) {
493 error.SetErrorToErrno();
494 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000495 }
496
Kate Stoneb9c1b512016-09-06 20:57:50 +0000497 SetPrivateState(eStateExited);
498 }
499
500 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000501}
502
Kate Stoneb9c1b512016-09-06 20:57:50 +0000503void ProcessFreeBSD::DoDidExec() {
504 Target *target = &GetTarget();
505 if (target) {
506 PlatformSP platform_sp(target->GetPlatform());
507 assert(platform_sp.get());
508 if (platform_sp) {
509 ProcessInstanceInfo process_info;
510 platform_sp->GetProcessInfo(GetID(), process_info);
511 ModuleSP exe_module_sp;
512 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
513 target->GetArchitecture());
514 FileSpecList executable_search_paths(
515 Target::GetDefaultExecutableSearchPaths());
516 Error error = platform_sp->ResolveExecutable(
517 exe_module_spec, exe_module_sp,
518 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
519 if (!error.Success())
520 return;
521 target->SetExecutableModule(exe_module_sp, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000522 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000524}
525
Kate Stoneb9c1b512016-09-06 20:57:50 +0000526bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
527 bool added_to_set = false;
528 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
529 if (it == m_seen_initial_stop.end()) {
530 m_seen_initial_stop.insert(stop_tid);
531 added_to_set = true;
532 }
533 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000534}
535
Kate Stoneb9c1b512016-09-06 20:57:50 +0000536bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
537 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000538}
539
540FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
542 lldb::tid_t tid) {
543 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000544}
545
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546void ProcessFreeBSD::RefreshStateAfterStop() {
547 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000548 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000549
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 // This method used to only handle one message. Changing it to loop allows
553 // it to handle the case where we hit a breakpoint while handling a different
554 // breakpoint.
555 while (!m_message_queue.empty()) {
556 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 // Resolve the thread this message corresponds to and pass it along.
559 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000560 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
561 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
566 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000567 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000568 thread->Notify(message);
569
570 if (message.GetKind() == ProcessMessage::eExitMessage) {
571 // FIXME: We should tell the user about this, but the limbo message is
572 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000573 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
575
576 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
577 thread_sp.reset();
578 m_seen_initial_stop.erase(tid);
579 }
580
581 m_message_queue.pop();
582 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000583}
584
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585bool ProcessFreeBSD::IsAlive() {
586 StateType state = GetPrivateState();
587 return state != eStateDetached && state != eStateExited &&
588 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000589}
590
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
592 Error &error) {
593 assert(m_monitor);
594 return m_monitor->ReadMemory(vm_addr, buf, size, error);
595}
596
597size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
598 size_t size, Error &error) {
599 assert(m_monitor);
600 return m_monitor->WriteMemory(vm_addr, buf, size, error);
601}
602
603addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
604 Error &error) {
605 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
606
607 unsigned prot = 0;
608 if (permissions & lldb::ePermissionsReadable)
609 prot |= eMmapProtRead;
610 if (permissions & lldb::ePermissionsWritable)
611 prot |= eMmapProtWrite;
612 if (permissions & lldb::ePermissionsExecutable)
613 prot |= eMmapProtExec;
614
615 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
616 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
617 m_addr_to_mmap_size[allocated_addr] = size;
618 error.Clear();
619 } else {
620 allocated_addr = LLDB_INVALID_ADDRESS;
621 error.SetErrorStringWithFormat(
622 "unable to allocate %zu bytes of memory with permissions %s", size,
623 GetPermissionsAsCString(permissions));
624 }
625
626 return allocated_addr;
627}
628
629Error ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
630 Error error;
631 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
632 if (pos != m_addr_to_mmap_size.end() &&
633 InferiorCallMunmap(this, addr, pos->second))
634 m_addr_to_mmap_size.erase(pos);
635 else
636 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
637 addr);
638
639 return error;
640}
641
642size_t
643ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
644 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
645 static const uint8_t g_i386_opcode[] = {0xCC};
646
647 ArchSpec arch = GetTarget().GetArchitecture();
648 const uint8_t *opcode = NULL;
649 size_t opcode_size = 0;
650
651 switch (arch.GetMachine()) {
652 default:
653 assert(false && "CPU type not supported!");
654 break;
655
656 case llvm::Triple::arm: {
657 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
658 // but the linux kernel does otherwise.
659 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
660 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
661
662 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
663 AddressClass addr_class = eAddressClassUnknown;
664
665 if (bp_loc_sp)
666 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
667
668 if (addr_class == eAddressClassCodeAlternateISA ||
669 (addr_class == eAddressClassUnknown &&
670 bp_loc_sp->GetAddress().GetOffset() & 1)) {
671 opcode = g_thumb_breakpoint_opcode;
672 opcode_size = sizeof(g_thumb_breakpoint_opcode);
673 } else {
674 opcode = g_arm_breakpoint_opcode;
675 opcode_size = sizeof(g_arm_breakpoint_opcode);
676 }
677 } break;
678 case llvm::Triple::aarch64:
679 opcode = g_aarch64_opcode;
680 opcode_size = sizeof(g_aarch64_opcode);
681 break;
682
683 case llvm::Triple::x86:
684 case llvm::Triple::x86_64:
685 opcode = g_i386_opcode;
686 opcode_size = sizeof(g_i386_opcode);
687 break;
688 }
689
690 bp_site->SetTrapOpcode(opcode, opcode_size);
691 return opcode_size;
692}
693
694Error ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
695 return EnableSoftwareBreakpoint(bp_site);
696}
697
698Error ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
699 return DisableSoftwareBreakpoint(bp_site);
700}
701
702Error ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
703 Error error;
704 if (wp) {
705 user_id_t watchID = wp->GetID();
706 addr_t addr = wp->GetLoadAddress();
707 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
708 if (log)
709 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
710 watchID);
711 if (wp->IsEnabled()) {
712 if (log)
713 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
714 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
715 watchID, (uint64_t)addr);
716 return error;
717 }
718
719 // Try to find a vacant watchpoint slot in the inferiors' main thread
720 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000721 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
723 m_thread_list.GetThreadAtIndex(0, false).get());
724
725 if (thread)
726 wp_hw_index = thread->FindVacantWatchpointIndex();
727
728 if (wp_hw_index == LLDB_INVALID_INDEX32) {
729 error.SetErrorString("Setting hardware watchpoint failed.");
730 } else {
731 wp->SetHardwareIndex(wp_hw_index);
732 bool wp_enabled = true;
733 uint32_t thread_count = m_thread_list.GetSize(false);
734 for (uint32_t i = 0; i < thread_count; ++i) {
735 thread = static_cast<FreeBSDThread *>(
736 m_thread_list.GetThreadAtIndex(i, false).get());
737 if (thread)
738 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
739 else
740 wp_enabled = false;
741 }
742 if (wp_enabled) {
743 wp->SetEnabled(true, notify);
744 return error;
745 } else {
746 // Watchpoint enabling failed on at least one
747 // of the threads so roll back all of them
748 DisableWatchpoint(wp, false);
749 error.SetErrorString("Setting hardware watchpoint failed");
750 }
751 }
752 } else
753 error.SetErrorString("Watchpoint argument was NULL.");
754 return error;
755}
756
757Error ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
758 Error error;
759 if (wp) {
760 user_id_t watchID = wp->GetID();
761 addr_t addr = wp->GetLoadAddress();
762 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
763 if (log)
764 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
765 watchID);
766 if (!wp->IsEnabled()) {
767 if (log)
768 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
769 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
770 watchID, (uint64_t)addr);
771 // This is needed (for now) to keep watchpoints disabled correctly
772 wp->SetEnabled(false, notify);
773 return error;
774 }
775
776 if (wp->IsHardware()) {
777 bool wp_disabled = true;
778 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
779 uint32_t thread_count = m_thread_list.GetSize(false);
780 for (uint32_t i = 0; i < thread_count; ++i) {
781 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
782 m_thread_list.GetThreadAtIndex(i, false).get());
783 if (thread)
784 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
785 else
786 wp_disabled = false;
787 }
788 if (wp_disabled) {
789 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
790 wp->SetEnabled(false, notify);
791 return error;
792 } else
793 error.SetErrorString("Disabling hardware watchpoint failed");
794 }
795 } else
796 error.SetErrorString("Watchpoint argument was NULL.");
797 return error;
798}
799
800Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
801 Error error;
802 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
803 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
804 m_thread_list.GetThreadAtIndex(0, false).get());
805 if (thread)
806 num = thread->NumSupportedHardwareWatchpoints();
807 else
808 error.SetErrorString("Process does not exist.");
809 return error;
810}
811
812Error ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
813 Error error = GetWatchpointSupportInfo(num);
814 // Watchpoints trigger and halt the inferior after
815 // the corresponding instruction has been executed.
816 after = true;
817 return error;
818}
819
820uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
821 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
822 // Do not allow recursive updates.
823 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000824}
825
826#if 0
827bool
828ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
829{
830 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
831 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
832 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
833
834 bool has_updated = false;
835 // Update the process thread list with this new thread.
836 // FIXME: We should be using tid, not pid.
837 assert(m_monitor);
838 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
839 if (!thread_sp) {
840 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
841 has_updated = true;
842 }
843
844 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
845 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
846 new_thread_list.AddThread(thread_sp);
847
848 return has_updated; // the list has been updated
849}
850#endif
851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852ByteOrder ProcessFreeBSD::GetByteOrder() const {
853 // FIXME: We should be able to extract this value directly. See comment in
854 // ProcessFreeBSD().
855 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000856}
857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error) {
859 ssize_t status;
860 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
861 error.SetErrorToErrno();
862 return 0;
863 }
864 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000865}
866
867//------------------------------------------------------------------------------
868// Utility functions.
869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870bool ProcessFreeBSD::HasExited() {
871 switch (GetPrivateState()) {
872 default:
873 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000874
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 case eStateDetached:
876 case eStateExited:
877 return true;
878 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000879
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000881}
882
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883bool ProcessFreeBSD::IsStopped() {
884 switch (GetPrivateState()) {
885 default:
886 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 case eStateStopped:
889 case eStateCrashed:
890 case eStateSuspended:
891 return true;
892 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000895}
896
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897bool ProcessFreeBSD::IsAThreadRunning() {
898 bool is_running = false;
899 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
900 uint32_t thread_count = m_thread_list.GetSize(false);
901 for (uint32_t i = 0; i < thread_count; ++i) {
902 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
903 m_thread_list.GetThreadAtIndex(i, false).get());
904 StateType thread_state = thread->GetState();
905 if (thread_state == eStateRunning || thread_state == eStateStepping) {
906 is_running = true;
907 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000908 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 }
910 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000911}
912
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913const DataBufferSP ProcessFreeBSD::GetAuxvData() {
914 // If we're the local platform, we can ask the host for auxv data.
915 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000916 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000917
Pavel Labath5b116232017-03-17 11:33:57 +0000918 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000919 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
920 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
921
Pavel Labath5b116232017-03-17 11:33:57 +0000922 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000923 perror("sysctl failed on auxv");
924 buf_sp.reset();
925 }
926
927 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000928}
Ed Maste31f01802017-01-24 14:34:49 +0000929
930struct EmulatorBaton {
931 ProcessFreeBSD *m_process;
932 RegisterContext *m_reg_context;
933
934 // eRegisterKindDWARF -> RegisterValue
935 std::unordered_map<uint32_t, RegisterValue> m_register_values;
936
937 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
938 : m_process(process), m_reg_context(reg_context) {}
939};
940
941static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
942 const EmulateInstruction::Context &context,
943 lldb::addr_t addr, void *dst, size_t length) {
944 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
945
946 Error error;
947 size_t bytes_read =
948 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
949 if (!error.Success())
950 bytes_read = 0;
951 return bytes_read;
952}
953
954static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
955 const RegisterInfo *reg_info,
956 RegisterValue &reg_value) {
957 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
958
959 auto it = emulator_baton->m_register_values.find(
960 reg_info->kinds[eRegisterKindDWARF]);
961 if (it != emulator_baton->m_register_values.end()) {
962 reg_value = it->second;
963 return true;
964 }
965
966 // The emulator only fills in the dwarf register numbers (and in some cases
967 // the generic register numbers). Get the full register info from the
968 // register context based on the dwarf register numbers.
969 const RegisterInfo *full_reg_info =
970 emulator_baton->m_reg_context->GetRegisterInfo(
971 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
972
973 bool error =
974 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
975 return error;
976}
977
978static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
979 const EmulateInstruction::Context &context,
980 const RegisterInfo *reg_info,
981 const RegisterValue &reg_value) {
982 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
983 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
984 reg_value;
985 return true;
986}
987
988static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
989 const EmulateInstruction::Context &context,
990 lldb::addr_t addr, const void *dst,
991 size_t length) {
992 return length;
993}
994
995bool ProcessFreeBSD::SingleStepBreakpointHit(
996 void *baton, lldb_private::StoppointCallbackContext *context,
997 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
998 return false;
999}
1000
1001Error ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
1002 lldb::addr_t addr) {
1003 Error error;
1004
1005 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
1006 if (log) {
1007 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1008 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
1009 }
1010
1011 // Validate the address.
1012 if (addr == LLDB_INVALID_ADDRESS)
1013 return Error("ProcessFreeBSD::%s invalid load address specified.",
1014 __FUNCTION__);
1015
1016 Breakpoint *const sw_step_break =
1017 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
1018 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
1019 sw_step_break->SetBreakpointKind("software-signle-step");
1020
1021 if (log)
1022 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
1023 __FUNCTION__, addr);
1024
1025 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
1026 return Error();
1027}
1028
1029bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1030 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1031 if (!thread)
1032 return false;
1033
1034 assert(thread->GetRegisterContext());
1035 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1036
1037 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1038 if (iter == m_threads_stepping_with_breakpoint.end())
1039 return false;
1040
1041 lldb::break_id_t bp_id = iter->second;
1042 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1043 if (!bp)
1044 return false;
1045
1046 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1047 if (!bp_loc)
1048 return false;
1049
1050 GetTarget().RemoveBreakpointByID(bp_id);
1051 m_threads_stepping_with_breakpoint.erase(tid);
1052 return true;
1053}
1054
1055bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1056 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1057 if (arch.GetMachine() == llvm::Triple::arm ||
1058 arch.GetMachine() == llvm::Triple::mips64 ||
1059 arch.GetMachine() == llvm::Triple::mips64el ||
1060 arch.GetMachine() == llvm::Triple::mips ||
1061 arch.GetMachine() == llvm::Triple::mipsel)
1062 return false;
1063 return true;
1064}
1065
1066Error ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
1067 std::unique_ptr<EmulateInstruction> emulator_ap(
1068 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1069 eInstructionTypePCModifying, nullptr));
1070
1071 if (emulator_ap == nullptr)
1072 return Error("Instruction emulator not found!");
1073
1074 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1075 m_thread_list.FindThreadByID(tid, false).get());
1076 if (thread == NULL)
1077 return Error("Thread not found not found!");
1078
1079 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1080
1081 EmulatorBaton baton(this, register_context_sp.get());
1082 emulator_ap->SetBaton(&baton);
1083 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1084 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1085 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1086 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1087
1088 if (!emulator_ap->ReadInstruction())
1089 return Error("Read instruction failed!");
1090
1091 bool emulation_result =
1092 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1093 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1094 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1095 auto pc_it =
1096 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1097
1098 lldb::addr_t next_pc;
1099 if (emulation_result) {
1100 assert(pc_it != baton.m_register_values.end() &&
1101 "Emulation was successful but PC wasn't updated");
1102 next_pc = pc_it->second.GetAsUInt64();
1103 } else if (pc_it == baton.m_register_values.end()) {
1104 // Emulate instruction failed and it haven't changed PC. Advance PC
1105 // with the size of the current opcode because the emulation of all
1106 // PC modifying instruction should be successful. The failure most
1107 // likely caused by a not supported instruction which don't modify PC.
1108 next_pc =
1109 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1110 } else {
1111 // The instruction emulation failed after it modified the PC. It is an
1112 // unknown error where we can't continue because the next instruction is
1113 // modifying the PC but we don't know how.
1114 return Error("Instruction emulation failed unexpectedly");
1115 }
1116
1117 SetSoftwareSingleStepBreakpoint(tid, next_pc);
1118 return Error();
1119}