blob: 6f96ae66a1b884585f947ee5a6ad65afea015561 [file] [log] [blame]
Kate Stoneb9c1b512016-09-06 20:57:50 +00001//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++
2//-*-===//
Johnny Chen9ed5b492012-01-05 21:48:15 +00003//
4// The LLVM Compiler Infrastructure
5//
6// This file is distributed under the University of Illinois Open Source
7// License. See LICENSE.TXT for details.
8//
9//===----------------------------------------------------------------------===//
10
11// C Includes
12#include <errno.h>
Pavel Labathb7f0f452017-03-17 11:08:40 +000013#include <pthread.h>
14#include <pthread_np.h>
15#include <stdlib.h>
16#include <sys/sysctl.h>
17#include <sys/types.h>
18#include <sys/user.h>
Pavel Labath5b116232017-03-17 11:33:57 +000019#include <machine/elf.h>
Johnny Chen9ed5b492012-01-05 21:48:15 +000020
21// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000022#include <mutex>
Ed Maste31f01802017-01-24 14:34:49 +000023#include <unordered_map>
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000024
Johnny Chen9ed5b492012-01-05 21:48:15 +000025// Other libraries and framework includes
26#include "lldb/Core/PluginManager.h"
Jonas Devlieghere60cf3f82018-11-01 17:35:31 +000027#include "lldb/Host/FileSystem.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000028#include "lldb/Host/Host.h"
29#include "lldb/Symbol/ObjectFile.h"
30#include "lldb/Target/DynamicLoader.h"
31#include "lldb/Target/Target.h"
Pavel Labathd821c992018-08-07 11:07:21 +000032#include "lldb/Utility/RegisterValue.h"
33#include "lldb/Utility/State.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000034
Ed Maste7fd845c2013-12-09 15:51:17 +000035#include "FreeBSDThread.h"
Pavel Labathf0a6d8a2017-04-11 12:26:25 +000036#include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000037#include "Plugins/Process/Utility/FreeBSDSignals.h"
38#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
39#include "ProcessFreeBSD.h"
40#include "ProcessMonitor.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000041
Ed Mastefe5a6422015-07-28 15:45:57 +000042// Other libraries and framework includes
43#include "lldb/Breakpoint/BreakpointLocation.h"
44#include "lldb/Breakpoint/Watchpoint.h"
45#include "lldb/Core/Module.h"
46#include "lldb/Core/ModuleSpec.h"
47#include "lldb/Core/PluginManager.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000048#include "lldb/Host/Host.h"
49#include "lldb/Symbol/ObjectFile.h"
50#include "lldb/Target/DynamicLoader.h"
51#include "lldb/Target/Platform.h"
52#include "lldb/Target/Target.h"
Pavel Labath5b116232017-03-17 11:33:57 +000053#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner5713a052017-03-22 18:40:07 +000054#include "lldb/Utility/FileSpec.h"
Pavel Labathd821c992018-08-07 11:07:21 +000055#include "lldb/Utility/State.h"
Ed Mastefe5a6422015-07-28 15:45:57 +000056
57#include "lldb/Host/posix/Fcntl.h"
58
Zachary Turner7d86ee52017-03-08 17:56:08 +000059#include "llvm/Support/FileSystem.h"
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000060#include "llvm/Support/Threading.h"
61
Johnny Chen9ed5b492012-01-05 21:48:15 +000062using namespace lldb;
63using namespace lldb_private;
64
Kate Stoneb9c1b512016-09-06 20:57:50 +000065namespace {
66UnixSignalsSP &GetFreeBSDSignals() {
67 static UnixSignalsSP s_freebsd_signals_sp(new FreeBSDSignals());
68 return s_freebsd_signals_sp;
69}
Todd Fiala4ceced32014-08-29 17:35:57 +000070}
71
Johnny Chen9ed5b492012-01-05 21:48:15 +000072//------------------------------------------------------------------------------
73// Static functions.
74
Greg Clayton29d19302012-02-27 18:40:48 +000075lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000076ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000077 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000078 const FileSpec *crash_file_path) {
79 lldb::ProcessSP process_sp;
80 if (crash_file_path == NULL)
81 process_sp.reset(
82 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
83 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000084}
85
Kate Stoneb9c1b512016-09-06 20:57:50 +000086void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000087 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000088
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000089 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 PluginManager::RegisterPlugin(GetPluginNameStatic(),
91 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000093}
94
Kate Stoneb9c1b512016-09-06 20:57:50 +000095lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
96 static ConstString g_name("freebsd");
97 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000098}
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
101 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +0000102}
103
104//------------------------------------------------------------------------------
105// ProcessInterface protocol.
106
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
108 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000109}
110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000112
Kate Stoneb9c1b512016-09-06 20:57:50 +0000113void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000114
Zachary Turner97206d52017-05-12 04:51:55 +0000115Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
116 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 if (keep_stopped) {
118 error.SetErrorString("Detaching with keep_stopped true is not currently "
119 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000120 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 }
122
123 error = m_monitor->Detach(GetID());
124
125 if (error.Success())
126 SetPrivateState(eStateDetached);
127
128 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000129}
130
Zachary Turner97206d52017-05-12 04:51:55 +0000131Status ProcessFreeBSD::DoResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000133
Kate Stoneb9c1b512016-09-06 20:57:50 +0000134 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000135
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
137 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000138 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000139
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
141 t_end = m_run_tids.end();
142 t_pos != t_end; ++t_pos) {
143 m_monitor->ThreadSuspend(*t_pos, false);
144 }
145 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
146 t_end = m_step_tids.end();
147 t_pos != t_end; ++t_pos) {
148 m_monitor->ThreadSuspend(*t_pos, false);
149 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000150 if (software_single_step) {
Zachary Turner97206d52017-05-12 04:51:55 +0000151 Status error = SetupSoftwareSingleStepping(*t_pos);
Ed Maste31f01802017-01-24 14:34:49 +0000152 if (error.Fail())
153 return error;
154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 }
156 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
157 t_end = m_suspend_tids.end();
158 t_pos != t_end; ++t_pos) {
159 m_monitor->ThreadSuspend(*t_pos, true);
160 // XXX Cannot PT_CONTINUE properly with suspended threads.
161 do_step = true;
162 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 if (log)
165 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
166 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000167 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 m_monitor->SingleStep(GetID(), m_resume_signo);
169 else
170 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000171
Zachary Turner97206d52017-05-12 04:51:55 +0000172 return Status();
Ed Maste7fd845c2013-12-09 15:51:17 +0000173}
174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
176 ThreadList &new_thread_list) {
177 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
178 if (log)
179 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
180 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 std::vector<lldb::pid_t> tds;
183 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
184 return false;
185 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187 ThreadList old_thread_list_copy(old_thread_list);
188 for (size_t i = 0; i < tds.size(); ++i) {
189 tid_t tid = tds[i];
190 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
191 if (!thread_sp) {
192 thread_sp.reset(new FreeBSDThread(*this, tid));
193 if (log)
194 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
195 } else {
196 if (log)
197 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
198 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000199 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 new_thread_list.AddThread(thread_sp);
201 }
202 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
203 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
204 if (old_thread_sp) {
205 if (log)
206 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000207 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000208 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000209
Kate Stoneb9c1b512016-09-06 20:57:50 +0000210 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000211}
Ed Maste7fd845c2013-12-09 15:51:17 +0000212
Zachary Turner97206d52017-05-12 04:51:55 +0000213Status ProcessFreeBSD::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214 m_resume_signo = 0;
215 m_suspend_tids.clear();
216 m_run_tids.clear();
217 m_step_tids.clear();
218 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000219}
220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
222 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000223
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 switch (message.GetKind()) {
225 case ProcessMessage::eInvalidMessage:
226 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 case ProcessMessage::eAttachMessage:
229 SetPrivateState(eStateStopped);
230 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000231
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 case ProcessMessage::eLimboMessage:
233 case ProcessMessage::eExitMessage:
234 SetExitStatus(message.GetExitStatus(), NULL);
235 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000236
Kate Stoneb9c1b512016-09-06 20:57:50 +0000237 case ProcessMessage::eSignalMessage:
238 case ProcessMessage::eSignalDeliveredMessage:
239 case ProcessMessage::eBreakpointMessage:
240 case ProcessMessage::eTraceMessage:
241 case ProcessMessage::eWatchpointMessage:
242 case ProcessMessage::eCrashMessage:
243 SetPrivateState(eStateStopped);
244 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 case ProcessMessage::eNewThreadMessage:
247 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
248 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 case ProcessMessage::eExecMessage:
251 SetPrivateState(eStateStopped);
252 break;
253 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000254
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000256}
Ed Mastefe5a6422015-07-28 15:45:57 +0000257
258//------------------------------------------------------------------------------
259// Constructors and destructors.
260
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
262 lldb::ListenerSP listener_sp,
263 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000264 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
266 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
267 m_resume_signo(0) {
268 // FIXME: Putting this code in the ctor and saving the byte order in a
269 // member variable is a hack to avoid const qual issues in GetByteOrder.
270 lldb::ModuleSP module = GetTarget().GetExecutableModule();
271 if (module && module->GetObjectFile())
272 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000273}
274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000276
277//------------------------------------------------------------------------------
278// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000280 Process::Finalize();
281
282 if (m_monitor)
283 m_monitor->StopMonitor();
284}
285
Kate Stoneb9c1b512016-09-06 20:57:50 +0000286bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
287 bool plugin_specified_by_name) {
288 // For now we are just making sure the file exists for a given module
289 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
290 if (exe_module_sp.get())
Jonas Devlieghere60cf3f82018-11-01 17:35:31 +0000291 return FileSystem::Instance()::Exists(exe_module_sp->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 // If there is no executable module, we return true since we might be
293 // preparing to attach.
294 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000295}
296
Zachary Turner97206d52017-05-12 04:51:55 +0000297Status
298ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
299 const ProcessAttachInfo &attach_info) {
300 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000302
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000304 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000305
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000307
Kate Stoneb9c1b512016-09-06 20:57:50 +0000308 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000309 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000310
311 PlatformSP platform_sp(GetTarget().GetPlatform());
312 assert(platform_sp.get());
313 if (!platform_sp)
314 return error; // FIXME: Detatch?
315
316 // Find out what we can about this process
317 ProcessInstanceInfo process_info;
318 platform_sp->GetProcessInfo(pid, process_info);
319
320 // Resolve the executable module
321 ModuleSP exe_module_sp;
322 FileSpecList executable_search_paths(
323 Target::GetDefaultExecutableSearchPaths());
324 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
325 GetTarget().GetArchitecture());
326 error = platform_sp->ResolveExecutable(
327 exe_module_spec, exe_module_sp,
328 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
329 if (!error.Success())
330 return error;
331
332 // Fix the target architecture if necessary
333 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
334 if (module_arch.IsValid() &&
335 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
336 GetTarget().SetArchitecture(module_arch);
337
338 // Initialize the target module list
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000339 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340
341 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
342
343 SetID(pid);
344
345 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000346}
347
Zachary Turner97206d52017-05-12 04:51:55 +0000348Status ProcessFreeBSD::WillLaunch(Module *module) {
349 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000351}
352
353FileSpec
354ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 const FileSpec &default_file_spec,
356 const FileSpec &dbg_pts_file_spec) {
357 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000358
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
360 file_spec = file_action->GetFileSpec();
Adrian Prantl05097242018-04-30 16:49:04 +0000361 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
362 // If so, convert to using a different default path instead to redirect I/O
363 // to the debugger console. This should also handle user overrides to
364 // /dev/null or a different file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 if (!file_spec || file_spec == dbg_pts_file_spec)
366 file_spec = default_file_spec;
367 }
368 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000369}
370
Zachary Turner97206d52017-05-12 04:51:55 +0000371Status ProcessFreeBSD::DoLaunch(Module *module,
372 ProcessLaunchInfo &launch_info) {
373 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000375
Kate Stoneb9c1b512016-09-06 20:57:50 +0000376 FileSpec working_dir = launch_info.GetWorkingDirectory();
Zachary Turner7d86ee52017-03-08 17:56:08 +0000377 namespace fs = llvm::sys::fs;
378 if (working_dir && (!working_dir.ResolvePath() ||
379 !fs::is_directory(working_dir.GetPath()))) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 error.SetErrorStringWithFormat("No such file or directory: %s",
381 working_dir.GetCString());
382 return error;
383 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000384
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000386
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389 // Default of empty will mean to use existing open file descriptors
390 FileSpec stdin_file_spec{};
391 FileSpec stdout_file_spec{};
392 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0),
395 false};
Ed Mastefe5a6422015-07-28 15:45:57 +0000396
Kate Stoneb9c1b512016-09-06 20:57:50 +0000397 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
398 stdin_file_spec =
399 GetFileSpec(file_action, stdin_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(STDOUT_FILENO);
402 stdout_file_spec =
403 GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
406 stderr_file_spec =
407 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 m_monitor = new ProcessMonitor(
410 this, module, launch_info.GetArguments().GetConstArgumentVector(),
Pavel Labath75c6de02018-01-10 13:53:40 +0000411 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
Pavel Labath3ff377a2018-01-10 12:25:48 +0000412 stderr_file_spec, working_dir, launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 if (!error.Success())
417 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000418
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419 int terminal = m_monitor->GetTerminalFD();
420 if (terminal >= 0) {
421// The reader thread will close the file descriptor when done, so we pass it a
422// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000423#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
425 if (stdio == -1) {
426 error.SetErrorToErrno();
427 return error;
428 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000429#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
431 int stdio = fcntl(terminal, F_DUPFD, 0);
432 if (stdio == -1) {
433 error.SetErrorToErrno();
434 return error;
435 }
436 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
437 if (stdio == -1) {
438 error.SetErrorToErrno();
439 return error;
440 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000441#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 SetSTDIOFileDescriptor(stdio);
443 }
444
445 SetID(m_monitor->GetPID());
446 return error;
447}
448
449void ProcessFreeBSD::DidLaunch() {}
450
451addr_t ProcessFreeBSD::GetImageInfoAddress() {
452 Target *target = &GetTarget();
453 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
454 Address addr = obj_file->GetImageInfoAddress(target);
455
456 if (addr.IsValid())
457 return addr.GetLoadAddress(target);
458 return LLDB_INVALID_ADDRESS;
459}
460
Zachary Turner97206d52017-05-12 04:51:55 +0000461Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
462 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463
464 if (IsStopped()) {
465 caused_stop = false;
466 } else if (kill(GetID(), SIGSTOP)) {
467 caused_stop = false;
468 error.SetErrorToErrno();
469 } else {
470 caused_stop = true;
471 }
472 return error;
473}
474
Zachary Turner97206d52017-05-12 04:51:55 +0000475Status ProcessFreeBSD::DoSignal(int signal) {
476 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477
478 if (kill(GetID(), signal))
479 error.SetErrorToErrno();
480
481 return error;
482}
483
Zachary Turner97206d52017-05-12 04:51:55 +0000484Status ProcessFreeBSD::DoDestroy() {
485 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000486
487 if (!HasExited()) {
488 assert(m_monitor);
489 m_exit_now = true;
490 if (GetID() == LLDB_INVALID_PROCESS_ID) {
491 error.SetErrorString("invalid process id");
492 return error;
493 }
494 if (!m_monitor->Kill()) {
495 error.SetErrorToErrno();
496 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000497 }
498
Kate Stoneb9c1b512016-09-06 20:57:50 +0000499 SetPrivateState(eStateExited);
500 }
501
502 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000503}
504
Kate Stoneb9c1b512016-09-06 20:57:50 +0000505void ProcessFreeBSD::DoDidExec() {
506 Target *target = &GetTarget();
507 if (target) {
508 PlatformSP platform_sp(target->GetPlatform());
509 assert(platform_sp.get());
510 if (platform_sp) {
511 ProcessInstanceInfo process_info;
512 platform_sp->GetProcessInfo(GetID(), process_info);
513 ModuleSP exe_module_sp;
514 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
515 target->GetArchitecture());
516 FileSpecList executable_search_paths(
517 Target::GetDefaultExecutableSearchPaths());
Zachary Turner97206d52017-05-12 04:51:55 +0000518 Status error = platform_sp->ResolveExecutable(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 exe_module_spec, exe_module_sp,
520 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
521 if (!error.Success())
522 return;
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000523 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Ed Mastefe5a6422015-07-28 15:45:57 +0000524 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000526}
527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
529 bool added_to_set = false;
530 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
531 if (it == m_seen_initial_stop.end()) {
532 m_seen_initial_stop.insert(stop_tid);
533 added_to_set = true;
534 }
535 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000536}
537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
539 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000540}
541
542FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
544 lldb::tid_t tid) {
545 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000546}
547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548void ProcessFreeBSD::RefreshStateAfterStop() {
549 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000550 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000551
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 // This method used to only handle one message. Changing it to loop allows
555 // it to handle the case where we hit a breakpoint while handling a different
556 // breakpoint.
557 while (!m_message_queue.empty()) {
558 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 // Resolve the thread this message corresponds to and pass it along.
561 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000562 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
563 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000564
Kate Stoneb9c1b512016-09-06 20:57:50 +0000565 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000566
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
568 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000569 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000570 thread->Notify(message);
571
572 if (message.GetKind() == ProcessMessage::eExitMessage) {
573 // FIXME: We should tell the user about this, but the limbo message is
574 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000575 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
577
578 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
579 thread_sp.reset();
580 m_seen_initial_stop.erase(tid);
581 }
582
583 m_message_queue.pop();
584 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000585}
586
Kate Stoneb9c1b512016-09-06 20:57:50 +0000587bool ProcessFreeBSD::IsAlive() {
588 StateType state = GetPrivateState();
589 return state != eStateDetached && state != eStateExited &&
590 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000591}
592
Kate Stoneb9c1b512016-09-06 20:57:50 +0000593size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000594 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000595 assert(m_monitor);
596 return m_monitor->ReadMemory(vm_addr, buf, size, error);
597}
598
599size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +0000600 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601 assert(m_monitor);
602 return m_monitor->WriteMemory(vm_addr, buf, size, error);
603}
604
605addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000606 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
608
609 unsigned prot = 0;
610 if (permissions & lldb::ePermissionsReadable)
611 prot |= eMmapProtRead;
612 if (permissions & lldb::ePermissionsWritable)
613 prot |= eMmapProtWrite;
614 if (permissions & lldb::ePermissionsExecutable)
615 prot |= eMmapProtExec;
616
617 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
618 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
619 m_addr_to_mmap_size[allocated_addr] = size;
620 error.Clear();
621 } else {
622 allocated_addr = LLDB_INVALID_ADDRESS;
623 error.SetErrorStringWithFormat(
624 "unable to allocate %zu bytes of memory with permissions %s", size,
625 GetPermissionsAsCString(permissions));
626 }
627
628 return allocated_addr;
629}
630
Zachary Turner97206d52017-05-12 04:51:55 +0000631Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
632 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
634 if (pos != m_addr_to_mmap_size.end() &&
635 InferiorCallMunmap(this, addr, pos->second))
636 m_addr_to_mmap_size.erase(pos);
637 else
638 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
639 addr);
640
641 return error;
642}
643
644size_t
645ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
646 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
647 static const uint8_t g_i386_opcode[] = {0xCC};
648
649 ArchSpec arch = GetTarget().GetArchitecture();
650 const uint8_t *opcode = NULL;
651 size_t opcode_size = 0;
652
653 switch (arch.GetMachine()) {
654 default:
655 assert(false && "CPU type not supported!");
656 break;
657
658 case llvm::Triple::arm: {
Adrian Prantl05097242018-04-30 16:49:04 +0000659 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
660 // linux kernel does otherwise.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000661 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
662 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
663
664 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000665 AddressClass addr_class = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666
667 if (bp_loc_sp)
668 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
669
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000670 if (addr_class == AddressClass::eCodeAlternateISA ||
671 (addr_class == AddressClass::eUnknown &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 bp_loc_sp->GetAddress().GetOffset() & 1)) {
673 opcode = g_thumb_breakpoint_opcode;
674 opcode_size = sizeof(g_thumb_breakpoint_opcode);
675 } else {
676 opcode = g_arm_breakpoint_opcode;
677 opcode_size = sizeof(g_arm_breakpoint_opcode);
678 }
679 } break;
680 case llvm::Triple::aarch64:
681 opcode = g_aarch64_opcode;
682 opcode_size = sizeof(g_aarch64_opcode);
683 break;
684
685 case llvm::Triple::x86:
686 case llvm::Triple::x86_64:
687 opcode = g_i386_opcode;
688 opcode_size = sizeof(g_i386_opcode);
689 break;
690 }
691
692 bp_site->SetTrapOpcode(opcode, opcode_size);
693 return opcode_size;
694}
695
Zachary Turner97206d52017-05-12 04:51:55 +0000696Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 return EnableSoftwareBreakpoint(bp_site);
698}
699
Zachary Turner97206d52017-05-12 04:51:55 +0000700Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 return DisableSoftwareBreakpoint(bp_site);
702}
703
Zachary Turner97206d52017-05-12 04:51:55 +0000704Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
705 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000706 if (wp) {
707 user_id_t watchID = wp->GetID();
708 addr_t addr = wp->GetLoadAddress();
709 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
710 if (log)
711 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
712 watchID);
713 if (wp->IsEnabled()) {
714 if (log)
715 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
716 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
717 watchID, (uint64_t)addr);
718 return error;
719 }
720
721 // Try to find a vacant watchpoint slot in the inferiors' main thread
722 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000723 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
725 m_thread_list.GetThreadAtIndex(0, false).get());
726
727 if (thread)
728 wp_hw_index = thread->FindVacantWatchpointIndex();
729
730 if (wp_hw_index == LLDB_INVALID_INDEX32) {
731 error.SetErrorString("Setting hardware watchpoint failed.");
732 } else {
733 wp->SetHardwareIndex(wp_hw_index);
734 bool wp_enabled = true;
735 uint32_t thread_count = m_thread_list.GetSize(false);
736 for (uint32_t i = 0; i < thread_count; ++i) {
737 thread = static_cast<FreeBSDThread *>(
738 m_thread_list.GetThreadAtIndex(i, false).get());
739 if (thread)
740 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
741 else
742 wp_enabled = false;
743 }
744 if (wp_enabled) {
745 wp->SetEnabled(true, notify);
746 return error;
747 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000748 // Watchpoint enabling failed on at least one of the threads so roll
749 // back all of them
Kate Stoneb9c1b512016-09-06 20:57:50 +0000750 DisableWatchpoint(wp, false);
751 error.SetErrorString("Setting hardware watchpoint failed");
752 }
753 }
754 } else
755 error.SetErrorString("Watchpoint argument was NULL.");
756 return error;
757}
758
Zachary Turner97206d52017-05-12 04:51:55 +0000759Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
760 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 if (wp) {
762 user_id_t watchID = wp->GetID();
763 addr_t addr = wp->GetLoadAddress();
764 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
765 if (log)
766 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
767 watchID);
768 if (!wp->IsEnabled()) {
769 if (log)
770 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
771 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
772 watchID, (uint64_t)addr);
773 // This is needed (for now) to keep watchpoints disabled correctly
774 wp->SetEnabled(false, notify);
775 return error;
776 }
777
778 if (wp->IsHardware()) {
779 bool wp_disabled = true;
780 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
781 uint32_t thread_count = m_thread_list.GetSize(false);
782 for (uint32_t i = 0; i < thread_count; ++i) {
783 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
784 m_thread_list.GetThreadAtIndex(i, false).get());
785 if (thread)
786 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
787 else
788 wp_disabled = false;
789 }
790 if (wp_disabled) {
791 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
792 wp->SetEnabled(false, notify);
793 return error;
794 } else
795 error.SetErrorString("Disabling hardware watchpoint failed");
796 }
797 } else
798 error.SetErrorString("Watchpoint argument was NULL.");
799 return error;
800}
801
Zachary Turner97206d52017-05-12 04:51:55 +0000802Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
803 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
805 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
806 m_thread_list.GetThreadAtIndex(0, false).get());
807 if (thread)
808 num = thread->NumSupportedHardwareWatchpoints();
809 else
810 error.SetErrorString("Process does not exist.");
811 return error;
812}
813
Zachary Turner97206d52017-05-12 04:51:55 +0000814Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
815 Status error = GetWatchpointSupportInfo(num);
Adrian Prantl05097242018-04-30 16:49:04 +0000816 // Watchpoints trigger and halt the inferior after the corresponding
817 // instruction has been executed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 after = true;
819 return error;
820}
821
822uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
823 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
824 // Do not allow recursive updates.
825 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000826}
827
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828ByteOrder ProcessFreeBSD::GetByteOrder() const {
829 // FIXME: We should be able to extract this value directly. See comment in
830 // ProcessFreeBSD().
831 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000832}
833
Zachary Turner97206d52017-05-12 04:51:55 +0000834size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 ssize_t status;
836 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
837 error.SetErrorToErrno();
838 return 0;
839 }
840 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000841}
842
843//------------------------------------------------------------------------------
844// Utility functions.
845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846bool ProcessFreeBSD::HasExited() {
847 switch (GetPrivateState()) {
848 default:
849 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000850
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 case eStateDetached:
852 case eStateExited:
853 return true;
854 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000855
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000857}
858
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859bool ProcessFreeBSD::IsStopped() {
860 switch (GetPrivateState()) {
861 default:
862 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000863
Kate Stoneb9c1b512016-09-06 20:57:50 +0000864 case eStateStopped:
865 case eStateCrashed:
866 case eStateSuspended:
867 return true;
868 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000869
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000871}
872
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873bool ProcessFreeBSD::IsAThreadRunning() {
874 bool is_running = false;
875 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
876 uint32_t thread_count = m_thread_list.GetSize(false);
877 for (uint32_t i = 0; i < thread_count; ++i) {
878 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
879 m_thread_list.GetThreadAtIndex(i, false).get());
880 StateType thread_state = thread->GetState();
881 if (thread_state == eStateRunning || thread_state == eStateStepping) {
882 is_running = true;
883 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000884 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 }
886 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000887}
888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889const DataBufferSP ProcessFreeBSD::GetAuxvData() {
890 // If we're the local platform, we can ask the host for auxv data.
891 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000892 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000893
Pavel Labath5b116232017-03-17 11:33:57 +0000894 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000895 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
896 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
897
Pavel Labath5b116232017-03-17 11:33:57 +0000898 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000899 perror("sysctl failed on auxv");
900 buf_sp.reset();
901 }
902
903 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000904}
Ed Maste31f01802017-01-24 14:34:49 +0000905
906struct EmulatorBaton {
907 ProcessFreeBSD *m_process;
908 RegisterContext *m_reg_context;
909
910 // eRegisterKindDWARF -> RegisterValue
911 std::unordered_map<uint32_t, RegisterValue> m_register_values;
912
913 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
914 : m_process(process), m_reg_context(reg_context) {}
915};
916
917static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
918 const EmulateInstruction::Context &context,
919 lldb::addr_t addr, void *dst, size_t length) {
920 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
921
Zachary Turner97206d52017-05-12 04:51:55 +0000922 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000923 size_t bytes_read =
924 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
925 if (!error.Success())
926 bytes_read = 0;
927 return bytes_read;
928}
929
930static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
931 const RegisterInfo *reg_info,
932 RegisterValue &reg_value) {
933 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
934
935 auto it = emulator_baton->m_register_values.find(
936 reg_info->kinds[eRegisterKindDWARF]);
937 if (it != emulator_baton->m_register_values.end()) {
938 reg_value = it->second;
939 return true;
940 }
941
942 // The emulator only fills in the dwarf register numbers (and in some cases
943 // the generic register numbers). Get the full register info from the
944 // register context based on the dwarf register numbers.
945 const RegisterInfo *full_reg_info =
946 emulator_baton->m_reg_context->GetRegisterInfo(
947 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
948
949 bool error =
950 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
951 return error;
952}
953
954static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
955 const EmulateInstruction::Context &context,
956 const RegisterInfo *reg_info,
957 const RegisterValue &reg_value) {
958 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
959 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
960 reg_value;
961 return true;
962}
963
964static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
965 const EmulateInstruction::Context &context,
966 lldb::addr_t addr, const void *dst,
967 size_t length) {
968 return length;
969}
970
971bool ProcessFreeBSD::SingleStepBreakpointHit(
972 void *baton, lldb_private::StoppointCallbackContext *context,
973 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
974 return false;
975}
976
Zachary Turner97206d52017-05-12 04:51:55 +0000977Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
978 lldb::addr_t addr) {
979 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000980
981 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
982 if (log) {
983 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
984 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
985 }
986
987 // Validate the address.
988 if (addr == LLDB_INVALID_ADDRESS)
Zachary Turner97206d52017-05-12 04:51:55 +0000989 return Status("ProcessFreeBSD::%s invalid load address specified.",
990 __FUNCTION__);
Ed Maste31f01802017-01-24 14:34:49 +0000991
992 Breakpoint *const sw_step_break =
993 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
994 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
995 sw_step_break->SetBreakpointKind("software-signle-step");
996
997 if (log)
998 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
999 __FUNCTION__, addr);
1000
1001 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
Zachary Turner97206d52017-05-12 04:51:55 +00001002 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001003}
1004
1005bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
1006 ThreadSP thread = GetThreadList().FindThreadByID(tid);
1007 if (!thread)
1008 return false;
1009
1010 assert(thread->GetRegisterContext());
1011 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1012
1013 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1014 if (iter == m_threads_stepping_with_breakpoint.end())
1015 return false;
1016
1017 lldb::break_id_t bp_id = iter->second;
1018 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1019 if (!bp)
1020 return false;
1021
1022 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1023 if (!bp_loc)
1024 return false;
1025
1026 GetTarget().RemoveBreakpointByID(bp_id);
1027 m_threads_stepping_with_breakpoint.erase(tid);
1028 return true;
1029}
1030
1031bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1032 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
1033 if (arch.GetMachine() == llvm::Triple::arm ||
1034 arch.GetMachine() == llvm::Triple::mips64 ||
1035 arch.GetMachine() == llvm::Triple::mips64el ||
1036 arch.GetMachine() == llvm::Triple::mips ||
1037 arch.GetMachine() == llvm::Triple::mipsel)
1038 return false;
1039 return true;
1040}
1041
Zachary Turner97206d52017-05-12 04:51:55 +00001042Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
Ed Maste31f01802017-01-24 14:34:49 +00001043 std::unique_ptr<EmulateInstruction> emulator_ap(
1044 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1045 eInstructionTypePCModifying, nullptr));
1046
1047 if (emulator_ap == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001048 return Status("Instruction emulator not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001049
1050 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1051 m_thread_list.FindThreadByID(tid, false).get());
1052 if (thread == NULL)
Zachary Turner97206d52017-05-12 04:51:55 +00001053 return Status("Thread not found not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001054
1055 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1056
1057 EmulatorBaton baton(this, register_context_sp.get());
1058 emulator_ap->SetBaton(&baton);
1059 emulator_ap->SetReadMemCallback(&ReadMemoryCallback);
1060 emulator_ap->SetReadRegCallback(&ReadRegisterCallback);
1061 emulator_ap->SetWriteMemCallback(&WriteMemoryCallback);
1062 emulator_ap->SetWriteRegCallback(&WriteRegisterCallback);
1063
1064 if (!emulator_ap->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001065 return Status("Read instruction failed!");
Ed Maste31f01802017-01-24 14:34:49 +00001066
1067 bool emulation_result =
1068 emulator_ap->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
1069 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1070 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1071 auto pc_it =
1072 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1073
1074 lldb::addr_t next_pc;
1075 if (emulation_result) {
1076 assert(pc_it != baton.m_register_values.end() &&
1077 "Emulation was successful but PC wasn't updated");
1078 next_pc = pc_it->second.GetAsUInt64();
1079 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001080 // Emulate instruction failed and it haven't changed PC. Advance PC with
1081 // the size of the current opcode because the emulation of all
Ed Maste31f01802017-01-24 14:34:49 +00001082 // PC modifying instruction should be successful. The failure most
1083 // likely caused by a not supported instruction which don't modify PC.
1084 next_pc =
1085 register_context_sp->GetPC() + emulator_ap->GetOpcode().GetByteSize();
1086 } else {
1087 // The instruction emulation failed after it modified the PC. It is an
1088 // unknown error where we can't continue because the next instruction is
1089 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001090 return Status("Instruction emulation failed unexpectedly");
Ed Maste31f01802017-01-24 14:34:49 +00001091 }
1092
1093 SetSoftwareSingleStepBreakpoint(tid, next_pc);
Zachary Turner97206d52017-05-12 04:51:55 +00001094 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001095}