blob: a13d4bcc4ecb5cdb2966988e095ce4f0db53e24d [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
Johnny Chen9ed5b492012-01-05 21:48:15 +000011#include <errno.h>
Pavel Labathb7f0f452017-03-17 11:08:40 +000012#include <pthread.h>
13#include <pthread_np.h>
14#include <stdlib.h>
15#include <sys/sysctl.h>
16#include <sys/types.h>
17#include <sys/user.h>
Pavel Labath5b116232017-03-17 11:33:57 +000018#include <machine/elf.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000019
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000020#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000021#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000022
Johnny Chen9ed5b492012-01-05 21:48:15 +000023#include "lldb/Core/PluginManager.h"
Jonas Devlieghere60cf3f82018-11-01 17:35:31 +000024#include "lldb/Host/FileSystem.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000025#include "lldb/Host/Host.h"
26#include "lldb/Symbol/ObjectFile.h"
27#include "lldb/Target/DynamicLoader.h"
28#include "lldb/Target/Target.h"
Pavel Labathd821c992018-08-07 11:07:21 +000029#include "lldb/Utility/RegisterValue.h"
30#include "lldb/Utility/State.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000031
Ed Maste7fd845c2013-12-09 15:51:17 +000032#include "FreeBSDThread.h"
Pavel Labathf0a6d8a2017-04-11 12:26:25 +000033#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000034#include "Plugins/Process/Utility/FreeBSDSignals.h"
35#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
36#include "ProcessFreeBSD.h"
37#include "ProcessMonitor.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000038
Ed Mastefe5a6422015-07-28 15:45:57 +000039#include "lldb/Breakpoint/BreakpointLocation.h"
40#include "lldb/Breakpoint/Watchpoint.h"
41#include "lldb/Core/Module.h"
42#include "lldb/Core/ModuleSpec.h"
43#include "lldb/Core/PluginManager.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000044#include "lldb/Host/Host.h"
45#include "lldb/Symbol/ObjectFile.h"
46#include "lldb/Target/DynamicLoader.h"
47#include "lldb/Target/Platform.h"
48#include "lldb/Target/Target.h"
Pavel Labath5b116232017-03-17 11:33:57 +000049#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner5713a052017-03-22 18:40:07 +000050#include "lldb/Utility/FileSpec.h"
Pavel Labathd821c992018-08-07 11:07:21 +000051#include "lldb/Utility/State.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000052
53#include "lldb/Host/posix/Fcntl.h"
54
Zachary Turner7d86ee52017-03-08 17:56:08 +000055#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000056#include "llvm/Support/Threading.h"
57
Johnny Chen9ed5b492012-01-05 21:48:15 +000058using namespace lldb;
59using namespace lldb_private;
60
Kate Stoneb9c1b512016-09-06 20:57:50 +000061namespace {
62UnixSignalsSP &GetFreeBSDSignals() {
63 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
64 return s_freebsd_signals_sp;
65}
Todd Fiala4ceced32014-08-29 17:35:57 +000066}
67
Johnny Chen9ed5b492012-01-05 21:48:15 +000068//------------------------------------------------------------------------------
69// Static functions.
70
Greg Clayton29d19302012-02-27 18:40:48 +000071lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000072ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000073 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000074 const FileSpec *crash_file_path) {
75 lldb::ProcessSP process_sp;
76 if (crash_file_path == NULL)
77 process_sp.reset(
78 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
79 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000080}
81
Kate Stoneb9c1b512016-09-06 20:57:50 +000082void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000083 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000084
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000085 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 PluginManager::RegisterPlugin(GetPluginNameStatic(),
87 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000088 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000089}
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
92 static ConstString g_name("freebsd");
93 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000094}
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
97 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000098}
99
100//------------------------------------------------------------------------------
101// ProcessInterface protocol.
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
104 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000105}
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000110
Zachary Turner97206d52017-05-12 04:51:55 +0000111Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
112 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113 if (keep_stopped) {
114 error.SetErrorString("Detaching with keep_stopped true is not currently "
115 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000116 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 }
118
119 error = m_monitor->Detach(GetID());
120
121 if (error.Success())
122 SetPrivateState(eStateDetached);
123
124 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000125}
126
Zachary Turner97206d52017-05-12 04:51:55 +0000127Status ProcessFreeBSD::DoResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
133 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000134 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
137 t_end = m_run_tids.end();
138 t_pos != t_end; ++t_pos) {
139 m_monitor->ThreadSuspend(*t_pos, false);
140 }
141 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
142 t_end = m_step_tids.end();
143 t_pos != t_end; ++t_pos) {
144 m_monitor->ThreadSuspend(*t_pos, false);
145 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000146 if (software_single_step) {
Zachary Turner97206d52017-05-12 04:51:55 +0000147 Status error = SetupSoftwareSingleStepping(*t_pos);
Ed Maste31f01802017-01-24 14:34:49 +0000148 if (error.Fail())
149 return error;
150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 }
152 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
153 t_end = m_suspend_tids.end();
154 t_pos != t_end; ++t_pos) {
155 m_monitor->ThreadSuspend(*t_pos, true);
156 // XXX Cannot PT_CONTINUE properly with suspended threads.
157 do_step = true;
158 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 if (log)
161 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
162 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000163 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 m_monitor->SingleStep(GetID(), m_resume_signo);
165 else
166 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000167
Zachary Turner97206d52017-05-12 04:51:55 +0000168 return Status();
Ed Maste7fd845c2013-12-09 15:51:17 +0000169}
170
Kate Stoneb9c1b512016-09-06 20:57:50 +0000171bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
172 ThreadList &new_thread_list) {
173 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
174 if (log)
175 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
176 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000177
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 std::vector<lldb::pid_t> tds;
179 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
180 return false;
181 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000182
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 ThreadList old_thread_list_copy(old_thread_list);
184 for (size_t i = 0; i < tds.size(); ++i) {
185 tid_t tid = tds[i];
186 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
187 if (!thread_sp) {
188 thread_sp.reset(new FreeBSDThread(*this, tid));
189 if (log)
190 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
191 } else {
192 if (log)
193 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
194 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000195 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 new_thread_list.AddThread(thread_sp);
197 }
198 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
199 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
200 if (old_thread_sp) {
201 if (log)
202 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000203 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000207}
Ed Maste7fd845c2013-12-09 15:51:17 +0000208
Zachary Turner97206d52017-05-12 04:51:55 +0000209Status ProcessFreeBSD::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 m_resume_signo = 0;
211 m_suspend_tids.clear();
212 m_run_tids.clear();
213 m_step_tids.clear();
214 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000215}
216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
218 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 switch (message.GetKind()) {
221 case ProcessMessage::eInvalidMessage:
222 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 case ProcessMessage::eAttachMessage:
225 SetPrivateState(eStateStopped);
226 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 case ProcessMessage::eLimboMessage:
229 case ProcessMessage::eExitMessage:
230 SetExitStatus(message.GetExitStatus(), NULL);
231 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000232
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 case ProcessMessage::eSignalMessage:
234 case ProcessMessage::eSignalDeliveredMessage:
235 case ProcessMessage::eBreakpointMessage:
236 case ProcessMessage::eTraceMessage:
237 case ProcessMessage::eWatchpointMessage:
238 case ProcessMessage::eCrashMessage:
239 SetPrivateState(eStateStopped);
240 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000241
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 case ProcessMessage::eNewThreadMessage:
243 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
244 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 case ProcessMessage::eExecMessage:
247 SetPrivateState(eStateStopped);
248 break;
249 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000250
Kate Stoneb9c1b512016-09-06 20:57:50 +0000251 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000252}
Ed Mastefe5a6422015-07-28 15:45:57 +0000253
254//------------------------------------------------------------------------------
255// Constructors and destructors.
256
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
258 lldb::ListenerSP listener_sp,
259 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000260 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
262 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
263 m_resume_signo(0) {
264 // FIXME: Putting this code in the ctor and saving the byte order in a
265 // member variable is a hack to avoid const qual issues in GetByteOrder.
266 lldb::ModuleSP module = GetTarget().GetExecutableModule();
267 if (module && module->GetObjectFile())
268 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000269}
270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000272
273//------------------------------------------------------------------------------
274// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000276 Process::Finalize();
277
278 if (m_monitor)
279 m_monitor->StopMonitor();
280}
281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
283 bool plugin_specified_by_name) {
284 // For now we are just making sure the file exists for a given module
285 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
286 if (exe_module_sp.get())
Jonas Devlieghere49996c12018-11-01 17:46:31 +0000287 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288 // If there is no executable module, we return true since we might be
289 // preparing to attach.
290 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000291}
292
Zachary Turner97206d52017-05-12 04:51:55 +0000293Status
294ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
295 const ProcessAttachInfo &attach_info) {
296 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000300 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000301
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000305 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306
307 PlatformSP platform_sp(GetTarget().GetPlatform());
308 assert(platform_sp.get());
309 if (!platform_sp)
310 return error; // FIXME: Detatch?
311
312 // Find out what we can about this process
313 ProcessInstanceInfo process_info;
314 platform_sp->GetProcessInfo(pid, process_info);
315
316 // Resolve the executable module
317 ModuleSP exe_module_sp;
318 FileSpecList executable_search_paths(
319 Target::GetDefaultExecutableSearchPaths());
320 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
321 GetTarget().GetArchitecture());
322 error = platform_sp->ResolveExecutable(
323 exe_module_spec, exe_module_sp,
324 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
325 if (!error.Success())
326 return error;
327
328 // Fix the target architecture if necessary
329 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
330 if (module_arch.IsValid() &&
331 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
332 GetTarget().SetArchitecture(module_arch);
333
334 // Initialize the target module list
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000335 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336
337 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
338
339 SetID(pid);
340
341 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000342}
343
Zachary Turner97206d52017-05-12 04:51:55 +0000344Status ProcessFreeBSD::WillLaunch(Module *module) {
345 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000347}
348
349FileSpec
350ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 const FileSpec &default_file_spec,
352 const FileSpec &dbg_pts_file_spec) {
353 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
356 file_spec = file_action->GetFileSpec();
Adrian Prantl05097242018-04-30 16:49:04 +0000357 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
358 // If so, convert to using a different default path instead to redirect I/O
359 // to the debugger console. This should also handle user overrides to
360 // /dev/null or a different file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 if (!file_spec || file_spec == dbg_pts_file_spec)
362 file_spec = default_file_spec;
363 }
364 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000365}
366
Zachary Turner97206d52017-05-12 04:51:55 +0000367Status ProcessFreeBSD::DoLaunch(Module *module,
368 ProcessLaunchInfo &launch_info) {
369 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000371
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 FileSpec working_dir = launch_info.GetWorkingDirectory();
David Carlier511e1cf2018-11-04 23:19:25 +0000373 if (working_dir) {
374 FileSystem::Instance().Resolve(working_dir);
Jonas Devlieghere3a58d892018-11-08 00:14:50 +0000375 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) {
David Carlier511e1cf2018-11-04 23:19:25 +0000376 error.SetErrorStringWithFormat("No such file or directory: %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 working_dir.GetCString());
David Carlier511e1cf2018-11-04 23:19:25 +0000378 return error;
379 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 }
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
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000391 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)};
Ed Mastefe5a6422015-07-28 15:45:57 +0000392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
394 stdin_file_spec =
395 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
398 stdout_file_spec =
399 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
402 stderr_file_spec =
403 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 m_monitor = new ProcessMonitor(
406 this, module, launch_info.GetArguments().GetConstArgumentVector(),
Pavel Labath75c6de02018-01-10 13:53:40 +0000407 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
Pavel Labath3ff377a2018-01-10 12:25:48 +0000408 stderr_file_spec, working_dir, launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 if (!error.Success())
413 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 int terminal = m_monitor->GetTerminalFD();
416 if (terminal >= 0) {
417// The reader thread will close the file descriptor when done, so we pass it a
418// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000419#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
421 if (stdio == -1) {
422 error.SetErrorToErrno();
423 return error;
424 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000425#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
427 int stdio = fcntl(terminal, F_DUPFD, 0);
428 if (stdio == -1) {
429 error.SetErrorToErrno();
430 return error;
431 }
432 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
433 if (stdio == -1) {
434 error.SetErrorToErrno();
435 return error;
436 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000437#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000438 SetSTDIOFileDescriptor(stdio);
439 }
440
441 SetID(m_monitor->GetPID());
442 return error;
443}
444
445void ProcessFreeBSD::DidLaunch() {}
446
447addr_t ProcessFreeBSD::GetImageInfoAddress() {
448 Target *target = &GetTarget();
449 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
450 Address addr = obj_file->GetImageInfoAddress(target);
451
452 if (addr.IsValid())
453 return addr.GetLoadAddress(target);
454 return LLDB_INVALID_ADDRESS;
455}
456
Zachary Turner97206d52017-05-12 04:51:55 +0000457Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
458 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459
460 if (IsStopped()) {
461 caused_stop = false;
462 } else if (kill(GetID(), SIGSTOP)) {
463 caused_stop = false;
464 error.SetErrorToErrno();
465 } else {
466 caused_stop = true;
467 }
468 return error;
469}
470
Zachary Turner97206d52017-05-12 04:51:55 +0000471Status ProcessFreeBSD::DoSignal(int signal) {
472 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473
474 if (kill(GetID(), signal))
475 error.SetErrorToErrno();
476
477 return error;
478}
479
Zachary Turner97206d52017-05-12 04:51:55 +0000480Status ProcessFreeBSD::DoDestroy() {
481 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482
483 if (!HasExited()) {
484 assert(m_monitor);
485 m_exit_now = true;
486 if (GetID() == LLDB_INVALID_PROCESS_ID) {
487 error.SetErrorString("invalid process id");
488 return error;
489 }
490 if (!m_monitor->Kill()) {
491 error.SetErrorToErrno();
492 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000493 }
494
Kate Stoneb9c1b512016-09-06 20:57:50 +0000495 SetPrivateState(eStateExited);
496 }
497
498 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000499}
500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501void ProcessFreeBSD::DoDidExec() {
502 Target *target = &GetTarget();
503 if (target) {
504 PlatformSP platform_sp(target->GetPlatform());
505 assert(platform_sp.get());
506 if (platform_sp) {
507 ProcessInstanceInfo process_info;
508 platform_sp->GetProcessInfo(GetID(), process_info);
509 ModuleSP exe_module_sp;
510 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
511 target->GetArchitecture());
512 FileSpecList executable_search_paths(
513 Target::GetDefaultExecutableSearchPaths());
Zachary Turner97206d52017-05-12 04:51:55 +0000514 Status error = platform_sp->ResolveExecutable(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 exe_module_spec, exe_module_sp,
516 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
517 if (!error.Success())
518 return;
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000519 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Ed Mastefe5a6422015-07-28 15:45:57 +0000520 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000522}
523
Kate Stoneb9c1b512016-09-06 20:57:50 +0000524bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
525 bool added_to_set = false;
526 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
527 if (it == m_seen_initial_stop.end()) {
528 m_seen_initial_stop.insert(stop_tid);
529 added_to_set = true;
530 }
531 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000532}
533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
535 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000536}
537
538FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
540 lldb::tid_t tid) {
541 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000542}
543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544void ProcessFreeBSD::RefreshStateAfterStop() {
545 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000546 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000549
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 // This method used to only handle one message. Changing it to loop allows
551 // it to handle the case where we hit a breakpoint while handling a different
552 // breakpoint.
553 while (!m_message_queue.empty()) {
554 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 // Resolve the thread this message corresponds to and pass it along.
557 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000558 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
559 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
564 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000565 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 thread->Notify(message);
567
568 if (message.GetKind() == ProcessMessage::eExitMessage) {
569 // FIXME: We should tell the user about this, but the limbo message is
570 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000571 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000572 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
573
574 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
575 thread_sp.reset();
576 m_seen_initial_stop.erase(tid);
577 }
578
579 m_message_queue.pop();
580 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000581}
582
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583bool ProcessFreeBSD::IsAlive() {
584 StateType state = GetPrivateState();
585 return state != eStateDetached && state != eStateExited &&
586 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000587}
588
Kate Stoneb9c1b512016-09-06 20:57:50 +0000589size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000590 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 assert(m_monitor);
592 return m_monitor->ReadMemory(vm_addr, buf, size, error);
593}
594
595size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +0000596 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000597 assert(m_monitor);
598 return m_monitor->WriteMemory(vm_addr, buf, size, error);
599}
600
601addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000602 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000603 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
604
605 unsigned prot = 0;
606 if (permissions & lldb::ePermissionsReadable)
607 prot |= eMmapProtRead;
608 if (permissions & lldb::ePermissionsWritable)
609 prot |= eMmapProtWrite;
610 if (permissions & lldb::ePermissionsExecutable)
611 prot |= eMmapProtExec;
612
613 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
614 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
615 m_addr_to_mmap_size[allocated_addr] = size;
616 error.Clear();
617 } else {
618 allocated_addr = LLDB_INVALID_ADDRESS;
619 error.SetErrorStringWithFormat(
620 "unable to allocate %zu bytes of memory with permissions %s", size,
621 GetPermissionsAsCString(permissions));
622 }
623
624 return allocated_addr;
625}
626
Zachary Turner97206d52017-05-12 04:51:55 +0000627Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
628 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
630 if (pos != m_addr_to_mmap_size.end() &&
631 InferiorCallMunmap(this, addr, pos->second))
632 m_addr_to_mmap_size.erase(pos);
633 else
634 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
635 addr);
636
637 return error;
638}
639
640size_t
641ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
642 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
643 static const uint8_t g_i386_opcode[] = {0xCC};
644
645 ArchSpec arch = GetTarget().GetArchitecture();
646 const uint8_t *opcode = NULL;
647 size_t opcode_size = 0;
648
649 switch (arch.GetMachine()) {
650 default:
651 assert(false && "CPU type not supported!");
652 break;
653
654 case llvm::Triple::arm: {
Adrian Prantl05097242018-04-30 16:49:04 +0000655 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
656 // linux kernel does otherwise.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
658 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
659
660 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000661 AddressClass addr_class = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662
663 if (bp_loc_sp)
664 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
665
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000666 if (addr_class == AddressClass::eCodeAlternateISA ||
667 (addr_class == AddressClass::eUnknown &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000668 bp_loc_sp->GetAddress().GetOffset() & 1)) {
669 opcode = g_thumb_breakpoint_opcode;
670 opcode_size = sizeof(g_thumb_breakpoint_opcode);
671 } else {
672 opcode = g_arm_breakpoint_opcode;
673 opcode_size = sizeof(g_arm_breakpoint_opcode);
674 }
675 } break;
676 case llvm::Triple::aarch64:
677 opcode = g_aarch64_opcode;
678 opcode_size = sizeof(g_aarch64_opcode);
679 break;
680
681 case llvm::Triple::x86:
682 case llvm::Triple::x86_64:
683 opcode = g_i386_opcode;
684 opcode_size = sizeof(g_i386_opcode);
685 break;
686 }
687
688 bp_site->SetTrapOpcode(opcode, opcode_size);
689 return opcode_size;
690}
691
Zachary Turner97206d52017-05-12 04:51:55 +0000692Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 return EnableSoftwareBreakpoint(bp_site);
694}
695
Zachary Turner97206d52017-05-12 04:51:55 +0000696Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 return DisableSoftwareBreakpoint(bp_site);
698}
699
Zachary Turner97206d52017-05-12 04:51:55 +0000700Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
701 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 if (wp) {
703 user_id_t watchID = wp->GetID();
704 addr_t addr = wp->GetLoadAddress();
705 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
706 if (log)
707 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
708 watchID);
709 if (wp->IsEnabled()) {
710 if (log)
711 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
712 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
713 watchID, (uint64_t)addr);
714 return error;
715 }
716
717 // Try to find a vacant watchpoint slot in the inferiors' main thread
718 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000719 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
721 m_thread_list.GetThreadAtIndex(0, false).get());
722
723 if (thread)
724 wp_hw_index = thread->FindVacantWatchpointIndex();
725
726 if (wp_hw_index == LLDB_INVALID_INDEX32) {
727 error.SetErrorString("Setting hardware watchpoint failed.");
728 } else {
729 wp->SetHardwareIndex(wp_hw_index);
730 bool wp_enabled = true;
731 uint32_t thread_count = m_thread_list.GetSize(false);
732 for (uint32_t i = 0; i < thread_count; ++i) {
733 thread = static_cast<FreeBSDThread *>(
734 m_thread_list.GetThreadAtIndex(i, false).get());
735 if (thread)
736 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
737 else
738 wp_enabled = false;
739 }
740 if (wp_enabled) {
741 wp->SetEnabled(true, notify);
742 return error;
743 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000744 // Watchpoint enabling failed on at least one of the threads so roll
745 // back all of them
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 DisableWatchpoint(wp, false);
747 error.SetErrorString("Setting hardware watchpoint failed");
748 }
749 }
750 } else
751 error.SetErrorString("Watchpoint argument was NULL.");
752 return error;
753}
754
Zachary Turner97206d52017-05-12 04:51:55 +0000755Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
756 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 if (wp) {
758 user_id_t watchID = wp->GetID();
759 addr_t addr = wp->GetLoadAddress();
760 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
761 if (log)
762 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
763 watchID);
764 if (!wp->IsEnabled()) {
765 if (log)
766 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
767 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
768 watchID, (uint64_t)addr);
769 // This is needed (for now) to keep watchpoints disabled correctly
770 wp->SetEnabled(false, notify);
771 return error;
772 }
773
774 if (wp->IsHardware()) {
775 bool wp_disabled = true;
776 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
777 uint32_t thread_count = m_thread_list.GetSize(false);
778 for (uint32_t i = 0; i < thread_count; ++i) {
779 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
780 m_thread_list.GetThreadAtIndex(i, false).get());
781 if (thread)
782 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
783 else
784 wp_disabled = false;
785 }
786 if (wp_disabled) {
787 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
788 wp->SetEnabled(false, notify);
789 return error;
790 } else
791 error.SetErrorString("Disabling hardware watchpoint failed");
792 }
793 } else
794 error.SetErrorString("Watchpoint argument was NULL.");
795 return error;
796}
797
Zachary Turner97206d52017-05-12 04:51:55 +0000798Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
799 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
801 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
802 m_thread_list.GetThreadAtIndex(0, false).get());
803 if (thread)
804 num = thread->NumSupportedHardwareWatchpoints();
805 else
806 error.SetErrorString("Process does not exist.");
807 return error;
808}
809
Zachary Turner97206d52017-05-12 04:51:55 +0000810Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
811 Status error = GetWatchpointSupportInfo(num);
Adrian Prantl05097242018-04-30 16:49:04 +0000812 // Watchpoints trigger and halt the inferior after the corresponding
813 // instruction has been executed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 after = true;
815 return error;
816}
817
818uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
819 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
820 // Do not allow recursive updates.
821 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000822}
823
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824ByteOrder ProcessFreeBSD::GetByteOrder() const {
825 // FIXME: We should be able to extract this value directly. See comment in
826 // ProcessFreeBSD().
827 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000828}
829
Zachary Turner97206d52017-05-12 04:51:55 +0000830size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 ssize_t status;
832 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
833 error.SetErrorToErrno();
834 return 0;
835 }
836 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000837}
838
839//------------------------------------------------------------------------------
840// Utility functions.
841
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842bool ProcessFreeBSD::HasExited() {
843 switch (GetPrivateState()) {
844 default:
845 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000846
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 case eStateDetached:
848 case eStateExited:
849 return true;
850 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000851
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000853}
854
Kate Stoneb9c1b512016-09-06 20:57:50 +0000855bool ProcessFreeBSD::IsStopped() {
856 switch (GetPrivateState()) {
857 default:
858 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 case eStateStopped:
861 case eStateCrashed:
862 case eStateSuspended:
863 return true;
864 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000867}
868
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869bool ProcessFreeBSD::IsAThreadRunning() {
870 bool is_running = false;
871 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
872 uint32_t thread_count = m_thread_list.GetSize(false);
873 for (uint32_t i = 0; i < thread_count; ++i) {
874 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
875 m_thread_list.GetThreadAtIndex(i, false).get());
876 StateType thread_state = thread->GetState();
877 if (thread_state == eStateRunning || thread_state == eStateStepping) {
878 is_running = true;
879 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000880 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 }
882 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000883}
884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885const DataBufferSP ProcessFreeBSD::GetAuxvData() {
886 // If we're the local platform, we can ask the host for auxv data.
887 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000888 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000889
Pavel Labath5b116232017-03-17 11:33:57 +0000890 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000891 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
892 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
893
Pavel Labath5b116232017-03-17 11:33:57 +0000894 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000895 perror("sysctl failed on auxv");
896 buf_sp.reset();
897 }
898
899 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000900}
Ed Maste31f01802017-01-24 14:34:49 +0000901
902struct EmulatorBaton {
903 ProcessFreeBSD *m_process;
904 RegisterContext *m_reg_context;
905
906 // eRegisterKindDWARF -> RegisterValue
907 std::unordered_map<uint32_t, RegisterValue> m_register_values;
908
909 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
910 : m_process(process), m_reg_context(reg_context) {}
911};
912
913static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
914 const EmulateInstruction::Context &context,
915 lldb::addr_t addr, void *dst, size_t length) {
916 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
917
Zachary Turner97206d52017-05-12 04:51:55 +0000918 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000919 size_t bytes_read =
920 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
921 if (!error.Success())
922 bytes_read = 0;
923 return bytes_read;
924}
925
926static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
927 const RegisterInfo *reg_info,
928 RegisterValue &reg_value) {
929 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
930
931 auto it = emulator_baton->m_register_values.find(
932 reg_info->kinds[eRegisterKindDWARF]);
933 if (it != emulator_baton->m_register_values.end()) {
934 reg_value = it->second;
935 return true;
936 }
937
938 // The emulator only fills in the dwarf register numbers (and in some cases
939 // the generic register numbers). Get the full register info from the
940 // register context based on the dwarf register numbers.
941 const RegisterInfo *full_reg_info =
942 emulator_baton->m_reg_context->GetRegisterInfo(
943 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
944
945 bool error =
946 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
947 return error;
948}
949
950static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
951 const EmulateInstruction::Context &context,
952 const RegisterInfo *reg_info,
953 const RegisterValue &reg_value) {
954 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
955 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
956 reg_value;
957 return true;
958}
959
960static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
961 const EmulateInstruction::Context &context,
962 lldb::addr_t addr, const void *dst,
963 size_t length) {
964 return length;
965}
966
967bool ProcessFreeBSD::SingleStepBreakpointHit(
968 void *baton, lldb_private::StoppointCallbackContext *context,
969 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
970 return false;
971}
972
Zachary Turner97206d52017-05-12 04:51:55 +0000973Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
974 lldb::addr_t addr) {
975 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000976
977 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
978 if (log) {
979 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
980 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
981 }
982
983 // Validate the address.
984 if (addr == LLDB_INVALID_ADDRESS)
Zachary Turner97206d52017-05-12 04:51:55 +0000985 return Status("ProcessFreeBSD::%s invalid load address specified.",
986 __FUNCTION__);
Ed Maste31f01802017-01-24 14:34:49 +0000987
988 Breakpoint *const sw_step_break =
989 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
990 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
991 sw_step_break->SetBreakpointKind("software-signle-step");
992
993 if (log)
994 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
995 __FUNCTION__, addr);
996
997 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
Zachary Turner97206d52017-05-12 04:51:55 +0000998 return Status();
Ed Maste31f01802017-01-24 14:34:49 +0000999}
1000
1001bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1002 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1003 if (!thread)
1004 return false;
1005
1006 assert(thread->GetRegisterContext());
1007 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1008
1009 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1010 if (iter == m_threads_stepping_with_breakpoint.end())
1011 return false;
1012
1013 lldb::break_id_t bp_id = iter->second;
1014 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1015 if (!bp)
1016 return false;
1017
1018 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1019 if (!bp_loc)
1020 return false;
1021
1022 GetTarget().RemoveBreakpointByID(bp_id);
1023 m_threads_stepping_with_breakpoint.erase(tid);
1024 return true;
1025}
1026
1027bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1028 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1029 if (arch.GetMachine() == llvm::Triple::arm ||
1030 arch.GetMachine() == llvm::Triple::mips64 ||
1031 arch.GetMachine() == llvm::Triple::mips64el ||
1032 arch.GetMachine() == llvm::Triple::mips ||
1033 arch.GetMachine() == llvm::Triple::mipsel)
1034 return false;
1035 return true;
1036}
1037
Zachary Turner97206d52017-05-12 04:51:55 +00001038Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
Ed Maste31f01802017-01-24 14:34:49 +00001039 std::unique_ptr<EmulateInstruction> emulator_ap(
1040 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1041 eInstructionTypePCModifying, nullptr));
1042
1043 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001044 return Status("Instruction emulator not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001045
1046 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1047 m_thread_list.FindThreadByID(tid, false).get());
1048 if (thread == NULL)
Zachary Turner97206d52017-05-12 04:51:55 +00001049 return Status("Thread not found not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001050
1051 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1052
1053 EmulatorBaton baton(this, register_context_sp.get());
1054 emulator_ap->SetBaton(&baton);
1055 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1056 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1057 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1058 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1059
1060 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001061 return Status("Read instruction failed!");
Ed Maste31f01802017-01-24 14:34:49 +00001062
1063 bool emulation_result =
1064 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1065 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1066 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1067 auto pc_it =
1068 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1069
1070 lldb::addr_t next_pc;
1071 if (emulation_result) {
1072 assert(pc_it != baton.m_register_values.end() &&
1073 "Emulation was successful but PC wasn't updated");
1074 next_pc = pc_it->second.GetAsUInt64();
1075 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001076 // Emulate instruction failed and it haven't changed PC. Advance PC with
1077 // the size of the current opcode because the emulation of all
Ed Maste31f01802017-01-24 14:34:49 +00001078 // PC modifying instruction should be successful. The failure most
1079 // likely caused by a not supported instruction which don't modify PC.
1080 next_pc =
1081 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1082 } else {
1083 // The instruction emulation failed after it modified the PC. It is an
1084 // unknown error where we can't continue because the next instruction is
1085 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001086 return Status("Instruction emulation failed unexpectedly");
Ed Maste31f01802017-01-24 14:34:49 +00001087 }
1088
1089 SetSoftwareSingleStepBreakpoint(tid, next_pc);
Zachary Turner97206d52017-05-12 04:51:55 +00001090 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001091}