blob: d985a52ce4442b267c94447975b4aafe5d4034c1 [file] [log] [blame]
Kate Stoneb9c1b512016-09-06 20:57:50 +00001//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++
2//-*-===//
Johnny Chen9ed5b492012-01-05 21:48:15 +00003//
Chandler Carruth2946cd72019-01-19 08:50:56 +00004// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Johnny Chen9ed5b492012-01-05 21:48:15 +00007//
8//===----------------------------------------------------------------------===//
9
Johnny Chen9ed5b492012-01-05 21:48:15 +000010#include <errno.h>
Pavel Labathb7f0f452017-03-17 11:08:40 +000011#include <pthread.h>
12#include <pthread_np.h>
13#include <stdlib.h>
14#include <sys/sysctl.h>
15#include <sys/types.h>
16#include <sys/user.h>
Pavel Labath5b116232017-03-17 11:33:57 +000017#include <machine/elf.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000018
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000019#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000020#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000021
Johnny Chen9ed5b492012-01-05 21:48:15 +000022#include "lldb/Core/PluginManager.h"
Jonas Devlieghere60cf3f82018-11-01 17:35:31 +000023#include "lldb/Host/FileSystem.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000024#include "lldb/Host/Host.h"
25#include "lldb/Symbol/ObjectFile.h"
26#include "lldb/Target/DynamicLoader.h"
27#include "lldb/Target/Target.h"
Pavel Labathd821c992018-08-07 11:07:21 +000028#include "lldb/Utility/RegisterValue.h"
29#include "lldb/Utility/State.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000030
Ed Maste7fd845c2013-12-09 15:51:17 +000031#include "FreeBSDThread.h"
Pavel Labathf0a6d8a2017-04-11 12:26:25 +000032#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000033#include "Plugins/Process/Utility/FreeBSDSignals.h"
34#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
35#include "ProcessFreeBSD.h"
36#include "ProcessMonitor.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000037
Ed Mastefe5a6422015-07-28 15:45:57 +000038#include "lldb/Breakpoint/BreakpointLocation.h"
39#include "lldb/Breakpoint/Watchpoint.h"
40#include "lldb/Core/Module.h"
41#include "lldb/Core/ModuleSpec.h"
42#include "lldb/Core/PluginManager.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000043#include "lldb/Host/Host.h"
44#include "lldb/Symbol/ObjectFile.h"
45#include "lldb/Target/DynamicLoader.h"
46#include "lldb/Target/Platform.h"
47#include "lldb/Target/Target.h"
Pavel Labath5b116232017-03-17 11:33:57 +000048#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner5713a052017-03-22 18:40:07 +000049#include "lldb/Utility/FileSpec.h"
Pavel Labathd821c992018-08-07 11:07:21 +000050#include "lldb/Utility/State.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000051
52#include "lldb/Host/posix/Fcntl.h"
53
Zachary Turner7d86ee52017-03-08 17:56:08 +000054#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000055#include "llvm/Support/Threading.h"
56
Johnny Chen9ed5b492012-01-05 21:48:15 +000057using namespace lldb;
58using namespace lldb_private;
59
Kate Stoneb9c1b512016-09-06 20:57:50 +000060namespace {
61UnixSignalsSP &GetFreeBSDSignals() {
62 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
63 return s_freebsd_signals_sp;
64}
Todd Fiala4ceced32014-08-29 17:35:57 +000065}
66
Johnny Chen9ed5b492012-01-05 21:48:15 +000067//------------------------------------------------------------------------------
68// Static functions.
69
Greg Clayton29d19302012-02-27 18:40:48 +000070lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000071ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000072 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000073 const FileSpec *crash_file_path) {
74 lldb::ProcessSP process_sp;
75 if (crash_file_path == NULL)
76 process_sp.reset(
77 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
78 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000079}
80
Kate Stoneb9c1b512016-09-06 20:57:50 +000081void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000082 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000083
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000084 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000085 PluginManager::RegisterPlugin(GetPluginNameStatic(),
86 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000088}
89
Kate Stoneb9c1b512016-09-06 20:57:50 +000090lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
91 static ConstString g_name("freebsd");
92 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000093}
94
Kate Stoneb9c1b512016-09-06 20:57:50 +000095const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
96 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000097}
98
99//------------------------------------------------------------------------------
100// ProcessInterface protocol.
101
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
103 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000104}
105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000107
Kate Stoneb9c1b512016-09-06 20:57:50 +0000108void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000109
Zachary Turner97206d52017-05-12 04:51:55 +0000110Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
111 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 if (keep_stopped) {
113 error.SetErrorString("Detaching with keep_stopped true is not currently "
114 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000115 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 }
117
118 error = m_monitor->Detach(GetID());
119
120 if (error.Success())
121 SetPrivateState(eStateDetached);
122
123 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000124}
125
Zachary Turner97206d52017-05-12 04:51:55 +0000126Status ProcessFreeBSD::DoResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
132 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000133 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
136 t_end = m_run_tids.end();
137 t_pos != t_end; ++t_pos) {
138 m_monitor->ThreadSuspend(*t_pos, false);
139 }
140 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
141 t_end = m_step_tids.end();
142 t_pos != t_end; ++t_pos) {
143 m_monitor->ThreadSuspend(*t_pos, false);
144 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000145 if (software_single_step) {
Zachary Turner97206d52017-05-12 04:51:55 +0000146 Status error = SetupSoftwareSingleStepping(*t_pos);
Ed Maste31f01802017-01-24 14:34:49 +0000147 if (error.Fail())
148 return error;
149 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 }
151 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
152 t_end = m_suspend_tids.end();
153 t_pos != t_end; ++t_pos) {
154 m_monitor->ThreadSuspend(*t_pos, true);
155 // XXX Cannot PT_CONTINUE properly with suspended threads.
156 do_step = true;
157 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159 if (log)
160 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
161 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000162 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 m_monitor->SingleStep(GetID(), m_resume_signo);
164 else
165 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000166
Zachary Turner97206d52017-05-12 04:51:55 +0000167 return Status();
Ed Maste7fd845c2013-12-09 15:51:17 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
171 ThreadList &new_thread_list) {
172 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
173 if (log)
174 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
175 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 std::vector<lldb::pid_t> tds;
178 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
179 return false;
180 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 ThreadList old_thread_list_copy(old_thread_list);
183 for (size_t i = 0; i < tds.size(); ++i) {
184 tid_t tid = tds[i];
185 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
186 if (!thread_sp) {
187 thread_sp.reset(new FreeBSDThread(*this, tid));
188 if (log)
189 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
190 } else {
191 if (log)
192 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
193 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000194 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195 new_thread_list.AddThread(thread_sp);
196 }
197 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
198 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
199 if (old_thread_sp) {
200 if (log)
201 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000202 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000206}
Ed Maste7fd845c2013-12-09 15:51:17 +0000207
Zachary Turner97206d52017-05-12 04:51:55 +0000208Status ProcessFreeBSD::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 m_resume_signo = 0;
210 m_suspend_tids.clear();
211 m_run_tids.clear();
212 m_step_tids.clear();
213 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
217 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 switch (message.GetKind()) {
220 case ProcessMessage::eInvalidMessage:
221 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 case ProcessMessage::eAttachMessage:
224 SetPrivateState(eStateStopped);
225 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 case ProcessMessage::eLimboMessage:
228 case ProcessMessage::eExitMessage:
229 SetExitStatus(message.GetExitStatus(), NULL);
230 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 case ProcessMessage::eSignalMessage:
233 case ProcessMessage::eSignalDeliveredMessage:
234 case ProcessMessage::eBreakpointMessage:
235 case ProcessMessage::eTraceMessage:
236 case ProcessMessage::eWatchpointMessage:
237 case ProcessMessage::eCrashMessage:
238 SetPrivateState(eStateStopped);
239 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000240
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241 case ProcessMessage::eNewThreadMessage:
242 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
243 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 case ProcessMessage::eExecMessage:
246 SetPrivateState(eStateStopped);
247 break;
248 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000251}
Ed Mastefe5a6422015-07-28 15:45:57 +0000252
253//------------------------------------------------------------------------------
254// Constructors and destructors.
255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
257 lldb::ListenerSP listener_sp,
258 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000259 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
261 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
262 m_resume_signo(0) {
263 // FIXME: Putting this code in the ctor and saving the byte order in a
264 // member variable is a hack to avoid const qual issues in GetByteOrder.
265 lldb::ModuleSP module = GetTarget().GetExecutableModule();
266 if (module && module->GetObjectFile())
267 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000268}
269
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000271
272//------------------------------------------------------------------------------
273// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000275 Process::Finalize();
276
277 if (m_monitor)
278 m_monitor->StopMonitor();
279}
280
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
282 bool plugin_specified_by_name) {
283 // For now we are just making sure the file exists for a given module
284 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
285 if (exe_module_sp.get())
Jonas Devlieghere49996c12018-11-01 17:46:31 +0000286 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000287 // If there is no executable module, we return true since we might be
288 // preparing to attach.
289 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000290}
291
Zachary Turner97206d52017-05-12 04:51:55 +0000292Status
293ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
294 const ProcessAttachInfo &attach_info) {
295 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000299 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000300
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000304 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305
306 PlatformSP platform_sp(GetTarget().GetPlatform());
307 assert(platform_sp.get());
308 if (!platform_sp)
309 return error; // FIXME: Detatch?
310
311 // Find out what we can about this process
312 ProcessInstanceInfo process_info;
313 platform_sp->GetProcessInfo(pid, process_info);
314
315 // Resolve the executable module
316 ModuleSP exe_module_sp;
317 FileSpecList executable_search_paths(
318 Target::GetDefaultExecutableSearchPaths());
319 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
320 GetTarget().GetArchitecture());
321 error = platform_sp->ResolveExecutable(
322 exe_module_spec, exe_module_sp,
323 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
324 if (!error.Success())
325 return error;
326
327 // Fix the target architecture if necessary
328 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
329 if (module_arch.IsValid() &&
330 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
331 GetTarget().SetArchitecture(module_arch);
332
333 // Initialize the target module list
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000334 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335
336 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
337
338 SetID(pid);
339
340 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000341}
342
Zachary Turner97206d52017-05-12 04:51:55 +0000343Status ProcessFreeBSD::WillLaunch(Module *module) {
344 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000346}
347
348FileSpec
349ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 const FileSpec &default_file_spec,
351 const FileSpec &dbg_pts_file_spec) {
352 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000353
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
355 file_spec = file_action->GetFileSpec();
Adrian Prantl05097242018-04-30 16:49:04 +0000356 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
357 // If so, convert to using a different default path instead to redirect I/O
358 // to the debugger console. This should also handle user overrides to
359 // /dev/null or a different file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 if (!file_spec || file_spec == dbg_pts_file_spec)
361 file_spec = default_file_spec;
362 }
363 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000364}
365
Zachary Turner97206d52017-05-12 04:51:55 +0000366Status ProcessFreeBSD::DoLaunch(Module *module,
367 ProcessLaunchInfo &launch_info) {
368 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 FileSpec working_dir = launch_info.GetWorkingDirectory();
David Carlier511e1cf2018-11-04 23:19:25 +0000372 if (working_dir) {
373 FileSystem::Instance().Resolve(working_dir);
Jonas Devlieghere3a58d892018-11-08 00:14:50 +0000374 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) {
David Carlier511e1cf2018-11-04 23:19:25 +0000375 error.SetErrorStringWithFormat("No such file or directory: %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 working_dir.GetCString());
David Carlier511e1cf2018-11-04 23:19:25 +0000377 return error;
378 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000382
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 // Default of empty will mean to use existing open file descriptors
386 FileSpec stdin_file_spec{};
387 FileSpec stdout_file_spec{};
388 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000389
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000390 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)};
Ed Mastefe5a6422015-07-28 15:45:57 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
393 stdin_file_spec =
394 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
397 stdout_file_spec =
398 GetFileSpec(file_action, stdout_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(STDERR_FILENO);
401 stderr_file_spec =
402 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 m_monitor = new ProcessMonitor(
405 this, module, launch_info.GetArguments().GetConstArgumentVector(),
Pavel Labath75c6de02018-01-10 13:53:40 +0000406 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
Pavel Labath3ff377a2018-01-10 12:25:48 +0000407 stderr_file_spec, working_dir, launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 if (!error.Success())
412 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 int terminal = m_monitor->GetTerminalFD();
415 if (terminal >= 0) {
416// The reader thread will close the file descriptor when done, so we pass it a
417// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000418#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
420 if (stdio == -1) {
421 error.SetErrorToErrno();
422 return error;
423 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000424#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
426 int stdio = fcntl(terminal, F_DUPFD, 0);
427 if (stdio == -1) {
428 error.SetErrorToErrno();
429 return error;
430 }
431 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
432 if (stdio == -1) {
433 error.SetErrorToErrno();
434 return error;
435 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000436#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 SetSTDIOFileDescriptor(stdio);
438 }
439
440 SetID(m_monitor->GetPID());
441 return error;
442}
443
444void ProcessFreeBSD::DidLaunch() {}
445
446addr_t ProcessFreeBSD::GetImageInfoAddress() {
447 Target *target = &GetTarget();
448 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
449 Address addr = obj_file->GetImageInfoAddress(target);
450
451 if (addr.IsValid())
452 return addr.GetLoadAddress(target);
453 return LLDB_INVALID_ADDRESS;
454}
455
Zachary Turner97206d52017-05-12 04:51:55 +0000456Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
457 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458
459 if (IsStopped()) {
460 caused_stop = false;
461 } else if (kill(GetID(), SIGSTOP)) {
462 caused_stop = false;
463 error.SetErrorToErrno();
464 } else {
465 caused_stop = true;
466 }
467 return error;
468}
469
Zachary Turner97206d52017-05-12 04:51:55 +0000470Status ProcessFreeBSD::DoSignal(int signal) {
471 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472
473 if (kill(GetID(), signal))
474 error.SetErrorToErrno();
475
476 return error;
477}
478
Zachary Turner97206d52017-05-12 04:51:55 +0000479Status ProcessFreeBSD::DoDestroy() {
480 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481
482 if (!HasExited()) {
483 assert(m_monitor);
484 m_exit_now = true;
485 if (GetID() == LLDB_INVALID_PROCESS_ID) {
486 error.SetErrorString("invalid process id");
487 return error;
488 }
489 if (!m_monitor->Kill()) {
490 error.SetErrorToErrno();
491 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000492 }
493
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 SetPrivateState(eStateExited);
495 }
496
497 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000498}
499
Kate Stoneb9c1b512016-09-06 20:57:50 +0000500void ProcessFreeBSD::DoDidExec() {
501 Target *target = &GetTarget();
502 if (target) {
503 PlatformSP platform_sp(target->GetPlatform());
504 assert(platform_sp.get());
505 if (platform_sp) {
506 ProcessInstanceInfo process_info;
507 platform_sp->GetProcessInfo(GetID(), process_info);
508 ModuleSP exe_module_sp;
509 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
510 target->GetArchitecture());
511 FileSpecList executable_search_paths(
512 Target::GetDefaultExecutableSearchPaths());
Zachary Turner97206d52017-05-12 04:51:55 +0000513 Status error = platform_sp->ResolveExecutable(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 exe_module_spec, exe_module_sp,
515 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
516 if (!error.Success())
517 return;
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000518 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Ed Mastefe5a6422015-07-28 15:45:57 +0000519 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000520 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000521}
522
Kate Stoneb9c1b512016-09-06 20:57:50 +0000523bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
524 bool added_to_set = false;
525 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
526 if (it == m_seen_initial_stop.end()) {
527 m_seen_initial_stop.insert(stop_tid);
528 added_to_set = true;
529 }
530 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000531}
532
Kate Stoneb9c1b512016-09-06 20:57:50 +0000533bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
534 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000535}
536
537FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
539 lldb::tid_t tid) {
540 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000541}
542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543void ProcessFreeBSD::RefreshStateAfterStop() {
544 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000545 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000548
Kate Stoneb9c1b512016-09-06 20:57:50 +0000549 // This method used to only handle one message. Changing it to loop allows
550 // it to handle the case where we hit a breakpoint while handling a different
551 // breakpoint.
552 while (!m_message_queue.empty()) {
553 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 // Resolve the thread this message corresponds to and pass it along.
556 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000557 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
558 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000561
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
563 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000564 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 thread->Notify(message);
566
567 if (message.GetKind() == ProcessMessage::eExitMessage) {
568 // FIXME: We should tell the user about this, but the limbo message is
569 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000570 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000571 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
572
573 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
574 thread_sp.reset();
575 m_seen_initial_stop.erase(tid);
576 }
577
578 m_message_queue.pop();
579 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000580}
581
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582bool ProcessFreeBSD::IsAlive() {
583 StateType state = GetPrivateState();
584 return state != eStateDetached && state != eStateExited &&
585 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000586}
587
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000589 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000590 assert(m_monitor);
591 return m_monitor->ReadMemory(vm_addr, buf, size, error);
592}
593
594size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +0000595 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000596 assert(m_monitor);
597 return m_monitor->WriteMemory(vm_addr, buf, size, error);
598}
599
600addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000601 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000602 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
603
604 unsigned prot = 0;
605 if (permissions & lldb::ePermissionsReadable)
606 prot |= eMmapProtRead;
607 if (permissions & lldb::ePermissionsWritable)
608 prot |= eMmapProtWrite;
609 if (permissions & lldb::ePermissionsExecutable)
610 prot |= eMmapProtExec;
611
612 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
613 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
614 m_addr_to_mmap_size[allocated_addr] = size;
615 error.Clear();
616 } else {
617 allocated_addr = LLDB_INVALID_ADDRESS;
618 error.SetErrorStringWithFormat(
619 "unable to allocate %zu bytes of memory with permissions %s", size,
620 GetPermissionsAsCString(permissions));
621 }
622
623 return allocated_addr;
624}
625
Zachary Turner97206d52017-05-12 04:51:55 +0000626Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
627 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
629 if (pos != m_addr_to_mmap_size.end() &&
630 InferiorCallMunmap(this, addr, pos->second))
631 m_addr_to_mmap_size.erase(pos);
632 else
633 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
634 addr);
635
636 return error;
637}
638
639size_t
640ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
641 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
642 static const uint8_t g_i386_opcode[] = {0xCC};
643
644 ArchSpec arch = GetTarget().GetArchitecture();
645 const uint8_t *opcode = NULL;
646 size_t opcode_size = 0;
647
648 switch (arch.GetMachine()) {
649 default:
650 assert(false && "CPU type not supported!");
651 break;
652
653 case llvm::Triple::arm: {
Adrian Prantl05097242018-04-30 16:49:04 +0000654 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
655 // linux kernel does otherwise.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
657 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
658
659 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000660 AddressClass addr_class = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661
662 if (bp_loc_sp)
663 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
664
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000665 if (addr_class == AddressClass::eCodeAlternateISA ||
666 (addr_class == AddressClass::eUnknown &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 bp_loc_sp->GetAddress().GetOffset() & 1)) {
668 opcode = g_thumb_breakpoint_opcode;
669 opcode_size = sizeof(g_thumb_breakpoint_opcode);
670 } else {
671 opcode = g_arm_breakpoint_opcode;
672 opcode_size = sizeof(g_arm_breakpoint_opcode);
673 }
674 } break;
675 case llvm::Triple::aarch64:
676 opcode = g_aarch64_opcode;
677 opcode_size = sizeof(g_aarch64_opcode);
678 break;
679
680 case llvm::Triple::x86:
681 case llvm::Triple::x86_64:
682 opcode = g_i386_opcode;
683 opcode_size = sizeof(g_i386_opcode);
684 break;
685 }
686
687 bp_site->SetTrapOpcode(opcode, opcode_size);
688 return opcode_size;
689}
690
Zachary Turner97206d52017-05-12 04:51:55 +0000691Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 return EnableSoftwareBreakpoint(bp_site);
693}
694
Zachary Turner97206d52017-05-12 04:51:55 +0000695Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 return DisableSoftwareBreakpoint(bp_site);
697}
698
Zachary Turner97206d52017-05-12 04:51:55 +0000699Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
700 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 if (wp) {
702 user_id_t watchID = wp->GetID();
703 addr_t addr = wp->GetLoadAddress();
704 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
705 if (log)
706 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
707 watchID);
708 if (wp->IsEnabled()) {
709 if (log)
710 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
711 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
712 watchID, (uint64_t)addr);
713 return error;
714 }
715
716 // Try to find a vacant watchpoint slot in the inferiors' main thread
717 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000718 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
720 m_thread_list.GetThreadAtIndex(0, false).get());
721
722 if (thread)
723 wp_hw_index = thread->FindVacantWatchpointIndex();
724
725 if (wp_hw_index == LLDB_INVALID_INDEX32) {
726 error.SetErrorString("Setting hardware watchpoint failed.");
727 } else {
728 wp->SetHardwareIndex(wp_hw_index);
729 bool wp_enabled = true;
730 uint32_t thread_count = m_thread_list.GetSize(false);
731 for (uint32_t i = 0; i < thread_count; ++i) {
732 thread = static_cast<FreeBSDThread *>(
733 m_thread_list.GetThreadAtIndex(i, false).get());
734 if (thread)
735 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
736 else
737 wp_enabled = false;
738 }
739 if (wp_enabled) {
740 wp->SetEnabled(true, notify);
741 return error;
742 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000743 // Watchpoint enabling failed on at least one of the threads so roll
744 // back all of them
Kate Stoneb9c1b512016-09-06 20:57:50 +0000745 DisableWatchpoint(wp, false);
746 error.SetErrorString("Setting hardware watchpoint failed");
747 }
748 }
749 } else
750 error.SetErrorString("Watchpoint argument was NULL.");
751 return error;
752}
753
Zachary Turner97206d52017-05-12 04:51:55 +0000754Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
755 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (wp) {
757 user_id_t watchID = wp->GetID();
758 addr_t addr = wp->GetLoadAddress();
759 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
760 if (log)
761 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
762 watchID);
763 if (!wp->IsEnabled()) {
764 if (log)
765 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
766 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
767 watchID, (uint64_t)addr);
768 // This is needed (for now) to keep watchpoints disabled correctly
769 wp->SetEnabled(false, notify);
770 return error;
771 }
772
773 if (wp->IsHardware()) {
774 bool wp_disabled = true;
775 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
776 uint32_t thread_count = m_thread_list.GetSize(false);
777 for (uint32_t i = 0; i < thread_count; ++i) {
778 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
779 m_thread_list.GetThreadAtIndex(i, false).get());
780 if (thread)
781 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
782 else
783 wp_disabled = false;
784 }
785 if (wp_disabled) {
786 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
787 wp->SetEnabled(false, notify);
788 return error;
789 } else
790 error.SetErrorString("Disabling hardware watchpoint failed");
791 }
792 } else
793 error.SetErrorString("Watchpoint argument was NULL.");
794 return error;
795}
796
Zachary Turner97206d52017-05-12 04:51:55 +0000797Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
798 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
800 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
801 m_thread_list.GetThreadAtIndex(0, false).get());
802 if (thread)
803 num = thread->NumSupportedHardwareWatchpoints();
804 else
805 error.SetErrorString("Process does not exist.");
806 return error;
807}
808
Zachary Turner97206d52017-05-12 04:51:55 +0000809Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
810 Status error = GetWatchpointSupportInfo(num);
Adrian Prantl05097242018-04-30 16:49:04 +0000811 // Watchpoints trigger and halt the inferior after the corresponding
812 // instruction has been executed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 after = true;
814 return error;
815}
816
817uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
818 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
819 // Do not allow recursive updates.
820 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000821}
822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823ByteOrder ProcessFreeBSD::GetByteOrder() const {
824 // FIXME: We should be able to extract this value directly. See comment in
825 // ProcessFreeBSD().
826 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000827}
828
Zachary Turner97206d52017-05-12 04:51:55 +0000829size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 ssize_t status;
831 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
832 error.SetErrorToErrno();
833 return 0;
834 }
835 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000836}
837
838//------------------------------------------------------------------------------
839// Utility functions.
840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841bool ProcessFreeBSD::HasExited() {
842 switch (GetPrivateState()) {
843 default:
844 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 case eStateDetached:
847 case eStateExited:
848 return true;
849 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000852}
853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854bool ProcessFreeBSD::IsStopped() {
855 switch (GetPrivateState()) {
856 default:
857 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000858
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 case eStateStopped:
860 case eStateCrashed:
861 case eStateSuspended:
862 return true;
863 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000864
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000866}
867
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868bool ProcessFreeBSD::IsAThreadRunning() {
869 bool is_running = false;
870 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
871 uint32_t thread_count = m_thread_list.GetSize(false);
872 for (uint32_t i = 0; i < thread_count; ++i) {
873 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
874 m_thread_list.GetThreadAtIndex(i, false).get());
875 StateType thread_state = thread->GetState();
876 if (thread_state == eStateRunning || thread_state == eStateStepping) {
877 is_running = true;
878 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000879 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000880 }
881 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000882}
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884const DataBufferSP ProcessFreeBSD::GetAuxvData() {
885 // If we're the local platform, we can ask the host for auxv data.
886 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000887 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000888
Pavel Labath5b116232017-03-17 11:33:57 +0000889 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000890 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
891 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
892
Pavel Labath5b116232017-03-17 11:33:57 +0000893 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000894 perror("sysctl failed on auxv");
895 buf_sp.reset();
896 }
897
898 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000899}
Ed Maste31f01802017-01-24 14:34:49 +0000900
901struct EmulatorBaton {
902 ProcessFreeBSD *m_process;
903 RegisterContext *m_reg_context;
904
905 // eRegisterKindDWARF -> RegisterValue
906 std::unordered_map<uint32_t, RegisterValue> m_register_values;
907
908 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
909 : m_process(process), m_reg_context(reg_context) {}
910};
911
912static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
913 const EmulateInstruction::Context &context,
914 lldb::addr_t addr, void *dst, size_t length) {
915 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
916
Zachary Turner97206d52017-05-12 04:51:55 +0000917 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000918 size_t bytes_read =
919 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
920 if (!error.Success())
921 bytes_read = 0;
922 return bytes_read;
923}
924
925static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
926 const RegisterInfo *reg_info,
927 RegisterValue &reg_value) {
928 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
929
930 auto it = emulator_baton->m_register_values.find(
931 reg_info->kinds[eRegisterKindDWARF]);
932 if (it != emulator_baton->m_register_values.end()) {
933 reg_value = it->second;
934 return true;
935 }
936
937 // The emulator only fills in the dwarf register numbers (and in some cases
938 // the generic register numbers). Get the full register info from the
939 // register context based on the dwarf register numbers.
940 const RegisterInfo *full_reg_info =
941 emulator_baton->m_reg_context->GetRegisterInfo(
942 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
943
944 bool error =
945 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
946 return error;
947}
948
949static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
950 const EmulateInstruction::Context &context,
951 const RegisterInfo *reg_info,
952 const RegisterValue &reg_value) {
953 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
954 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
955 reg_value;
956 return true;
957}
958
959static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
960 const EmulateInstruction::Context &context,
961 lldb::addr_t addr, const void *dst,
962 size_t length) {
963 return length;
964}
965
966bool ProcessFreeBSD::SingleStepBreakpointHit(
967 void *baton, lldb_private::StoppointCallbackContext *context,
968 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
969 return false;
970}
971
Zachary Turner97206d52017-05-12 04:51:55 +0000972Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
973 lldb::addr_t addr) {
974 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000975
976 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
977 if (log) {
978 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
979 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
980 }
981
982 // Validate the address.
983 if (addr == LLDB_INVALID_ADDRESS)
Zachary Turner97206d52017-05-12 04:51:55 +0000984 return Status("ProcessFreeBSD::%s invalid load address specified.",
985 __FUNCTION__);
Ed Maste31f01802017-01-24 14:34:49 +0000986
987 Breakpoint *const sw_step_break =
988 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
989 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
990 sw_step_break->SetBreakpointKind("software-signle-step");
991
992 if (log)
993 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
994 __FUNCTION__, addr);
995
996 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
Zachary Turner97206d52017-05-12 04:51:55 +0000997 return Status();
Ed Maste31f01802017-01-24 14:34:49 +0000998}
999
1000bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1001 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1002 if (!thread)
1003 return false;
1004
1005 assert(thread->GetRegisterContext());
1006 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1007
1008 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1009 if (iter == m_threads_stepping_with_breakpoint.end())
1010 return false;
1011
1012 lldb::break_id_t bp_id = iter->second;
1013 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1014 if (!bp)
1015 return false;
1016
1017 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1018 if (!bp_loc)
1019 return false;
1020
1021 GetTarget().RemoveBreakpointByID(bp_id);
1022 m_threads_stepping_with_breakpoint.erase(tid);
1023 return true;
1024}
1025
1026bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1027 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1028 if (arch.GetMachine() == llvm::Triple::arm ||
1029 arch.GetMachine() == llvm::Triple::mips64 ||
1030 arch.GetMachine() == llvm::Triple::mips64el ||
1031 arch.GetMachine() == llvm::Triple::mips ||
1032 arch.GetMachine() == llvm::Triple::mipsel)
1033 return false;
1034 return true;
1035}
1036
Zachary Turner97206d52017-05-12 04:51:55 +00001037Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001038 std::unique_ptr<EmulateInstruction> emulator_up(
Ed Maste31f01802017-01-24 14:34:49 +00001039 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1040 eInstructionTypePCModifying, nullptr));
1041
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001042 if (emulator_up == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001043 return Status("Instruction emulator not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001044
1045 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1046 m_thread_list.FindThreadByID(tid, false).get());
1047 if (thread == NULL)
Zachary Turner97206d52017-05-12 04:51:55 +00001048 return Status("Thread not found not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001049
1050 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1051
1052 EmulatorBaton baton(this, register_context_sp.get());
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001053 emulator_up->SetBaton(&baton);
1054 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
1055 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
1056 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
1057 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
Ed Maste31f01802017-01-24 14:34:49 +00001058
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001059 if (!emulator_up->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001060 return Status("Read instruction failed!");
Ed Maste31f01802017-01-24 14:34:49 +00001061
1062 bool emulation_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001063 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
Ed Maste31f01802017-01-24 14:34:49 +00001064 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1065 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1066 auto pc_it =
1067 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1068
1069 lldb::addr_t next_pc;
1070 if (emulation_result) {
1071 assert(pc_it != baton.m_register_values.end() &&
1072 "Emulation was successful but PC wasn't updated");
1073 next_pc = pc_it->second.GetAsUInt64();
1074 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001075 // Emulate instruction failed and it haven't changed PC. Advance PC with
1076 // the size of the current opcode because the emulation of all
Ed Maste31f01802017-01-24 14:34:49 +00001077 // PC modifying instruction should be successful. The failure most
1078 // likely caused by a not supported instruction which don't modify PC.
1079 next_pc =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001080 register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize();
Ed Maste31f01802017-01-24 14:34:49 +00001081 } else {
1082 // The instruction emulation failed after it modified the PC. It is an
1083 // unknown error where we can't continue because the next instruction is
1084 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001085 return Status("Instruction emulation failed unexpectedly");
Ed Maste31f01802017-01-24 14:34:49 +00001086 }
1087
1088 SetSoftwareSingleStepBreakpoint(tid, next_pc);
Zachary Turner97206d52017-05-12 04:51:55 +00001089 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001090}