blob: cc039c2fb9d8aa716402e310fec7663099371f75 [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"
Pavel Labathf0a6d8a2017-04-11 12:26:25 +000035#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000036#include "Plugins/Process/Utility/FreeBSDSignals.h"
37#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
38#include "ProcessFreeBSD.h"
39#include "ProcessMonitor.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
Zachary Turner97206d52017-05-12 04:51:55 +0000114Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
115 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 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
Zachary Turner97206d52017-05-12 04:51:55 +0000130Status ProcessFreeBSD::DoResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 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) {
Zachary Turner97206d52017-05-12 04:51:55 +0000150 Status error = SetupSoftwareSingleStepping(*t_pos);
Ed Maste31f01802017-01-24 14:34:49 +0000151 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
Zachary Turner97206d52017-05-12 04:51:55 +0000171 return Status();
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
Zachary Turner97206d52017-05-12 04:51:55 +0000212Status ProcessFreeBSD::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213 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
Zachary Turner97206d52017-05-12 04:51:55 +0000296Status
297ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
298 const ProcessAttachInfo &attach_info) {
299 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000301
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000303 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000304
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000306
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000308 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309
310 PlatformSP platform_sp(GetTarget().GetPlatform());
311 assert(platform_sp.get());
312 if (!platform_sp)
313 return error; // FIXME: Detatch?
314
315 // Find out what we can about this process
316 ProcessInstanceInfo process_info;
317 platform_sp->GetProcessInfo(pid, process_info);
318
319 // Resolve the executable module
320 ModuleSP exe_module_sp;
321 FileSpecList executable_search_paths(
322 Target::GetDefaultExecutableSearchPaths());
323 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
324 GetTarget().GetArchitecture());
325 error = platform_sp->ResolveExecutable(
326 exe_module_spec, exe_module_sp,
327 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
328 if (!error.Success())
329 return error;
330
331 // Fix the target architecture if necessary
332 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
333 if (module_arch.IsValid() &&
334 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
335 GetTarget().SetArchitecture(module_arch);
336
337 // Initialize the target module list
338 GetTarget().SetExecutableModule(exe_module_sp, true);
339
340 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
341
342 SetID(pid);
343
344 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000345}
346
Zachary Turner97206d52017-05-12 04:51:55 +0000347Status ProcessFreeBSD::WillLaunch(Module *module) {
348 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000350}
351
352FileSpec
353ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 const FileSpec &default_file_spec,
355 const FileSpec &dbg_pts_file_spec) {
356 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000357
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
359 file_spec = file_action->GetFileSpec();
360 // By default the stdio paths passed in will be pseudo-terminal
361 // (/dev/pts). If so, convert to using a different default path
362 // instead to redirect I/O to the debugger console. This should
363 // also handle user overrides to /dev/null or a different file.
364 if (!file_spec || file_spec == dbg_pts_file_spec)
365 file_spec = default_file_spec;
366 }
367 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000368}
369
Zachary Turner97206d52017-05-12 04:51:55 +0000370Status ProcessFreeBSD::DoLaunch(Module *module,
371 ProcessLaunchInfo &launch_info) {
372 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000374
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 FileSpec working_dir = launch_info.GetWorkingDirectory();
Zachary Turner7d86ee52017-03-08 17:56:08 +0000376 namespace fs = llvm::sys::fs;
377 if (working_dir && (!working_dir.ResolvePath() ||
378 !fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 error.SetErrorStringWithFormat("No such file or directory: %s",
380 working_dir.GetCString());
381 return error;
382 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000383
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000385
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 // Default of empty will mean to use existing open file descriptors
389 FileSpec stdin_file_spec{};
390 FileSpec stdout_file_spec{};
391 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
394 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
397 stdin_file_spec =
398 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
401 stdout_file_spec =
402 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
405 stderr_file_spec =
406 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 m_monitor = new ProcessMonitor(
409 this, module, launch_info.GetArguments().GetConstArgumentVector(),
Pavel Labath3ff377a2018-01-10 12:25:48 +0000410 launch_info.GetEnvironment().getEnvp(), stdin_file_spec, stdout_file_spec,
411 stderr_file_spec, working_dir, launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 if (!error.Success())
416 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 int terminal = m_monitor->GetTerminalFD();
419 if (terminal >= 0) {
420// The reader thread will close the file descriptor when done, so we pass it a
421// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000422#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
424 if (stdio == -1) {
425 error.SetErrorToErrno();
426 return error;
427 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000428#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
430 int stdio = fcntl(terminal, F_DUPFD, 0);
431 if (stdio == -1) {
432 error.SetErrorToErrno();
433 return error;
434 }
435 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
436 if (stdio == -1) {
437 error.SetErrorToErrno();
438 return error;
439 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000440#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 SetSTDIOFileDescriptor(stdio);
442 }
443
444 SetID(m_monitor->GetPID());
445 return error;
446}
447
448void ProcessFreeBSD::DidLaunch() {}
449
450addr_t ProcessFreeBSD::GetImageInfoAddress() {
451 Target *target = &GetTarget();
452 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
453 Address addr = obj_file->GetImageInfoAddress(target);
454
455 if (addr.IsValid())
456 return addr.GetLoadAddress(target);
457 return LLDB_INVALID_ADDRESS;
458}
459
Zachary Turner97206d52017-05-12 04:51:55 +0000460Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
461 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462
463 if (IsStopped()) {
464 caused_stop = false;
465 } else if (kill(GetID(), SIGSTOP)) {
466 caused_stop = false;
467 error.SetErrorToErrno();
468 } else {
469 caused_stop = true;
470 }
471 return error;
472}
473
Zachary Turner97206d52017-05-12 04:51:55 +0000474Status ProcessFreeBSD::DoSignal(int signal) {
475 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000476
477 if (kill(GetID(), signal))
478 error.SetErrorToErrno();
479
480 return error;
481}
482
Zachary Turner97206d52017-05-12 04:51:55 +0000483Status ProcessFreeBSD::DoDestroy() {
484 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485
486 if (!HasExited()) {
487 assert(m_monitor);
488 m_exit_now = true;
489 if (GetID() == LLDB_INVALID_PROCESS_ID) {
490 error.SetErrorString("invalid process id");
491 return error;
492 }
493 if (!m_monitor->Kill()) {
494 error.SetErrorToErrno();
495 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000496 }
497
Kate Stoneb9c1b512016-09-06 20:57:50 +0000498 SetPrivateState(eStateExited);
499 }
500
501 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000502}
503
Kate Stoneb9c1b512016-09-06 20:57:50 +0000504void ProcessFreeBSD::DoDidExec() {
505 Target *target = &GetTarget();
506 if (target) {
507 PlatformSP platform_sp(target->GetPlatform());
508 assert(platform_sp.get());
509 if (platform_sp) {
510 ProcessInstanceInfo process_info;
511 platform_sp->GetProcessInfo(GetID(), process_info);
512 ModuleSP exe_module_sp;
513 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
514 target->GetArchitecture());
515 FileSpecList executable_search_paths(
516 Target::GetDefaultExecutableSearchPaths());
Zachary Turner97206d52017-05-12 04:51:55 +0000517 Status error = platform_sp->ResolveExecutable(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 exe_module_spec, exe_module_sp,
519 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
520 if (!error.Success())
521 return;
522 target->SetExecutableModule(exe_module_sp, true);
Ed Mastefe5a6422015-07-28 15:45:57 +0000523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000525}
526
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
528 bool added_to_set = false;
529 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
530 if (it == m_seen_initial_stop.end()) {
531 m_seen_initial_stop.insert(stop_tid);
532 added_to_set = true;
533 }
534 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000535}
536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
538 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000539}
540
541FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000542ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
543 lldb::tid_t tid) {
544 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000545}
546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547void ProcessFreeBSD::RefreshStateAfterStop() {
548 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000549 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000550
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000552
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 // This method used to only handle one message. Changing it to loop allows
554 // it to handle the case where we hit a breakpoint while handling a different
555 // breakpoint.
556 while (!m_message_queue.empty()) {
557 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000558
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 // Resolve the thread this message corresponds to and pass it along.
560 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000561 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
562 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000563
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
567 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000568 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569 thread->Notify(message);
570
571 if (message.GetKind() == ProcessMessage::eExitMessage) {
572 // FIXME: We should tell the user about this, but the limbo message is
573 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000574 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000575 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
576
577 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
578 thread_sp.reset();
579 m_seen_initial_stop.erase(tid);
580 }
581
582 m_message_queue.pop();
583 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000584}
585
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586bool ProcessFreeBSD::IsAlive() {
587 StateType state = GetPrivateState();
588 return state != eStateDetached && state != eStateExited &&
589 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000590}
591
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000593 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000594 assert(m_monitor);
595 return m_monitor->ReadMemory(vm_addr, buf, size, error);
596}
597
598size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +0000599 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600 assert(m_monitor);
601 return m_monitor->WriteMemory(vm_addr, buf, size, error);
602}
603
604addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000605 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
607
608 unsigned prot = 0;
609 if (permissions & lldb::ePermissionsReadable)
610 prot |= eMmapProtRead;
611 if (permissions & lldb::ePermissionsWritable)
612 prot |= eMmapProtWrite;
613 if (permissions & lldb::ePermissionsExecutable)
614 prot |= eMmapProtExec;
615
616 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
617 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
618 m_addr_to_mmap_size[allocated_addr] = size;
619 error.Clear();
620 } else {
621 allocated_addr = LLDB_INVALID_ADDRESS;
622 error.SetErrorStringWithFormat(
623 "unable to allocate %zu bytes of memory with permissions %s", size,
624 GetPermissionsAsCString(permissions));
625 }
626
627 return allocated_addr;
628}
629
Zachary Turner97206d52017-05-12 04:51:55 +0000630Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
631 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
633 if (pos != m_addr_to_mmap_size.end() &&
634 InferiorCallMunmap(this, addr, pos->second))
635 m_addr_to_mmap_size.erase(pos);
636 else
637 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
638 addr);
639
640 return error;
641}
642
643size_t
644ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
645 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
646 static const uint8_t g_i386_opcode[] = {0xCC};
647
648 ArchSpec arch = GetTarget().GetArchitecture();
649 const uint8_t *opcode = NULL;
650 size_t opcode_size = 0;
651
652 switch (arch.GetMachine()) {
653 default:
654 assert(false && "CPU type not supported!");
655 break;
656
657 case llvm::Triple::arm: {
658 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
659 // but the linux kernel does otherwise.
660 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
661 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
662
663 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
664 AddressClass addr_class = eAddressClassUnknown;
665
666 if (bp_loc_sp)
667 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
668
669 if (addr_class == eAddressClassCodeAlternateISA ||
670 (addr_class == eAddressClassUnknown &&
671 bp_loc_sp->GetAddress().GetOffset() & 1)) {
672 opcode = g_thumb_breakpoint_opcode;
673 opcode_size = sizeof(g_thumb_breakpoint_opcode);
674 } else {
675 opcode = g_arm_breakpoint_opcode;
676 opcode_size = sizeof(g_arm_breakpoint_opcode);
677 }
678 } break;
679 case llvm::Triple::aarch64:
680 opcode = g_aarch64_opcode;
681 opcode_size = sizeof(g_aarch64_opcode);
682 break;
683
684 case llvm::Triple::x86:
685 case llvm::Triple::x86_64:
686 opcode = g_i386_opcode;
687 opcode_size = sizeof(g_i386_opcode);
688 break;
689 }
690
691 bp_site->SetTrapOpcode(opcode, opcode_size);
692 return opcode_size;
693}
694
Zachary Turner97206d52017-05-12 04:51:55 +0000695Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 return EnableSoftwareBreakpoint(bp_site);
697}
698
Zachary Turner97206d52017-05-12 04:51:55 +0000699Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700 return DisableSoftwareBreakpoint(bp_site);
701}
702
Zachary Turner97206d52017-05-12 04:51:55 +0000703Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
704 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 if (wp) {
706 user_id_t watchID = wp->GetID();
707 addr_t addr = wp->GetLoadAddress();
708 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
709 if (log)
710 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
711 watchID);
712 if (wp->IsEnabled()) {
713 if (log)
714 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
715 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
716 watchID, (uint64_t)addr);
717 return error;
718 }
719
720 // Try to find a vacant watchpoint slot in the inferiors' main thread
721 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000722 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
724 m_thread_list.GetThreadAtIndex(0, false).get());
725
726 if (thread)
727 wp_hw_index = thread->FindVacantWatchpointIndex();
728
729 if (wp_hw_index == LLDB_INVALID_INDEX32) {
730 error.SetErrorString("Setting hardware watchpoint failed.");
731 } else {
732 wp->SetHardwareIndex(wp_hw_index);
733 bool wp_enabled = true;
734 uint32_t thread_count = m_thread_list.GetSize(false);
735 for (uint32_t i = 0; i < thread_count; ++i) {
736 thread = static_cast<FreeBSDThread *>(
737 m_thread_list.GetThreadAtIndex(i, false).get());
738 if (thread)
739 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
740 else
741 wp_enabled = false;
742 }
743 if (wp_enabled) {
744 wp->SetEnabled(true, notify);
745 return error;
746 } else {
747 // Watchpoint enabling failed on at least one
748 // of the threads so roll back all of them
749 DisableWatchpoint(wp, false);
750 error.SetErrorString("Setting hardware watchpoint failed");
751 }
752 }
753 } else
754 error.SetErrorString("Watchpoint argument was NULL.");
755 return error;
756}
757
Zachary Turner97206d52017-05-12 04:51:55 +0000758Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
759 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 if (wp) {
761 user_id_t watchID = wp->GetID();
762 addr_t addr = wp->GetLoadAddress();
763 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
764 if (log)
765 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
766 watchID);
767 if (!wp->IsEnabled()) {
768 if (log)
769 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
770 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
771 watchID, (uint64_t)addr);
772 // This is needed (for now) to keep watchpoints disabled correctly
773 wp->SetEnabled(false, notify);
774 return error;
775 }
776
777 if (wp->IsHardware()) {
778 bool wp_disabled = true;
779 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
780 uint32_t thread_count = m_thread_list.GetSize(false);
781 for (uint32_t i = 0; i < thread_count; ++i) {
782 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
783 m_thread_list.GetThreadAtIndex(i, false).get());
784 if (thread)
785 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
786 else
787 wp_disabled = false;
788 }
789 if (wp_disabled) {
790 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
791 wp->SetEnabled(false, notify);
792 return error;
793 } else
794 error.SetErrorString("Disabling hardware watchpoint failed");
795 }
796 } else
797 error.SetErrorString("Watchpoint argument was NULL.");
798 return error;
799}
800
Zachary Turner97206d52017-05-12 04:51:55 +0000801Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
802 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
804 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
805 m_thread_list.GetThreadAtIndex(0, false).get());
806 if (thread)
807 num = thread->NumSupportedHardwareWatchpoints();
808 else
809 error.SetErrorString("Process does not exist.");
810 return error;
811}
812
Zachary Turner97206d52017-05-12 04:51:55 +0000813Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
814 Status error = GetWatchpointSupportInfo(num);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 // Watchpoints trigger and halt the inferior after
816 // the corresponding instruction has been executed.
817 after = true;
818 return error;
819}
820
821uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
822 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
823 // Do not allow recursive updates.
824 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000825}
826
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827ByteOrder ProcessFreeBSD::GetByteOrder() const {
828 // FIXME: We should be able to extract this value directly. See comment in
829 // ProcessFreeBSD().
830 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000831}
832
Zachary Turner97206d52017-05-12 04:51:55 +0000833size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000834 ssize_t status;
835 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
836 error.SetErrorToErrno();
837 return 0;
838 }
839 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000840}
841
842//------------------------------------------------------------------------------
843// Utility functions.
844
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845bool ProcessFreeBSD::HasExited() {
846 switch (GetPrivateState()) {
847 default:
848 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000849
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 case eStateDetached:
851 case eStateExited:
852 return true;
853 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000856}
857
Kate Stoneb9c1b512016-09-06 20:57:50 +0000858bool ProcessFreeBSD::IsStopped() {
859 switch (GetPrivateState()) {
860 default:
861 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 case eStateStopped:
864 case eStateCrashed:
865 case eStateSuspended:
866 return true;
867 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000870}
871
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872bool ProcessFreeBSD::IsAThreadRunning() {
873 bool is_running = false;
874 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
875 uint32_t thread_count = m_thread_list.GetSize(false);
876 for (uint32_t i = 0; i < thread_count; ++i) {
877 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
878 m_thread_list.GetThreadAtIndex(i, false).get());
879 StateType thread_state = thread->GetState();
880 if (thread_state == eStateRunning || thread_state == eStateStepping) {
881 is_running = true;
882 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 }
885 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000886}
887
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888const DataBufferSP ProcessFreeBSD::GetAuxvData() {
889 // If we're the local platform, we can ask the host for auxv data.
890 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000891 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000892
Pavel Labath5b116232017-03-17 11:33:57 +0000893 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000894 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
895 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
896
Pavel Labath5b116232017-03-17 11:33:57 +0000897 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000898 perror("sysctl failed on auxv");
899 buf_sp.reset();
900 }
901
902 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000903}
Ed Maste31f01802017-01-24 14:34:49 +0000904
905struct EmulatorBaton {
906 ProcessFreeBSD *m_process;
907 RegisterContext *m_reg_context;
908
909 // eRegisterKindDWARF -> RegisterValue
910 std::unordered_map<uint32_t, RegisterValue> m_register_values;
911
912 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
913 : m_process(process), m_reg_context(reg_context) {}
914};
915
916static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
917 const EmulateInstruction::Context &context,
918 lldb::addr_t addr, void *dst, size_t length) {
919 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
920
Zachary Turner97206d52017-05-12 04:51:55 +0000921 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000922 size_t bytes_read =
923 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
924 if (!error.Success())
925 bytes_read = 0;
926 return bytes_read;
927}
928
929static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
930 const RegisterInfo *reg_info,
931 RegisterValue &reg_value) {
932 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
933
934 auto it = emulator_baton->m_register_values.find(
935 reg_info->kinds[eRegisterKindDWARF]);
936 if (it != emulator_baton->m_register_values.end()) {
937 reg_value = it->second;
938 return true;
939 }
940
941 // The emulator only fills in the dwarf register numbers (and in some cases
942 // the generic register numbers). Get the full register info from the
943 // register context based on the dwarf register numbers.
944 const RegisterInfo *full_reg_info =
945 emulator_baton->m_reg_context->GetRegisterInfo(
946 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
947
948 bool error =
949 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
950 return error;
951}
952
953static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
954 const EmulateInstruction::Context &context,
955 const RegisterInfo *reg_info,
956 const RegisterValue &reg_value) {
957 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
958 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
959 reg_value;
960 return true;
961}
962
963static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
964 const EmulateInstruction::Context &context,
965 lldb::addr_t addr, const void *dst,
966 size_t length) {
967 return length;
968}
969
970bool ProcessFreeBSD::SingleStepBreakpointHit(
971 void *baton, lldb_private::StoppointCallbackContext *context,
972 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
973 return false;
974}
975
Zachary Turner97206d52017-05-12 04:51:55 +0000976Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
977 lldb::addr_t addr) {
978 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000979
980 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
981 if (log) {
982 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
983 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
984 }
985
986 // Validate the address.
987 if (addr == LLDB_INVALID_ADDRESS)
Zachary Turner97206d52017-05-12 04:51:55 +0000988 return Status("ProcessFreeBSD::%s invalid load address specified.",
989 __FUNCTION__);
Ed Maste31f01802017-01-24 14:34:49 +0000990
991 Breakpoint *const sw_step_break =
992 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
993 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
994 sw_step_break->SetBreakpointKind("software-signle-step");
995
996 if (log)
997 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
998 __FUNCTION__, addr);
999
1000 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
Zachary Turner97206d52017-05-12 04:51:55 +00001001 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001002}
1003
1004bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1005 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1006 if (!thread)
1007 return false;
1008
1009 assert(thread->GetRegisterContext());
1010 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1011
1012 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1013 if (iter == m_threads_stepping_with_breakpoint.end())
1014 return false;
1015
1016 lldb::break_id_t bp_id = iter->second;
1017 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1018 if (!bp)
1019 return false;
1020
1021 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1022 if (!bp_loc)
1023 return false;
1024
1025 GetTarget().RemoveBreakpointByID(bp_id);
1026 m_threads_stepping_with_breakpoint.erase(tid);
1027 return true;
1028}
1029
1030bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1031 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1032 if (arch.GetMachine() == llvm::Triple::arm ||
1033 arch.GetMachine() == llvm::Triple::mips64 ||
1034 arch.GetMachine() == llvm::Triple::mips64el ||
1035 arch.GetMachine() == llvm::Triple::mips ||
1036 arch.GetMachine() == llvm::Triple::mipsel)
1037 return false;
1038 return true;
1039}
1040
Zachary Turner97206d52017-05-12 04:51:55 +00001041Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
Ed Maste31f01802017-01-24 14:34:49 +00001042 std::unique_ptr<EmulateInstruction> emulator_ap(
1043 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1044 eInstructionTypePCModifying, nullptr));
1045
1046 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001047 return Status("Instruction emulator not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001048
1049 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1050 m_thread_list.FindThreadByID(tid, false).get());
1051 if (thread == NULL)
Zachary Turner97206d52017-05-12 04:51:55 +00001052 return Status("Thread not found not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001053
1054 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1055
1056 EmulatorBaton baton(this, register_context_sp.get());
1057 emulator_ap->SetBaton(&baton);
1058 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1059 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1060 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1061 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1062
1063 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001064 return Status("Read instruction failed!");
Ed Maste31f01802017-01-24 14:34:49 +00001065
1066 bool emulation_result =
1067 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1068 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1069 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1070 auto pc_it =
1071 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1072
1073 lldb::addr_t next_pc;
1074 if (emulation_result) {
1075 assert(pc_it != baton.m_register_values.end() &&
1076 "Emulation was successful but PC wasn't updated");
1077 next_pc = pc_it->second.GetAsUInt64();
1078 } else if (pc_it == baton.m_register_values.end()) {
1079 // Emulate instruction failed and it haven't changed PC. Advance PC
1080 // with the size of the current opcode because the emulation of all
1081 // PC modifying instruction should be successful. The failure most
1082 // likely caused by a not supported instruction which don't modify PC.
1083 next_pc =
1084 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1085 } else {
1086 // The instruction emulation failed after it modified the PC. It is an
1087 // unknown error where we can't continue because the next instruction is
1088 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001089 return Status("Instruction emulation failed unexpectedly");
Ed Maste31f01802017-01-24 14:34:49 +00001090 }
1091
1092 SetSoftwareSingleStepBreakpoint(tid, next_pc);
Zachary Turner97206d52017-05-12 04:51:55 +00001093 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001094}