blob: d29a5e8c993ba4674d09d67cf805604bb957735e [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// Static functions.
68
Greg Clayton29d19302012-02-27 18:40:48 +000069lldb::ProcessSP
Zachary Turner12004eb2015-09-02 16:47:47 +000070ProcessFreeBSD::CreateInstance(lldb::TargetSP target_sp,
Jim Ingham583bbb12016-03-07 21:50:25 +000071 lldb::ListenerSP listener_sp,
Kate Stoneb9c1b512016-09-06 20:57:50 +000072 const FileSpec *crash_file_path) {
73 lldb::ProcessSP process_sp;
74 if (crash_file_path == NULL)
75 process_sp.reset(
76 new ProcessFreeBSD(target_sp, listener_sp, GetFreeBSDSignals()));
77 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000078}
79
Kate Stoneb9c1b512016-09-06 20:57:50 +000080void ProcessFreeBSD::Initialize() {
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000081 static llvm::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000082
Kamil Rytarowskic5f28e22017-02-06 17:55:02 +000083 llvm::call_once(g_once_flag, []() {
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 PluginManager::RegisterPlugin(GetPluginNameStatic(),
85 GetPluginDescriptionStatic(), CreateInstance);
Kate Stoneb9c1b512016-09-06 20:57:50 +000086 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000087}
88
Kate Stoneb9c1b512016-09-06 20:57:50 +000089lldb_private::ConstString ProcessFreeBSD::GetPluginNameStatic() {
90 static ConstString g_name("freebsd");
91 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000092}
93
Kate Stoneb9c1b512016-09-06 20:57:50 +000094const char *ProcessFreeBSD::GetPluginDescriptionStatic() {
95 return "Process plugin for FreeBSD";
Johnny Chen9ed5b492012-01-05 21:48:15 +000096}
97
Johnny Chen9ed5b492012-01-05 21:48:15 +000098// ProcessInterface protocol.
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100lldb_private::ConstString ProcessFreeBSD::GetPluginName() {
101 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000102}
103
Kate Stoneb9c1b512016-09-06 20:57:50 +0000104uint32_t ProcessFreeBSD::GetPluginVersion() { return 1; }
Johnny Chen9ed5b492012-01-05 21:48:15 +0000105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106void ProcessFreeBSD::Terminate() {}
Johnny Chen9ed5b492012-01-05 21:48:15 +0000107
Zachary Turner97206d52017-05-12 04:51:55 +0000108Status ProcessFreeBSD::DoDetach(bool keep_stopped) {
109 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110 if (keep_stopped) {
111 error.SetErrorString("Detaching with keep_stopped true is not currently "
112 "supported on FreeBSD.");
Ed Maste7dcb77d2013-08-30 13:11:30 +0000113 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 }
115
116 error = m_monitor->Detach(GetID());
117
118 if (error.Success())
119 SetPrivateState(eStateDetached);
120
121 return error;
Ed Maste7dcb77d2013-08-30 13:11:30 +0000122}
123
Zachary Turner97206d52017-05-12 04:51:55 +0000124Status ProcessFreeBSD::DoResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Ed Maste7fd845c2013-12-09 15:51:17 +0000126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 SetPrivateState(eStateRunning);
Ed Maste7fd845c2013-12-09 15:51:17 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
130 bool do_step = false;
Ed Maste31f01802017-01-24 14:34:49 +0000131 bool software_single_step = !SupportHardwareSingleStepping();
Ed Maste7fd845c2013-12-09 15:51:17 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 for (tid_collection::const_iterator t_pos = m_run_tids.begin(),
134 t_end = m_run_tids.end();
135 t_pos != t_end; ++t_pos) {
136 m_monitor->ThreadSuspend(*t_pos, false);
137 }
138 for (tid_collection::const_iterator t_pos = m_step_tids.begin(),
139 t_end = m_step_tids.end();
140 t_pos != t_end; ++t_pos) {
141 m_monitor->ThreadSuspend(*t_pos, false);
142 do_step = true;
Ed Maste31f01802017-01-24 14:34:49 +0000143 if (software_single_step) {
Zachary Turner97206d52017-05-12 04:51:55 +0000144 Status error = SetupSoftwareSingleStepping(*t_pos);
Ed Maste31f01802017-01-24 14:34:49 +0000145 if (error.Fail())
146 return error;
147 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 }
149 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(),
150 t_end = m_suspend_tids.end();
151 t_pos != t_end; ++t_pos) {
152 m_monitor->ThreadSuspend(*t_pos, true);
153 // XXX Cannot PT_CONTINUE properly with suspended threads.
154 do_step = true;
155 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000156
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 if (log)
158 log->Printf("process %" PRIu64 " resuming (%s)", GetID(),
159 do_step ? "step" : "continue");
Ed Maste31f01802017-01-24 14:34:49 +0000160 if (do_step && !software_single_step)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 m_monitor->SingleStep(GetID(), m_resume_signo);
162 else
163 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000164
Zachary Turner97206d52017-05-12 04:51:55 +0000165 return Status();
Ed Maste7fd845c2013-12-09 15:51:17 +0000166}
167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168bool ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list,
169 ThreadList &new_thread_list) {
170 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
171 if (log)
172 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__,
173 GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000174
Kate Stoneb9c1b512016-09-06 20:57:50 +0000175 std::vector<lldb::pid_t> tds;
176 if (!GetMonitor().GetCurrentThreadIDs(tds)) {
177 return false;
178 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 ThreadList old_thread_list_copy(old_thread_list);
181 for (size_t i = 0; i < tds.size(); ++i) {
182 tid_t tid = tds[i];
183 ThreadSP thread_sp(old_thread_list_copy.RemoveThreadByID(tid, false));
184 if (!thread_sp) {
185 thread_sp.reset(new FreeBSDThread(*this, tid));
186 if (log)
187 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
188 } else {
189 if (log)
190 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__,
191 tid);
Ed Maste7fd845c2013-12-09 15:51:17 +0000192 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 new_thread_list.AddThread(thread_sp);
194 }
195 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i) {
196 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
197 if (old_thread_sp) {
198 if (log)
199 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
Ed Maste7fd845c2013-12-09 15:51:17 +0000200 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000201 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000202
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000204}
Ed Maste7fd845c2013-12-09 15:51:17 +0000205
Zachary Turner97206d52017-05-12 04:51:55 +0000206Status ProcessFreeBSD::WillResume() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000207 m_resume_signo = 0;
208 m_suspend_tids.clear();
209 m_run_tids.clear();
210 m_step_tids.clear();
211 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000212}
213
Kate Stoneb9c1b512016-09-06 20:57:50 +0000214void ProcessFreeBSD::SendMessage(const ProcessMessage &message) {
215 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Maste7fd845c2013-12-09 15:51:17 +0000216
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 switch (message.GetKind()) {
218 case ProcessMessage::eInvalidMessage:
219 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000220
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 case ProcessMessage::eAttachMessage:
222 SetPrivateState(eStateStopped);
223 return;
Ed Maste7fd845c2013-12-09 15:51:17 +0000224
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225 case ProcessMessage::eLimboMessage:
226 case ProcessMessage::eExitMessage:
227 SetExitStatus(message.GetExitStatus(), NULL);
228 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 case ProcessMessage::eSignalMessage:
231 case ProcessMessage::eSignalDeliveredMessage:
232 case ProcessMessage::eBreakpointMessage:
233 case ProcessMessage::eTraceMessage:
234 case ProcessMessage::eWatchpointMessage:
235 case ProcessMessage::eCrashMessage:
236 SetPrivateState(eStateStopped);
237 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 case ProcessMessage::eNewThreadMessage:
240 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
241 break;
Ed Maste7fd845c2013-12-09 15:51:17 +0000242
Kate Stoneb9c1b512016-09-06 20:57:50 +0000243 case ProcessMessage::eExecMessage:
244 SetPrivateState(eStateStopped);
245 break;
246 }
Ed Maste7fd845c2013-12-09 15:51:17 +0000247
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 m_message_queue.push(message);
Ed Maste7fd845c2013-12-09 15:51:17 +0000249}
Ed Mastefe5a6422015-07-28 15:45:57 +0000250
Ed Mastefe5a6422015-07-28 15:45:57 +0000251// Constructors and destructors.
252
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253ProcessFreeBSD::ProcessFreeBSD(lldb::TargetSP target_sp,
254 lldb::ListenerSP listener_sp,
255 UnixSignalsSP &unix_signals_sp)
Jim Ingham583bbb12016-03-07 21:50:25 +0000256 : Process(target_sp, listener_sp, unix_signals_sp),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 m_byte_order(endian::InlHostByteOrder()), m_monitor(NULL), m_module(NULL),
258 m_message_mutex(), m_exit_now(false), m_seen_initial_stop(),
259 m_resume_signo(0) {
260 // FIXME: Putting this code in the ctor and saving the byte order in a
261 // member variable is a hack to avoid const qual issues in GetByteOrder.
262 lldb::ModuleSP module = GetTarget().GetExecutableModule();
263 if (module && module->GetObjectFile())
264 m_byte_order = module->GetObjectFile()->GetByteOrder();
Ed Mastefe5a6422015-07-28 15:45:57 +0000265}
266
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267ProcessFreeBSD::~ProcessFreeBSD() { delete m_monitor; }
Ed Mastefe5a6422015-07-28 15:45:57 +0000268
Ed Mastefe5a6422015-07-28 15:45:57 +0000269// Process protocol.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270void ProcessFreeBSD::Finalize() {
Ed Mastefe5a6422015-07-28 15:45:57 +0000271 Process::Finalize();
272
273 if (m_monitor)
274 m_monitor->StopMonitor();
275}
276
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277bool ProcessFreeBSD::CanDebug(lldb::TargetSP target_sp,
278 bool plugin_specified_by_name) {
279 // For now we are just making sure the file exists for a given module
280 ModuleSP exe_module_sp(target_sp->GetExecutableModule());
281 if (exe_module_sp.get())
Jonas Devlieghere49996c12018-11-01 17:46:31 +0000282 return FileSystem::Instance().Exists(exe_module_sp->GetFileSpec());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 // If there is no executable module, we return true since we might be
284 // preparing to attach.
285 return true;
Ed Mastefe5a6422015-07-28 15:45:57 +0000286}
287
Zachary Turner97206d52017-05-12 04:51:55 +0000288Status
289ProcessFreeBSD::DoAttachToProcessWithID(lldb::pid_t pid,
290 const ProcessAttachInfo &attach_info) {
291 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000295 LLDB_LOGV(log, "pid = {0}", GetID());
Ed Mastefe5a6422015-07-28 15:45:57 +0000296
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 m_monitor = new ProcessMonitor(this, pid, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000298
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 if (!error.Success())
Ed Mastefe5a6422015-07-28 15:45:57 +0000300 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301
302 PlatformSP platform_sp(GetTarget().GetPlatform());
303 assert(platform_sp.get());
304 if (!platform_sp)
305 return error; // FIXME: Detatch?
306
307 // Find out what we can about this process
308 ProcessInstanceInfo process_info;
309 platform_sp->GetProcessInfo(pid, process_info);
310
311 // Resolve the executable module
312 ModuleSP exe_module_sp;
313 FileSpecList executable_search_paths(
314 Target::GetDefaultExecutableSearchPaths());
315 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
316 GetTarget().GetArchitecture());
317 error = platform_sp->ResolveExecutable(
318 exe_module_spec, exe_module_sp,
319 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
320 if (!error.Success())
321 return error;
322
323 // Fix the target architecture if necessary
324 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
325 if (module_arch.IsValid() &&
326 !GetTarget().GetArchitecture().IsExactMatch(module_arch))
327 GetTarget().SetArchitecture(module_arch);
328
329 // Initialize the target module list
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000330 GetTarget().SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331
332 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
333
334 SetID(pid);
335
336 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000337}
338
Zachary Turner97206d52017-05-12 04:51:55 +0000339Status ProcessFreeBSD::WillLaunch(Module *module) {
340 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000342}
343
344FileSpec
345ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 const FileSpec &default_file_spec,
347 const FileSpec &dbg_pts_file_spec) {
348 FileSpec file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen) {
351 file_spec = file_action->GetFileSpec();
Adrian Prantl05097242018-04-30 16:49:04 +0000352 // By default the stdio paths passed in will be pseudo-terminal (/dev/pts).
353 // If so, convert to using a different default path instead to redirect I/O
354 // to the debugger console. This should also handle user overrides to
355 // /dev/null or a different file.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (!file_spec || file_spec == dbg_pts_file_spec)
357 file_spec = default_file_spec;
358 }
359 return file_spec;
Ed Mastefe5a6422015-07-28 15:45:57 +0000360}
361
Zachary Turner97206d52017-05-12 04:51:55 +0000362Status ProcessFreeBSD::DoLaunch(Module *module,
363 ProcessLaunchInfo &launch_info) {
364 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 assert(m_monitor == NULL);
Ed Mastefe5a6422015-07-28 15:45:57 +0000366
Kate Stoneb9c1b512016-09-06 20:57:50 +0000367 FileSpec working_dir = launch_info.GetWorkingDirectory();
David Carlier511e1cf2018-11-04 23:19:25 +0000368 if (working_dir) {
369 FileSystem::Instance().Resolve(working_dir);
Jonas Devlieghere3a58d892018-11-08 00:14:50 +0000370 if (!FileSystem::Instance().IsDirectory(working_dir.GetPath())) {
David Carlier511e1cf2018-11-04 23:19:25 +0000371 error.SetErrorStringWithFormat("No such file or directory: %s",
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 working_dir.GetCString());
David Carlier511e1cf2018-11-04 23:19:25 +0000373 return error;
374 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000376
Kate Stoneb9c1b512016-09-06 20:57:50 +0000377 SetPrivateState(eStateLaunching);
Ed Mastefe5a6422015-07-28 15:45:57 +0000378
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 const lldb_private::FileAction *file_action;
Ed Mastefe5a6422015-07-28 15:45:57 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 // Default of empty will mean to use existing open file descriptors
382 FileSpec stdin_file_spec{};
383 FileSpec stdout_file_spec{};
384 FileSpec stderr_file_spec{};
Ed Mastefe5a6422015-07-28 15:45:57 +0000385
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000386 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL, 0)};
Ed Mastefe5a6422015-07-28 15:45:57 +0000387
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
389 stdin_file_spec =
390 GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000391
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
393 stdout_file_spec =
394 GetFileSpec(file_action, stdout_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(STDERR_FILENO);
397 stderr_file_spec =
398 GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
Ed Mastefe5a6422015-07-28 15:45:57 +0000399
Kate Stoneb9c1b512016-09-06 20:57:50 +0000400 m_monitor = new ProcessMonitor(
401 this, module, launch_info.GetArguments().GetConstArgumentVector(),
Pavel Labath75c6de02018-01-10 13:53:40 +0000402 launch_info.GetEnvironment(), stdin_file_spec, stdout_file_spec,
Pavel Labath3ff377a2018-01-10 12:25:48 +0000403 stderr_file_spec, working_dir, launch_info, error);
Ed Mastefe5a6422015-07-28 15:45:57 +0000404
Kate Stoneb9c1b512016-09-06 20:57:50 +0000405 m_module = module;
Ed Mastefe5a6422015-07-28 15:45:57 +0000406
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 if (!error.Success())
408 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000409
Kate Stoneb9c1b512016-09-06 20:57:50 +0000410 int terminal = m_monitor->GetTerminalFD();
411 if (terminal >= 0) {
412// The reader thread will close the file descriptor when done, so we pass it a
413// copy.
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000414#ifdef F_DUPFD_CLOEXEC
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
416 if (stdio == -1) {
417 error.SetErrorToErrno();
418 return error;
419 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000420#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 // Special case when F_DUPFD_CLOEXEC does not exist (Debian kFreeBSD)
422 int stdio = fcntl(terminal, F_DUPFD, 0);
423 if (stdio == -1) {
424 error.SetErrorToErrno();
425 return error;
426 }
427 stdio = fcntl(terminal, F_SETFD, FD_CLOEXEC);
428 if (stdio == -1) {
429 error.SetErrorToErrno();
430 return error;
431 }
Sylvestre Ledru79cb0092015-08-28 12:24:07 +0000432#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 SetSTDIOFileDescriptor(stdio);
434 }
435
436 SetID(m_monitor->GetPID());
437 return error;
438}
439
440void ProcessFreeBSD::DidLaunch() {}
441
442addr_t ProcessFreeBSD::GetImageInfoAddress() {
443 Target *target = &GetTarget();
444 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
445 Address addr = obj_file->GetImageInfoAddress(target);
446
447 if (addr.IsValid())
448 return addr.GetLoadAddress(target);
449 return LLDB_INVALID_ADDRESS;
450}
451
Zachary Turner97206d52017-05-12 04:51:55 +0000452Status ProcessFreeBSD::DoHalt(bool &caused_stop) {
453 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454
455 if (IsStopped()) {
456 caused_stop = false;
457 } else if (kill(GetID(), SIGSTOP)) {
458 caused_stop = false;
459 error.SetErrorToErrno();
460 } else {
461 caused_stop = true;
462 }
463 return error;
464}
465
Zachary Turner97206d52017-05-12 04:51:55 +0000466Status ProcessFreeBSD::DoSignal(int signal) {
467 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468
469 if (kill(GetID(), signal))
470 error.SetErrorToErrno();
471
472 return error;
473}
474
Zachary Turner97206d52017-05-12 04:51:55 +0000475Status ProcessFreeBSD::DoDestroy() {
476 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000477
478 if (!HasExited()) {
479 assert(m_monitor);
480 m_exit_now = true;
481 if (GetID() == LLDB_INVALID_PROCESS_ID) {
482 error.SetErrorString("invalid process id");
483 return error;
484 }
485 if (!m_monitor->Kill()) {
486 error.SetErrorToErrno();
487 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000488 }
489
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 SetPrivateState(eStateExited);
491 }
492
493 return error;
Ed Mastefe5a6422015-07-28 15:45:57 +0000494}
495
Kate Stoneb9c1b512016-09-06 20:57:50 +0000496void ProcessFreeBSD::DoDidExec() {
497 Target *target = &GetTarget();
498 if (target) {
499 PlatformSP platform_sp(target->GetPlatform());
500 assert(platform_sp.get());
501 if (platform_sp) {
502 ProcessInstanceInfo process_info;
503 platform_sp->GetProcessInfo(GetID(), process_info);
504 ModuleSP exe_module_sp;
505 ModuleSpec exe_module_spec(process_info.GetExecutableFile(),
506 target->GetArchitecture());
507 FileSpecList executable_search_paths(
508 Target::GetDefaultExecutableSearchPaths());
Zachary Turner97206d52017-05-12 04:51:55 +0000509 Status error = platform_sp->ResolveExecutable(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 exe_module_spec, exe_module_sp,
511 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
512 if (!error.Success())
513 return;
Tatyana Krasnukha891d7502018-09-25 17:59:44 +0000514 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
Ed Mastefe5a6422015-07-28 15:45:57 +0000515 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000517}
518
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519bool ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid) {
520 bool added_to_set = false;
521 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
522 if (it == m_seen_initial_stop.end()) {
523 m_seen_initial_stop.insert(stop_tid);
524 added_to_set = true;
525 }
526 return added_to_set;
Ed Mastefe5a6422015-07-28 15:45:57 +0000527}
528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529bool ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid) {
530 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
Ed Mastefe5a6422015-07-28 15:45:57 +0000531}
532
533FreeBSDThread *
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process,
535 lldb::tid_t tid) {
536 return new FreeBSDThread(process, tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000537}
538
Kate Stoneb9c1b512016-09-06 20:57:50 +0000539void ProcessFreeBSD::RefreshStateAfterStop() {
540 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
Pavel Labathaafe0532017-02-06 19:31:05 +0000541 LLDB_LOGV(log, "message_queue size = {0}", m_message_queue.size());
Ed Mastefe5a6422015-07-28 15:45:57 +0000542
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 std::lock_guard<std::recursive_mutex> guard(m_message_mutex);
Ed Mastefe5a6422015-07-28 15:45:57 +0000544
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 // This method used to only handle one message. Changing it to loop allows
546 // it to handle the case where we hit a breakpoint while handling a different
547 // breakpoint.
548 while (!m_message_queue.empty()) {
549 ProcessMessage &message = m_message_queue.front();
Ed Mastefe5a6422015-07-28 15:45:57 +0000550
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 // Resolve the thread this message corresponds to and pass it along.
552 lldb::tid_t tid = message.GetTID();
Pavel Labathaafe0532017-02-06 19:31:05 +0000553 LLDB_LOGV(log, " message_queue size = {0}, pid = {1}",
554 m_message_queue.size(), tid);
Ed Mastefe5a6422015-07-28 15:45:57 +0000555
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 m_thread_list.RefreshStateAfterStop();
Ed Mastefe5a6422015-07-28 15:45:57 +0000557
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
559 GetThreadList().FindThreadByID(tid, false).get());
Ed Mastefe5a6422015-07-28 15:45:57 +0000560 if (thread)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 thread->Notify(message);
562
563 if (message.GetKind() == ProcessMessage::eExitMessage) {
564 // FIXME: We should tell the user about this, but the limbo message is
565 // probably better for that.
Pavel Labathaafe0532017-02-06 19:31:05 +0000566 LLDB_LOG(log, "removing thread, tid = {0}", tid);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000567 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
568
569 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
570 thread_sp.reset();
571 m_seen_initial_stop.erase(tid);
572 }
573
574 m_message_queue.pop();
575 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000576}
577
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578bool ProcessFreeBSD::IsAlive() {
579 StateType state = GetPrivateState();
580 return state != eStateDetached && state != eStateExited &&
581 state != eStateInvalid && state != eStateUnloaded;
Ed Mastefe5a6422015-07-28 15:45:57 +0000582}
583
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584size_t ProcessFreeBSD::DoReadMemory(addr_t vm_addr, void *buf, size_t size,
Zachary Turner97206d52017-05-12 04:51:55 +0000585 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000586 assert(m_monitor);
587 return m_monitor->ReadMemory(vm_addr, buf, size, error);
588}
589
590size_t ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf,
Zachary Turner97206d52017-05-12 04:51:55 +0000591 size_t size, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000592 assert(m_monitor);
593 return m_monitor->WriteMemory(vm_addr, buf, size, error);
594}
595
596addr_t ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
Zachary Turner97206d52017-05-12 04:51:55 +0000597 Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000598 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
599
600 unsigned prot = 0;
601 if (permissions & lldb::ePermissionsReadable)
602 prot |= eMmapProtRead;
603 if (permissions & lldb::ePermissionsWritable)
604 prot |= eMmapProtWrite;
605 if (permissions & lldb::ePermissionsExecutable)
606 prot |= eMmapProtExec;
607
608 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
609 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
610 m_addr_to_mmap_size[allocated_addr] = size;
611 error.Clear();
612 } else {
613 allocated_addr = LLDB_INVALID_ADDRESS;
614 error.SetErrorStringWithFormat(
615 "unable to allocate %zu bytes of memory with permissions %s", size,
616 GetPermissionsAsCString(permissions));
617 }
618
619 return allocated_addr;
620}
621
Zachary Turner97206d52017-05-12 04:51:55 +0000622Status ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr) {
623 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000624 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
625 if (pos != m_addr_to_mmap_size.end() &&
626 InferiorCallMunmap(this, addr, pos->second))
627 m_addr_to_mmap_size.erase(pos);
628 else
629 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64,
630 addr);
631
632 return error;
633}
634
635size_t
636ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
637 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xD4};
638 static const uint8_t g_i386_opcode[] = {0xCC};
639
640 ArchSpec arch = GetTarget().GetArchitecture();
641 const uint8_t *opcode = NULL;
642 size_t opcode_size = 0;
643
644 switch (arch.GetMachine()) {
645 default:
646 assert(false && "CPU type not supported!");
647 break;
648
649 case llvm::Triple::arm: {
Adrian Prantl05097242018-04-30 16:49:04 +0000650 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
651 // linux kernel does otherwise.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
653 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
654
655 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000656 AddressClass addr_class = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657
658 if (bp_loc_sp)
659 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
660
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000661 if (addr_class == AddressClass::eCodeAlternateISA ||
662 (addr_class == AddressClass::eUnknown &&
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 bp_loc_sp->GetAddress().GetOffset() & 1)) {
664 opcode = g_thumb_breakpoint_opcode;
665 opcode_size = sizeof(g_thumb_breakpoint_opcode);
666 } else {
667 opcode = g_arm_breakpoint_opcode;
668 opcode_size = sizeof(g_arm_breakpoint_opcode);
669 }
670 } break;
671 case llvm::Triple::aarch64:
672 opcode = g_aarch64_opcode;
673 opcode_size = sizeof(g_aarch64_opcode);
674 break;
675
676 case llvm::Triple::x86:
677 case llvm::Triple::x86_64:
678 opcode = g_i386_opcode;
679 opcode_size = sizeof(g_i386_opcode);
680 break;
681 }
682
683 bp_site->SetTrapOpcode(opcode, opcode_size);
684 return opcode_size;
685}
686
Zachary Turner97206d52017-05-12 04:51:55 +0000687Status ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 return EnableSoftwareBreakpoint(bp_site);
689}
690
Zachary Turner97206d52017-05-12 04:51:55 +0000691Status ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 return DisableSoftwareBreakpoint(bp_site);
693}
694
Zachary Turner97206d52017-05-12 04:51:55 +0000695Status ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify) {
696 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 if (wp) {
698 user_id_t watchID = wp->GetID();
699 addr_t addr = wp->GetLoadAddress();
700 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
701 if (log)
702 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
703 watchID);
704 if (wp->IsEnabled()) {
705 if (log)
706 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
707 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
708 watchID, (uint64_t)addr);
709 return error;
710 }
711
712 // Try to find a vacant watchpoint slot in the inferiors' main thread
713 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
Saleem Abdulrasoolbb19a132016-05-19 05:13:57 +0000714 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000715 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
716 m_thread_list.GetThreadAtIndex(0, false).get());
717
718 if (thread)
719 wp_hw_index = thread->FindVacantWatchpointIndex();
720
721 if (wp_hw_index == LLDB_INVALID_INDEX32) {
722 error.SetErrorString("Setting hardware watchpoint failed.");
723 } else {
724 wp->SetHardwareIndex(wp_hw_index);
725 bool wp_enabled = true;
726 uint32_t thread_count = m_thread_list.GetSize(false);
727 for (uint32_t i = 0; i < thread_count; ++i) {
728 thread = static_cast<FreeBSDThread *>(
729 m_thread_list.GetThreadAtIndex(i, false).get());
730 if (thread)
731 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
732 else
733 wp_enabled = false;
734 }
735 if (wp_enabled) {
736 wp->SetEnabled(true, notify);
737 return error;
738 } else {
Adrian Prantl05097242018-04-30 16:49:04 +0000739 // Watchpoint enabling failed on at least one of the threads so roll
740 // back all of them
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 DisableWatchpoint(wp, false);
742 error.SetErrorString("Setting hardware watchpoint failed");
743 }
744 }
745 } else
746 error.SetErrorString("Watchpoint argument was NULL.");
747 return error;
748}
749
Zachary Turner97206d52017-05-12 04:51:55 +0000750Status ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify) {
751 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 if (wp) {
753 user_id_t watchID = wp->GetID();
754 addr_t addr = wp->GetLoadAddress();
755 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
756 if (log)
757 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
758 watchID);
759 if (!wp->IsEnabled()) {
760 if (log)
761 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
762 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
763 watchID, (uint64_t)addr);
764 // This is needed (for now) to keep watchpoints disabled correctly
765 wp->SetEnabled(false, notify);
766 return error;
767 }
768
769 if (wp->IsHardware()) {
770 bool wp_disabled = true;
771 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
772 uint32_t thread_count = m_thread_list.GetSize(false);
773 for (uint32_t i = 0; i < thread_count; ++i) {
774 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
775 m_thread_list.GetThreadAtIndex(i, false).get());
776 if (thread)
777 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
778 else
779 wp_disabled = false;
780 }
781 if (wp_disabled) {
782 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
783 wp->SetEnabled(false, notify);
784 return error;
785 } else
786 error.SetErrorString("Disabling hardware watchpoint failed");
787 }
788 } else
789 error.SetErrorString("Watchpoint argument was NULL.");
790 return error;
791}
792
Zachary Turner97206d52017-05-12 04:51:55 +0000793Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num) {
794 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
796 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
797 m_thread_list.GetThreadAtIndex(0, false).get());
798 if (thread)
799 num = thread->NumSupportedHardwareWatchpoints();
800 else
801 error.SetErrorString("Process does not exist.");
802 return error;
803}
804
Zachary Turner97206d52017-05-12 04:51:55 +0000805Status ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
806 Status error = GetWatchpointSupportInfo(num);
Adrian Prantl05097242018-04-30 16:49:04 +0000807 // Watchpoints trigger and halt the inferior after the corresponding
808 // instruction has been executed.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 after = true;
810 return error;
811}
812
813uint32_t ProcessFreeBSD::UpdateThreadListIfNeeded() {
814 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
815 // Do not allow recursive updates.
816 return m_thread_list.GetSize(false);
Ed Mastefe5a6422015-07-28 15:45:57 +0000817}
818
Kate Stoneb9c1b512016-09-06 20:57:50 +0000819ByteOrder ProcessFreeBSD::GetByteOrder() const {
820 // FIXME: We should be able to extract this value directly. See comment in
821 // ProcessFreeBSD().
822 return m_byte_order;
Ed Mastefe5a6422015-07-28 15:45:57 +0000823}
824
Zachary Turner97206d52017-05-12 04:51:55 +0000825size_t ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Status &error) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 ssize_t status;
827 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0) {
828 error.SetErrorToErrno();
829 return 0;
830 }
831 return status;
Ed Mastefe5a6422015-07-28 15:45:57 +0000832}
833
Ed Mastefe5a6422015-07-28 15:45:57 +0000834// Utility functions.
835
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836bool ProcessFreeBSD::HasExited() {
837 switch (GetPrivateState()) {
838 default:
839 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000840
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 case eStateDetached:
842 case eStateExited:
843 return true;
844 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000845
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000847}
848
Kate Stoneb9c1b512016-09-06 20:57:50 +0000849bool ProcessFreeBSD::IsStopped() {
850 switch (GetPrivateState()) {
851 default:
852 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000853
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 case eStateStopped:
855 case eStateCrashed:
856 case eStateSuspended:
857 return true;
858 }
Ed Mastefe5a6422015-07-28 15:45:57 +0000859
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 return false;
Ed Mastefe5a6422015-07-28 15:45:57 +0000861}
862
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863bool ProcessFreeBSD::IsAThreadRunning() {
864 bool is_running = false;
865 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
866 uint32_t thread_count = m_thread_list.GetSize(false);
867 for (uint32_t i = 0; i < thread_count; ++i) {
868 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
869 m_thread_list.GetThreadAtIndex(i, false).get());
870 StateType thread_state = thread->GetState();
871 if (thread_state == eStateRunning || thread_state == eStateStepping) {
872 is_running = true;
873 break;
Ed Mastefe5a6422015-07-28 15:45:57 +0000874 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000875 }
876 return is_running;
Ed Mastefe5a6422015-07-28 15:45:57 +0000877}
878
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879const DataBufferSP ProcessFreeBSD::GetAuxvData() {
880 // If we're the local platform, we can ask the host for auxv data.
881 PlatformSP platform_sp = GetTarget().GetPlatform();
Pavel Labathb7f0f452017-03-17 11:08:40 +0000882 assert(platform_sp && platform_sp->IsHost());
Ed Mastefe5a6422015-07-28 15:45:57 +0000883
Pavel Labath5b116232017-03-17 11:33:57 +0000884 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_AUXV, (int)m_process->GetID()};
Pavel Labathb7f0f452017-03-17 11:08:40 +0000885 size_t auxv_size = AT_COUNT * sizeof(Elf_Auxinfo);
886 DataBufferSP buf_sp(new DataBufferHeap(auxv_size, 0));
887
Pavel Labath5b116232017-03-17 11:33:57 +0000888 if (::sysctl(mib, 4, buf_sp->GetBytes(), &auxv_size, NULL, 0) != 0) {
Pavel Labathb7f0f452017-03-17 11:08:40 +0000889 perror("sysctl failed on auxv");
890 buf_sp.reset();
891 }
892
893 return buf_sp;
Ed Mastefe5a6422015-07-28 15:45:57 +0000894}
Ed Maste31f01802017-01-24 14:34:49 +0000895
896struct EmulatorBaton {
897 ProcessFreeBSD *m_process;
898 RegisterContext *m_reg_context;
899
900 // eRegisterKindDWARF -> RegisterValue
901 std::unordered_map<uint32_t, RegisterValue> m_register_values;
902
903 EmulatorBaton(ProcessFreeBSD *process, RegisterContext *reg_context)
904 : m_process(process), m_reg_context(reg_context) {}
905};
906
907static size_t ReadMemoryCallback(EmulateInstruction *instruction, void *baton,
908 const EmulateInstruction::Context &context,
909 lldb::addr_t addr, void *dst, size_t length) {
910 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
911
Zachary Turner97206d52017-05-12 04:51:55 +0000912 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000913 size_t bytes_read =
914 emulator_baton->m_process->DoReadMemory(addr, dst, length, error);
915 if (!error.Success())
916 bytes_read = 0;
917 return bytes_read;
918}
919
920static bool ReadRegisterCallback(EmulateInstruction *instruction, void *baton,
921 const RegisterInfo *reg_info,
922 RegisterValue &reg_value) {
923 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
924
925 auto it = emulator_baton->m_register_values.find(
926 reg_info->kinds[eRegisterKindDWARF]);
927 if (it != emulator_baton->m_register_values.end()) {
928 reg_value = it->second;
929 return true;
930 }
931
932 // The emulator only fills in the dwarf register numbers (and in some cases
933 // the generic register numbers). Get the full register info from the
934 // register context based on the dwarf register numbers.
935 const RegisterInfo *full_reg_info =
936 emulator_baton->m_reg_context->GetRegisterInfo(
937 eRegisterKindDWARF, reg_info->kinds[eRegisterKindDWARF]);
938
939 bool error =
940 emulator_baton->m_reg_context->ReadRegister(full_reg_info, reg_value);
941 return error;
942}
943
944static bool WriteRegisterCallback(EmulateInstruction *instruction, void *baton,
945 const EmulateInstruction::Context &context,
946 const RegisterInfo *reg_info,
947 const RegisterValue &reg_value) {
948 EmulatorBaton *emulator_baton = static_cast<EmulatorBaton *>(baton);
949 emulator_baton->m_register_values[reg_info->kinds[eRegisterKindDWARF]] =
950 reg_value;
951 return true;
952}
953
954static size_t WriteMemoryCallback(EmulateInstruction *instruction, void *baton,
955 const EmulateInstruction::Context &context,
956 lldb::addr_t addr, const void *dst,
957 size_t length) {
958 return length;
959}
960
961bool ProcessFreeBSD::SingleStepBreakpointHit(
962 void *baton, lldb_private::StoppointCallbackContext *context,
963 lldb::user_id_t break_id, lldb::user_id_t break_loc_id) {
964 return false;
965}
966
Zachary Turner97206d52017-05-12 04:51:55 +0000967Status ProcessFreeBSD::SetSoftwareSingleStepBreakpoint(lldb::tid_t tid,
968 lldb::addr_t addr) {
969 Status error;
Ed Maste31f01802017-01-24 14:34:49 +0000970
971 Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_PROCESS));
972 if (log) {
973 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
974 log->Printf("SoftwareBreakpoint::%s addr = 0x%" PRIx64, __FUNCTION__, addr);
975 }
976
977 // Validate the address.
978 if (addr == LLDB_INVALID_ADDRESS)
Zachary Turner97206d52017-05-12 04:51:55 +0000979 return Status("ProcessFreeBSD::%s invalid load address specified.",
980 __FUNCTION__);
Ed Maste31f01802017-01-24 14:34:49 +0000981
982 Breakpoint *const sw_step_break =
983 m_process->GetTarget().CreateBreakpoint(addr, true, false).get();
984 sw_step_break->SetCallback(SingleStepBreakpointHit, this, true);
985 sw_step_break->SetBreakpointKind("software-signle-step");
986
987 if (log)
988 log->Printf("ProcessFreeBSD::%s addr = 0x%" PRIx64 " -- SUCCESS",
989 __FUNCTION__, addr);
990
991 m_threads_stepping_with_breakpoint.insert({tid, sw_step_break->GetID()});
Zachary Turner97206d52017-05-12 04:51:55 +0000992 return Status();
Ed Maste31f01802017-01-24 14:34:49 +0000993}
994
995bool ProcessFreeBSD::IsSoftwareStepBreakpoint(lldb::tid_t tid) {
996 ThreadSP thread = GetThreadList().FindThreadByID(tid);
997 if (!thread)
998 return false;
999
1000 assert(thread->GetRegisterContext());
1001 lldb::addr_t stop_pc = thread->GetRegisterContext()->GetPC();
1002
1003 const auto &iter = m_threads_stepping_with_breakpoint.find(tid);
1004 if (iter == m_threads_stepping_with_breakpoint.end())
1005 return false;
1006
1007 lldb::break_id_t bp_id = iter->second;
1008 BreakpointSP bp = GetTarget().GetBreakpointByID(bp_id);
1009 if (!bp)
1010 return false;
1011
1012 BreakpointLocationSP bp_loc = bp->FindLocationByAddress(stop_pc);
1013 if (!bp_loc)
1014 return false;
1015
1016 GetTarget().RemoveBreakpointByID(bp_id);
1017 m_threads_stepping_with_breakpoint.erase(tid);
1018 return true;
1019}
1020
1021bool ProcessFreeBSD::SupportHardwareSingleStepping() const {
1022 lldb_private::ArchSpec arch = GetTarget().GetArchitecture();
Fangrui Songddb93b62019-05-16 08:37:32 +00001023 if (arch.GetMachine() == llvm::Triple::arm || arch.IsMIPS())
Ed Maste31f01802017-01-24 14:34:49 +00001024 return false;
1025 return true;
1026}
1027
Zachary Turner97206d52017-05-12 04:51:55 +00001028Status ProcessFreeBSD::SetupSoftwareSingleStepping(lldb::tid_t tid) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001029 std::unique_ptr<EmulateInstruction> emulator_up(
Ed Maste31f01802017-01-24 14:34:49 +00001030 EmulateInstruction::FindPlugin(GetTarget().GetArchitecture(),
1031 eInstructionTypePCModifying, nullptr));
1032
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001033 if (emulator_up == nullptr)
Zachary Turner97206d52017-05-12 04:51:55 +00001034 return Status("Instruction emulator not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001035
1036 FreeBSDThread *thread = static_cast<FreeBSDThread *>(
1037 m_thread_list.FindThreadByID(tid, false).get());
1038 if (thread == NULL)
Zachary Turner97206d52017-05-12 04:51:55 +00001039 return Status("Thread not found not found!");
Ed Maste31f01802017-01-24 14:34:49 +00001040
1041 lldb::RegisterContextSP register_context_sp = thread->GetRegisterContext();
1042
1043 EmulatorBaton baton(this, register_context_sp.get());
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001044 emulator_up->SetBaton(&baton);
1045 emulator_up->SetReadMemCallback(&ReadMemoryCallback);
1046 emulator_up->SetReadRegCallback(&ReadRegisterCallback);
1047 emulator_up->SetWriteMemCallback(&WriteMemoryCallback);
1048 emulator_up->SetWriteRegCallback(&WriteRegisterCallback);
Ed Maste31f01802017-01-24 14:34:49 +00001049
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001050 if (!emulator_up->ReadInstruction())
Zachary Turner97206d52017-05-12 04:51:55 +00001051 return Status("Read instruction failed!");
Ed Maste31f01802017-01-24 14:34:49 +00001052
1053 bool emulation_result =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001054 emulator_up->EvaluateInstruction(eEmulateInstructionOptionAutoAdvancePC);
Ed Maste31f01802017-01-24 14:34:49 +00001055 const RegisterInfo *reg_info_pc = register_context_sp->GetRegisterInfo(
1056 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1057 auto pc_it =
1058 baton.m_register_values.find(reg_info_pc->kinds[eRegisterKindDWARF]);
1059
1060 lldb::addr_t next_pc;
1061 if (emulation_result) {
1062 assert(pc_it != baton.m_register_values.end() &&
1063 "Emulation was successful but PC wasn't updated");
1064 next_pc = pc_it->second.GetAsUInt64();
1065 } else if (pc_it == baton.m_register_values.end()) {
Adrian Prantl05097242018-04-30 16:49:04 +00001066 // Emulate instruction failed and it haven't changed PC. Advance PC with
1067 // the size of the current opcode because the emulation of all
Ed Maste31f01802017-01-24 14:34:49 +00001068 // PC modifying instruction should be successful. The failure most
1069 // likely caused by a not supported instruction which don't modify PC.
1070 next_pc =
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001071 register_context_sp->GetPC() + emulator_up->GetOpcode().GetByteSize();
Ed Maste31f01802017-01-24 14:34:49 +00001072 } else {
1073 // The instruction emulation failed after it modified the PC. It is an
1074 // unknown error where we can't continue because the next instruction is
1075 // modifying the PC but we don't know how.
Zachary Turner97206d52017-05-12 04:51:55 +00001076 return Status("Instruction emulation failed unexpectedly");
Ed Maste31f01802017-01-24 14:34:49 +00001077 }
1078
1079 SetSoftwareSingleStepBreakpoint(tid, next_pc);
Zachary Turner97206d52017-05-12 04:51:55 +00001080 return Status();
Ed Maste31f01802017-01-24 14:34:49 +00001081}