blob: 8d8525481d9057ed006001d600aa58f835ec217c [file] [log] [blame]
Johnny Chen9ed5b492012-01-05 21:48:15 +00001//===-- ProcessFreeBSD.cpp ----------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <errno.h>
12
13// C++ Includes
Benjamin Kramer3f69fa62015-04-03 10:55:00 +000014#include <mutex>
15
Johnny Chen9ed5b492012-01-05 21:48:15 +000016// Other libraries and framework includes
17#include "lldb/Core/PluginManager.h"
18#include "lldb/Core/State.h"
19#include "lldb/Host/Host.h"
20#include "lldb/Symbol/ObjectFile.h"
21#include "lldb/Target/DynamicLoader.h"
22#include "lldb/Target/Target.h"
23
24#include "ProcessFreeBSD.h"
25#include "ProcessPOSIXLog.h"
26#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
Todd Fiala4ceced32014-08-29 17:35:57 +000027#include "Plugins/Process/Utility/FreeBSDSignals.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000028#include "ProcessMonitor.h"
Ed Maste7fd845c2013-12-09 15:51:17 +000029#include "FreeBSDThread.h"
Johnny Chen9ed5b492012-01-05 21:48:15 +000030
Ed Mastefe5a6422015-07-28 15:45:57 +000031// Other libraries and framework includes
32#include "lldb/Breakpoint/BreakpointLocation.h"
33#include "lldb/Breakpoint/Watchpoint.h"
34#include "lldb/Core/Module.h"
35#include "lldb/Core/ModuleSpec.h"
36#include "lldb/Core/PluginManager.h"
37#include "lldb/Core/State.h"
38#include "lldb/Host/FileSpec.h"
39#include "lldb/Host/Host.h"
40#include "lldb/Symbol/ObjectFile.h"
41#include "lldb/Target/DynamicLoader.h"
42#include "lldb/Target/Platform.h"
43#include "lldb/Target/Target.h"
44
45#include "lldb/Host/posix/Fcntl.h"
46
47
Johnny Chen9ed5b492012-01-05 21:48:15 +000048using namespace lldb;
49using namespace lldb_private;
50
Todd Fiala4ceced32014-08-29 17:35:57 +000051namespace
52{
53 UnixSignalsSP&
54 GetFreeBSDSignals ()
55 {
56 static UnixSignalsSP s_freebsd_signals_sp (new FreeBSDSignals ());
57 return s_freebsd_signals_sp;
58 }
59}
60
Johnny Chen9ed5b492012-01-05 21:48:15 +000061//------------------------------------------------------------------------------
62// Static functions.
63
Greg Clayton29d19302012-02-27 18:40:48 +000064lldb::ProcessSP
65ProcessFreeBSD::CreateInstance(Target& target,
66 Listener &listener,
67 const FileSpec *crash_file_path)
Johnny Chen9ed5b492012-01-05 21:48:15 +000068{
Greg Clayton29d19302012-02-27 18:40:48 +000069 lldb::ProcessSP process_sp;
70 if (crash_file_path == NULL)
Ed Mastefe5a6422015-07-28 15:45:57 +000071 process_sp.reset(new ProcessFreeBSD (target, listener, GetFreeBSDSignals()));
Greg Clayton29d19302012-02-27 18:40:48 +000072 return process_sp;
Johnny Chen9ed5b492012-01-05 21:48:15 +000073}
74
75void
76ProcessFreeBSD::Initialize()
77{
Davide Italianoc8d69822015-04-03 04:24:32 +000078 static std::once_flag g_once_flag;
Johnny Chen9ed5b492012-01-05 21:48:15 +000079
Davide Italianoc8d69822015-04-03 04:24:32 +000080 std::call_once(g_once_flag, []() {
Johnny Chen9ed5b492012-01-05 21:48:15 +000081 PluginManager::RegisterPlugin(GetPluginNameStatic(),
82 GetPluginDescriptionStatic(),
83 CreateInstance);
Robert Flack5f4b6c72015-03-11 21:14:22 +000084 ProcessPOSIXLog::Initialize(GetPluginNameStatic());
Davide Italianoc8d69822015-04-03 04:24:32 +000085 });
Johnny Chen9ed5b492012-01-05 21:48:15 +000086}
87
Greg Clayton57abc5d2013-05-10 21:47:16 +000088lldb_private::ConstString
Johnny Chen9ed5b492012-01-05 21:48:15 +000089ProcessFreeBSD::GetPluginNameStatic()
90{
Greg Clayton57abc5d2013-05-10 21:47:16 +000091 static ConstString g_name("freebsd");
92 return g_name;
Johnny Chen9ed5b492012-01-05 21:48:15 +000093}
94
95const char *
96ProcessFreeBSD::GetPluginDescriptionStatic()
97{
98 return "Process plugin for FreeBSD";
99}
100
101//------------------------------------------------------------------------------
102// ProcessInterface protocol.
103
Greg Clayton57abc5d2013-05-10 21:47:16 +0000104lldb_private::ConstString
Johnny Chen9ed5b492012-01-05 21:48:15 +0000105ProcessFreeBSD::GetPluginName()
106{
Greg Clayton57abc5d2013-05-10 21:47:16 +0000107 return GetPluginNameStatic();
Johnny Chen9ed5b492012-01-05 21:48:15 +0000108}
109
110uint32_t
111ProcessFreeBSD::GetPluginVersion()
112{
113 return 1;
114}
115
116void
117ProcessFreeBSD::GetPluginCommandHelp(const char *command, Stream *strm)
118{
119}
120
121Error
122ProcessFreeBSD::ExecutePluginCommand(Args &command, Stream *strm)
123{
124 return Error(1, eErrorTypeGeneric);
125}
126
127Log *
128ProcessFreeBSD::EnablePluginLogging(Stream *strm, Args &command)
129{
130 return NULL;
131}
132
Johnny Chen9ed5b492012-01-05 21:48:15 +0000133void
134ProcessFreeBSD::Terminate()
135{
136}
137
Ed Maste7dcb77d2013-08-30 13:11:30 +0000138Error
139ProcessFreeBSD::DoDetach(bool keep_stopped)
140{
141 Error error;
142 if (keep_stopped)
143 {
144 error.SetErrorString("Detaching with keep_stopped true is not currently supported on FreeBSD.");
145 return error;
146 }
147
148 error = m_monitor->Detach(GetID());
149
150 if (error.Success())
151 SetPrivateState(eStateDetached);
152
153 return error;
154}
155
Ed Maste7fd845c2013-12-09 15:51:17 +0000156Error
157ProcessFreeBSD::DoResume()
158{
159 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
160
Ed Maste7fd845c2013-12-09 15:51:17 +0000161 SetPrivateState(eStateRunning);
162
163 Mutex::Locker lock(m_thread_list.GetMutex());
164 bool do_step = false;
165
166 for (tid_collection::const_iterator t_pos = m_run_tids.begin(), t_end = m_run_tids.end(); t_pos != t_end; ++t_pos)
167 {
168 m_monitor->ThreadSuspend(*t_pos, false);
169 }
170 for (tid_collection::const_iterator t_pos = m_step_tids.begin(), t_end = m_step_tids.end(); t_pos != t_end; ++t_pos)
171 {
172 m_monitor->ThreadSuspend(*t_pos, false);
173 do_step = true;
174 }
175 for (tid_collection::const_iterator t_pos = m_suspend_tids.begin(), t_end = m_suspend_tids.end(); t_pos != t_end; ++t_pos)
176 {
177 m_monitor->ThreadSuspend(*t_pos, true);
178 // XXX Cannot PT_CONTINUE properly with suspended threads.
179 do_step = true;
180 }
181
182 if (log)
Joerg Sonnenberger420708a2014-05-02 19:00:27 +0000183 log->Printf("process %" PRIu64 " resuming (%s)", GetID(), do_step ? "step" : "continue");
Ed Maste7fd845c2013-12-09 15:51:17 +0000184 if (do_step)
Ed Mastec71f60f2014-02-28 17:13:39 +0000185 m_monitor->SingleStep(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000186 else
Ed Mastec71f60f2014-02-28 17:13:39 +0000187 m_monitor->Resume(GetID(), m_resume_signo);
Ed Maste7fd845c2013-12-09 15:51:17 +0000188
189 return Error();
190}
191
Greg Claytonc3c0b0e2012-04-12 19:04:34 +0000192bool
Johnny Chen9ed5b492012-01-05 21:48:15 +0000193ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
194{
Ed Maste7fd845c2013-12-09 15:51:17 +0000195 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
196 if (log)
197 log->Printf("ProcessFreeBSD::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
Daniel Maleae0f8f572013-08-26 23:57:52 +0000198
Ed Maste7fd845c2013-12-09 15:51:17 +0000199 std::vector<lldb::pid_t> tds;
200 if (!GetMonitor().GetCurrentThreadIDs(tds))
201 {
202 return false;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000203 }
204
Ed Maste7fd845c2013-12-09 15:51:17 +0000205 ThreadList old_thread_list_copy(old_thread_list);
206 for (size_t i = 0; i < tds.size(); ++i)
207 {
208 tid_t tid = tds[i];
209 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByID(tid, false));
210 if (!thread_sp)
211 {
212 thread_sp.reset(new FreeBSDThread(*this, tid));
213 if (log)
214 log->Printf("ProcessFreeBSD::%s new tid = %" PRIu64, __FUNCTION__, tid);
215 }
216 else
217 {
218 if (log)
219 log->Printf("ProcessFreeBSD::%s existing tid = %" PRIu64, __FUNCTION__, tid);
220 }
221 new_thread_list.AddThread(thread_sp);
222 }
223 for (size_t i = 0; i < old_thread_list_copy.GetSize(false); ++i)
224 {
225 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
226 if (old_thread_sp)
227 {
228 if (log)
229 log->Printf("ProcessFreeBSD::%s remove tid", __FUNCTION__);
230 }
231 }
Daniel Maleae0f8f572013-08-26 23:57:52 +0000232
Ed Maste7fd845c2013-12-09 15:51:17 +0000233 return true;
Johnny Chen9ed5b492012-01-05 21:48:15 +0000234}
Ed Maste7fd845c2013-12-09 15:51:17 +0000235
236Error
237ProcessFreeBSD::WillResume()
238{
Ed Mastec71f60f2014-02-28 17:13:39 +0000239 m_resume_signo = 0;
Ed Maste7fd845c2013-12-09 15:51:17 +0000240 m_suspend_tids.clear();
241 m_run_tids.clear();
242 m_step_tids.clear();
Ed Mastefe5a6422015-07-28 15:45:57 +0000243 return Process::WillResume();
Ed Maste7fd845c2013-12-09 15:51:17 +0000244}
245
246void
247ProcessFreeBSD::SendMessage(const ProcessMessage &message)
248{
249 Mutex::Locker lock(m_message_mutex);
250
251 switch (message.GetKind())
252 {
253 case ProcessMessage::eInvalidMessage:
254 return;
255
256 case ProcessMessage::eAttachMessage:
257 SetPrivateState(eStateStopped);
258 return;
259
260 case ProcessMessage::eLimboMessage:
261 case ProcessMessage::eExitMessage:
Todd Fiala7b0917a2014-09-15 20:07:33 +0000262 SetExitStatus(message.GetExitStatus(), NULL);
Ed Maste7fd845c2013-12-09 15:51:17 +0000263 break;
264
265 case ProcessMessage::eSignalMessage:
266 case ProcessMessage::eSignalDeliveredMessage:
267 case ProcessMessage::eBreakpointMessage:
268 case ProcessMessage::eTraceMessage:
269 case ProcessMessage::eWatchpointMessage:
270 case ProcessMessage::eCrashMessage:
271 SetPrivateState(eStateStopped);
272 break;
273
274 case ProcessMessage::eNewThreadMessage:
Ed Maste63c9fa02015-07-28 16:57:36 +0000275 llvm_unreachable("eNewThreadMessage unexpected on FreeBSD");
Ed Maste7fd845c2013-12-09 15:51:17 +0000276 break;
277
278 case ProcessMessage::eExecMessage:
279 SetPrivateState(eStateStopped);
280 break;
281 }
282
283 m_message_queue.push(message);
284}
Ed Mastefe5a6422015-07-28 15:45:57 +0000285
286//------------------------------------------------------------------------------
287// Constructors and destructors.
288
289ProcessFreeBSD::ProcessFreeBSD(Target& target, Listener &listener, UnixSignalsSP &unix_signals_sp)
290 : Process(target, listener, unix_signals_sp),
291 m_byte_order(lldb::endian::InlHostByteOrder()),
292 m_monitor(NULL),
293 m_module(NULL),
294 m_message_mutex (Mutex::eMutexTypeRecursive),
295 m_exit_now(false),
296 m_seen_initial_stop(),
297 m_resume_signo(0)
298{
299 // FIXME: Putting this code in the ctor and saving the byte order in a
300 // member variable is a hack to avoid const qual issues in GetByteOrder.
301 lldb::ModuleSP module = GetTarget().GetExecutableModule();
302 if (module && module->GetObjectFile())
303 m_byte_order = module->GetObjectFile()->GetByteOrder();
304}
305
306ProcessFreeBSD::~ProcessFreeBSD()
307{
308 delete m_monitor;
309}
310
311//------------------------------------------------------------------------------
312// Process protocol.
313void
314ProcessFreeBSD::Finalize()
315{
316 Process::Finalize();
317
318 if (m_monitor)
319 m_monitor->StopMonitor();
320}
321
322bool
323ProcessFreeBSD::CanDebug(Target &target, bool plugin_specified_by_name)
324{
325 // For now we are just making sure the file exists for a given module
326 ModuleSP exe_module_sp(target.GetExecutableModule());
327 if (exe_module_sp.get())
328 return exe_module_sp->GetFileSpec().Exists();
329 // If there is no executable module, we return true since we might be preparing to attach.
330 return true;
331}
332
333Error
334ProcessFreeBSD::DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info)
335{
336 Error error;
337 assert(m_monitor == NULL);
338
339 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
340 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
341 log->Printf ("ProcessFreeBSD::%s(pid = %" PRIi64 ")", __FUNCTION__, GetID());
342
343 m_monitor = new ProcessMonitor(this, pid, error);
344
345 if (!error.Success())
346 return error;
347
348 PlatformSP platform_sp (m_target.GetPlatform ());
349 assert (platform_sp.get());
350 if (!platform_sp)
351 return error; // FIXME: Detatch?
352
353 // Find out what we can about this process
354 ProcessInstanceInfo process_info;
355 platform_sp->GetProcessInfo (pid, process_info);
356
357 // Resolve the executable module
358 ModuleSP exe_module_sp;
359 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
360 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), m_target.GetArchitecture());
361 error = platform_sp->ResolveExecutable(exe_module_spec,
362 exe_module_sp,
363 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
364 if (!error.Success())
365 return error;
366
367 // Fix the target architecture if necessary
368 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
369 if (module_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(module_arch))
370 m_target.SetArchitecture(module_arch);
371
372 // Initialize the target module list
373 m_target.SetExecutableModule (exe_module_sp, true);
374
375 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
376
377 SetID(pid);
378
379 return error;
380}
381
382Error
383ProcessFreeBSD::WillLaunch(Module* module)
384{
385 Error error;
386 return error;
387}
388
389FileSpec
390ProcessFreeBSD::GetFileSpec(const lldb_private::FileAction *file_action,
391 const FileSpec &default_file_spec,
392 const FileSpec &dbg_pts_file_spec)
393{
394 FileSpec file_spec{};
395
396 if (file_action && file_action->GetAction() == FileAction::eFileActionOpen)
397 {
398 file_spec = file_action->GetFileSpec();
399 // By default the stdio paths passed in will be pseudo-terminal
400 // (/dev/pts). If so, convert to using a different default path
401 // instead to redirect I/O to the debugger console. This should
402 // also handle user overrides to /dev/null or a different file.
403 if (!file_spec || file_spec == dbg_pts_file_spec)
404 file_spec = default_file_spec;
405 }
406 return file_spec;
407}
408
409Error
410ProcessFreeBSD::DoLaunch (Module *module,
411 ProcessLaunchInfo &launch_info)
412{
413 Error error;
414 assert(m_monitor == NULL);
415
416 FileSpec working_dir = launch_info.GetWorkingDirectory();
417 if (working_dir &&
418 (!working_dir.ResolvePath() ||
419 working_dir.GetFileType() != FileSpec::eFileTypeDirectory))
420 {
421 error.SetErrorStringWithFormat("No such file or directory: %s",
422 working_dir.GetCString());
423 return error;
424 }
425
426 SetPrivateState(eStateLaunching);
427
428 const lldb_private::FileAction *file_action;
429
430 // Default of empty will mean to use existing open file descriptors
431 FileSpec stdin_file_spec{};
432 FileSpec stdout_file_spec{};
433 FileSpec stderr_file_spec{};
434
435 const FileSpec dbg_pts_file_spec{launch_info.GetPTY().GetSlaveName(NULL,0), false};
436
437 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
438 stdin_file_spec = GetFileSpec(file_action, stdin_file_spec, dbg_pts_file_spec);
439
440 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
441 stdout_file_spec = GetFileSpec(file_action, stdout_file_spec, dbg_pts_file_spec);
442
443 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
444 stderr_file_spec = GetFileSpec(file_action, stderr_file_spec, dbg_pts_file_spec);
445
446 m_monitor = new ProcessMonitor(this,
447 module,
448 launch_info.GetArguments().GetConstArgumentVector(),
449 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
450 stdin_file_spec,
451 stdout_file_spec,
452 stderr_file_spec,
453 working_dir,
454 launch_info,
455 error);
456
457 m_module = module;
458
459 if (!error.Success())
460 return error;
461
462 int terminal = m_monitor->GetTerminalFD();
463 if (terminal >= 0) {
464 // The reader thread will close the file descriptor when done, so we pass it a copy.
465 int stdio = fcntl(terminal, F_DUPFD_CLOEXEC, 0);
466 if (stdio == -1) {
467 error.SetErrorToErrno();
468 return error;
469 }
470 SetSTDIOFileDescriptor(stdio);
471 }
472
473 SetID(m_monitor->GetPID());
474 return error;
475}
476
477void
478ProcessFreeBSD::DidLaunch()
479{
480}
481
482addr_t
483ProcessFreeBSD::GetImageInfoAddress()
484{
485 Target *target = &GetTarget();
486 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
487 Address addr = obj_file->GetImageInfoAddress(target);
488
489 if (addr.IsValid())
490 return addr.GetLoadAddress(target);
491 return LLDB_INVALID_ADDRESS;
492}
493
494Error
495ProcessFreeBSD::DoHalt(bool &caused_stop)
496{
497 Error error;
498
499 if (IsStopped())
500 {
501 caused_stop = false;
502 }
503 else if (kill(GetID(), SIGSTOP))
504 {
505 caused_stop = false;
506 error.SetErrorToErrno();
507 }
508 else
509 {
510 caused_stop = true;
511 }
512 return error;
513}
514
515Error
516ProcessFreeBSD::DoSignal(int signal)
517{
518 Error error;
519
520 if (kill(GetID(), signal))
521 error.SetErrorToErrno();
522
523 return error;
524}
525
526Error
527ProcessFreeBSD::DoDestroy()
528{
529 Error error;
530
531 if (!HasExited())
532 {
533 assert(m_monitor);
534 m_exit_now = true;
535 if (GetID() == LLDB_INVALID_PROCESS_ID)
536 {
537 error.SetErrorString("invalid process id");
538 return error;
539 }
540 if (!m_monitor->Kill())
541 {
542 error.SetErrorToErrno();
543 return error;
544 }
545
546 SetPrivateState(eStateExited);
547 }
548
549 return error;
550}
551
552void
553ProcessFreeBSD::DoDidExec()
554{
555 Target *target = &GetTarget();
556 if (target)
557 {
558 PlatformSP platform_sp (target->GetPlatform());
559 assert (platform_sp.get());
560 if (platform_sp)
561 {
562 ProcessInstanceInfo process_info;
563 platform_sp->GetProcessInfo(GetID(), process_info);
564 ModuleSP exe_module_sp;
565 ModuleSpec exe_module_spec(process_info.GetExecutableFile(), target->GetArchitecture());
566 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
567 Error error = platform_sp->ResolveExecutable(exe_module_spec,
568 exe_module_sp,
569 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
570 if (!error.Success())
571 return;
572 target->SetExecutableModule(exe_module_sp, true);
573 }
574 }
575}
576
577bool
578ProcessFreeBSD::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid)
579{
580 bool added_to_set = false;
581 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
582 if (it == m_seen_initial_stop.end())
583 {
584 m_seen_initial_stop.insert(stop_tid);
585 added_to_set = true;
586 }
587 return added_to_set;
588}
589
590bool
591ProcessFreeBSD::WaitingForInitialStop(lldb::tid_t stop_tid)
592{
593 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
594}
595
596FreeBSDThread *
597ProcessFreeBSD::CreateNewFreeBSDThread(lldb_private::Process &process, lldb::tid_t tid)
598{
599 return new FreeBSDThread(process, tid);
600}
601
602void
603ProcessFreeBSD::RefreshStateAfterStop()
604{
605 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
606 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
607 log->Printf ("ProcessFreeBSD::%s(), message_queue size = %d", __FUNCTION__, (int)m_message_queue.size());
608
609 Mutex::Locker lock(m_message_mutex);
610
611 // This method used to only handle one message. Changing it to loop allows
612 // it to handle the case where we hit a breakpoint while handling a different
613 // breakpoint.
614 while (!m_message_queue.empty())
615 {
616 ProcessMessage &message = m_message_queue.front();
617
618 // Resolve the thread this message corresponds to and pass it along.
619 lldb::tid_t tid = message.GetTID();
620 if (log)
621 log->Printf ("ProcessFreeBSD::%s(), message_queue size = %d, pid = %" PRIi64, __FUNCTION__, (int)m_message_queue.size(), tid);
622
Ed Mastefe5a6422015-07-28 15:45:57 +0000623 m_thread_list.RefreshStateAfterStop();
624
625 FreeBSDThread *thread = static_cast<FreeBSDThread*>(
626 GetThreadList().FindThreadByID(tid, false).get());
627 if (thread)
628 thread->Notify(message);
629
630 if (message.GetKind() == ProcessMessage::eExitMessage)
631 {
632 // FIXME: We should tell the user about this, but the limbo message is probably better for that.
633 if (log)
634 log->Printf ("ProcessFreeBSD::%s() removing thread, tid = %" PRIi64, __FUNCTION__, tid);
635
636 Mutex::Locker lock(m_thread_list.GetMutex());
637
638 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
639 thread_sp.reset();
640 m_seen_initial_stop.erase(tid);
641 }
642
643 m_message_queue.pop();
644 }
645}
646
647bool
648ProcessFreeBSD::IsAlive()
649{
650 StateType state = GetPrivateState();
651 return state != eStateDetached
652 && state != eStateExited
653 && state != eStateInvalid
654 && state != eStateUnloaded;
655}
656
657size_t
658ProcessFreeBSD::DoReadMemory(addr_t vm_addr,
659 void *buf, size_t size, Error &error)
660{
661 assert(m_monitor);
662 return m_monitor->ReadMemory(vm_addr, buf, size, error);
663}
664
665size_t
666ProcessFreeBSD::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size,
667 Error &error)
668{
669 assert(m_monitor);
670 return m_monitor->WriteMemory(vm_addr, buf, size, error);
671}
672
673addr_t
674ProcessFreeBSD::DoAllocateMemory(size_t size, uint32_t permissions,
675 Error &error)
676{
677 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
678
679 unsigned prot = 0;
680 if (permissions & lldb::ePermissionsReadable)
681 prot |= eMmapProtRead;
682 if (permissions & lldb::ePermissionsWritable)
683 prot |= eMmapProtWrite;
684 if (permissions & lldb::ePermissionsExecutable)
685 prot |= eMmapProtExec;
686
687 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
688 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
689 m_addr_to_mmap_size[allocated_addr] = size;
690 error.Clear();
691 } else {
692 allocated_addr = LLDB_INVALID_ADDRESS;
693 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
694 }
695
696 return allocated_addr;
697}
698
699Error
700ProcessFreeBSD::DoDeallocateMemory(lldb::addr_t addr)
701{
702 Error error;
703 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
704 if (pos != m_addr_to_mmap_size.end() &&
705 InferiorCallMunmap(this, addr, pos->second))
706 m_addr_to_mmap_size.erase (pos);
707 else
708 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
709
710 return error;
711}
712
713size_t
714ProcessFreeBSD::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site)
715{
716 static const uint8_t g_aarch64_opcode[] = { 0x00, 0x00, 0x20, 0xD4 };
717 static const uint8_t g_i386_opcode[] = { 0xCC };
718
719 ArchSpec arch = GetTarget().GetArchitecture();
720 const uint8_t *opcode = NULL;
721 size_t opcode_size = 0;
722
723 switch (arch.GetMachine())
724 {
725 default:
726 assert(false && "CPU type not supported!");
727 break;
728
729 case llvm::Triple::arm:
730 {
731 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
732 // but the linux kernel does otherwise.
733 static const uint8_t g_arm_breakpoint_opcode[] = { 0xf0, 0x01, 0xf0, 0xe7 };
734 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x01, 0xde };
735
736 lldb::BreakpointLocationSP bp_loc_sp (bp_site->GetOwnerAtIndex (0));
737 AddressClass addr_class = eAddressClassUnknown;
738
739 if (bp_loc_sp)
740 addr_class = bp_loc_sp->GetAddress ().GetAddressClass ();
741
742 if (addr_class == eAddressClassCodeAlternateISA
743 || (addr_class == eAddressClassUnknown
744 && bp_loc_sp->GetAddress().GetOffset() & 1))
745 {
746 opcode = g_thumb_breakpoint_opcode;
747 opcode_size = sizeof(g_thumb_breakpoint_opcode);
748 }
749 else
750 {
751 opcode = g_arm_breakpoint_opcode;
752 opcode_size = sizeof(g_arm_breakpoint_opcode);
753 }
754 }
755 break;
756 case llvm::Triple::aarch64:
757 opcode = g_aarch64_opcode;
758 opcode_size = sizeof(g_aarch64_opcode);
759 break;
760
761 case llvm::Triple::x86:
762 case llvm::Triple::x86_64:
763 opcode = g_i386_opcode;
764 opcode_size = sizeof(g_i386_opcode);
765 break;
766 }
767
768 bp_site->SetTrapOpcode(opcode, opcode_size);
769 return opcode_size;
770}
771
772Error
773ProcessFreeBSD::EnableBreakpointSite(BreakpointSite *bp_site)
774{
775 return EnableSoftwareBreakpoint(bp_site);
776}
777
778Error
779ProcessFreeBSD::DisableBreakpointSite(BreakpointSite *bp_site)
780{
781 return DisableSoftwareBreakpoint(bp_site);
782}
783
784Error
785ProcessFreeBSD::EnableWatchpoint(Watchpoint *wp, bool notify)
786{
787 Error error;
788 if (wp)
789 {
790 user_id_t watchID = wp->GetID();
791 addr_t addr = wp->GetLoadAddress();
792 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
793 if (log)
794 log->Printf ("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64 ")",
795 watchID);
796 if (wp->IsEnabled())
797 {
798 if (log)
799 log->Printf("ProcessFreeBSD::EnableWatchpoint(watchID = %" PRIu64
800 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
801 watchID, (uint64_t)addr);
802 return error;
803 }
804
805 // Try to find a vacant watchpoint slot in the inferiors' main thread
806 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
807 Mutex::Locker lock(m_thread_list.GetMutex());
808 FreeBSDThread *thread = static_cast<FreeBSDThread*>(
809 m_thread_list.GetThreadAtIndex(0, false).get());
810
811 if (thread)
812 wp_hw_index = thread->FindVacantWatchpointIndex();
813
814 if (wp_hw_index == LLDB_INVALID_INDEX32)
815 {
816 error.SetErrorString("Setting hardware watchpoint failed.");
817 }
818 else
819 {
820 wp->SetHardwareIndex(wp_hw_index);
821 bool wp_enabled = true;
822 uint32_t thread_count = m_thread_list.GetSize(false);
823 for (uint32_t i = 0; i < thread_count; ++i)
824 {
825 thread = static_cast<FreeBSDThread*>(
826 m_thread_list.GetThreadAtIndex(i, false).get());
827 if (thread)
828 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
829 else
830 wp_enabled = false;
831 }
832 if (wp_enabled)
833 {
834 wp->SetEnabled(true, notify);
835 return error;
836 }
837 else
838 {
839 // Watchpoint enabling failed on at least one
840 // of the threads so roll back all of them
841 DisableWatchpoint(wp, false);
842 error.SetErrorString("Setting hardware watchpoint failed");
843 }
844 }
845 }
846 else
847 error.SetErrorString("Watchpoint argument was NULL.");
848 return error;
849}
850
851Error
852ProcessFreeBSD::DisableWatchpoint(Watchpoint *wp, bool notify)
853{
854 Error error;
855 if (wp)
856 {
857 user_id_t watchID = wp->GetID();
858 addr_t addr = wp->GetLoadAddress();
859 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
860 if (log)
861 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64 ")",
862 watchID);
863 if (!wp->IsEnabled())
864 {
865 if (log)
866 log->Printf("ProcessFreeBSD::DisableWatchpoint(watchID = %" PRIu64
867 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
868 watchID, (uint64_t)addr);
869 // This is needed (for now) to keep watchpoints disabled correctly
870 wp->SetEnabled(false, notify);
871 return error;
872 }
873
874 if (wp->IsHardware())
875 {
876 bool wp_disabled = true;
877 Mutex::Locker lock(m_thread_list.GetMutex());
878 uint32_t thread_count = m_thread_list.GetSize(false);
879 for (uint32_t i = 0; i < thread_count; ++i)
880 {
881 FreeBSDThread *thread = static_cast<FreeBSDThread*>(
882 m_thread_list.GetThreadAtIndex(i, false).get());
883 if (thread)
884 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
885 else
886 wp_disabled = false;
887 }
888 if (wp_disabled)
889 {
890 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
891 wp->SetEnabled(false, notify);
892 return error;
893 }
894 else
895 error.SetErrorString("Disabling hardware watchpoint failed");
896 }
897 }
898 else
899 error.SetErrorString("Watchpoint argument was NULL.");
900 return error;
901}
902
903Error
904ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num)
905{
906 Error error;
907 Mutex::Locker lock(m_thread_list.GetMutex());
908 FreeBSDThread *thread = static_cast<FreeBSDThread*>(
909 m_thread_list.GetThreadAtIndex(0, false).get());
910 if (thread)
911 num = thread->NumSupportedHardwareWatchpoints();
912 else
913 error.SetErrorString("Process does not exist.");
914 return error;
915}
916
917Error
918ProcessFreeBSD::GetWatchpointSupportInfo(uint32_t &num, bool &after)
919{
920 Error error = GetWatchpointSupportInfo(num);
921 // Watchpoints trigger and halt the inferior after
922 // the corresponding instruction has been executed.
923 after = true;
924 return error;
925}
926
927uint32_t
928ProcessFreeBSD::UpdateThreadListIfNeeded()
929{
930 Mutex::Locker lock(m_thread_list.GetMutex());
931 // Do not allow recursive updates.
932 return m_thread_list.GetSize(false);
933}
934
935#if 0
936bool
937ProcessFreeBSD::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
938{
939 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
940 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
941 log->Printf ("ProcessFreeBSD::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
942
943 bool has_updated = false;
944 // Update the process thread list with this new thread.
945 // FIXME: We should be using tid, not pid.
946 assert(m_monitor);
947 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
948 if (!thread_sp) {
949 thread_sp.reset(CreateNewFreeBSDThread(*this, GetID()));
950 has_updated = true;
951 }
952
953 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
954 log->Printf ("ProcessFreeBSD::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
955 new_thread_list.AddThread(thread_sp);
956
957 return has_updated; // the list has been updated
958}
959#endif
960
961ByteOrder
962ProcessFreeBSD::GetByteOrder() const
963{
964 // FIXME: We should be able to extract this value directly. See comment in
965 // ProcessFreeBSD().
966 return m_byte_order;
967}
968
969size_t
970ProcessFreeBSD::PutSTDIN(const char *buf, size_t len, Error &error)
971{
972 ssize_t status;
973 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0)
974 {
975 error.SetErrorToErrno();
976 return 0;
977 }
978 return status;
979}
980
981//------------------------------------------------------------------------------
982// Utility functions.
983
984bool
985ProcessFreeBSD::HasExited()
986{
987 switch (GetPrivateState())
988 {
989 default:
990 break;
991
992 case eStateDetached:
993 case eStateExited:
994 return true;
995 }
996
997 return false;
998}
999
1000bool
1001ProcessFreeBSD::IsStopped()
1002{
1003 switch (GetPrivateState())
1004 {
1005 default:
1006 break;
1007
1008 case eStateStopped:
1009 case eStateCrashed:
1010 case eStateSuspended:
1011 return true;
1012 }
1013
1014 return false;
1015}
1016
1017bool
1018ProcessFreeBSD::IsAThreadRunning()
1019{
1020 bool is_running = false;
1021 Mutex::Locker lock(m_thread_list.GetMutex());
1022 uint32_t thread_count = m_thread_list.GetSize(false);
1023 for (uint32_t i = 0; i < thread_count; ++i)
1024 {
1025 FreeBSDThread *thread = static_cast<FreeBSDThread*>(
1026 m_thread_list.GetThreadAtIndex(i, false).get());
1027 StateType thread_state = thread->GetState();
1028 if (thread_state == eStateRunning || thread_state == eStateStepping)
1029 {
1030 is_running = true;
1031 break;
1032 }
1033 }
1034 return is_running;
1035}
1036
1037const DataBufferSP
1038ProcessFreeBSD::GetAuxvData ()
1039{
1040 // If we're the local platform, we can ask the host for auxv data.
1041 PlatformSP platform_sp = m_target.GetPlatform ();
1042 if (platform_sp && platform_sp->IsHost ())
1043 return lldb_private::Host::GetAuxvData(this);
1044
1045 // Somewhat unexpected - the process is not running locally or we don't have a platform.
1046 assert (false && "no platform or not the host - how did we get here with ProcessFreeBSD?");
1047 return DataBufferSP ();
1048}