1 //===-- ProcessPOSIX.cpp ----------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
16 // Other libraries and framework includes
17 #include "lldb/Breakpoint/Watchpoint.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/State.h"
21 #include "lldb/Host/FileSpec.h"
22 #include "lldb/Host/Host.h"
23 #include "lldb/Symbol/ObjectFile.h"
24 #include "lldb/Target/DynamicLoader.h"
25 #include "lldb/Target/Platform.h"
26 #include "lldb/Target/Target.h"
28 #include "ProcessPOSIX.h"
29 #include "ProcessPOSIXLog.h"
30 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
31 #include "ProcessMonitor.h"
32 #include "POSIXThread.h"
35 using namespace lldb_private;
37 //------------------------------------------------------------------------------
41 ProcessPOSIX::CreateInstance(Target& target, Listener &listener)
43 return new ProcessPOSIX(target, listener);
48 ProcessPOSIX::Initialize()
50 static bool g_initialized = false;
55 PluginManager::RegisterPlugin(GetPluginNameStatic(),
56 GetPluginDescriptionStatic(),
59 Log::Callbacks log_callbacks = {
60 ProcessPOSIXLog::DisableLog,
61 ProcessPOSIXLog::EnableLog,
62 ProcessPOSIXLog::ListLogCategories
65 Log::RegisterLogChannel (ProcessPOSIX::GetPluginNameStatic(), log_callbacks);
70 //------------------------------------------------------------------------------
71 // Constructors and destructors.
73 ProcessPOSIX::ProcessPOSIX(Target& target, Listener &listener)
74 : Process(target, listener),
75 m_byte_order(lldb::endian::InlHostByteOrder()),
78 m_message_mutex (Mutex::eMutexTypeRecursive),
82 // FIXME: Putting this code in the ctor and saving the byte order in a
83 // member variable is a hack to avoid const qual issues in GetByteOrder.
84 lldb::ModuleSP module = GetTarget().GetExecutableModule();
85 if (module && module->GetObjectFile())
86 m_byte_order = module->GetObjectFile()->GetByteOrder();
89 ProcessPOSIX::~ProcessPOSIX()
94 //------------------------------------------------------------------------------
97 ProcessPOSIX::Finalize()
102 m_monitor->StopMonitor();
106 ProcessPOSIX::CanDebug(Target &target, bool plugin_specified_by_name)
108 // For now we are just making sure the file exists for a given module
109 ModuleSP exe_module_sp(target.GetExecutableModule());
110 if (exe_module_sp.get())
111 return exe_module_sp->GetFileSpec().Exists();
112 // If there is no executable module, we return true since we might be preparing to attach.
117 ProcessPOSIX::DoAttachToProcessWithID(lldb::pid_t pid)
120 assert(m_monitor == NULL);
122 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
123 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
124 log->Printf ("ProcessPOSIX::%s(pid = %" PRIi64 ")", __FUNCTION__, GetID());
126 m_monitor = new ProcessMonitor(this, pid, error);
128 if (!error.Success())
131 PlatformSP platform_sp (m_target.GetPlatform ());
132 assert (platform_sp.get());
134 return error; // FIXME: Detatch?
136 // Find out what we can about this process
137 ProcessInstanceInfo process_info;
138 platform_sp->GetProcessInfo (pid, process_info);
140 // Resolve the executable module
141 ModuleSP exe_module_sp;
142 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
143 error = platform_sp->ResolveExecutable(process_info.GetExecutableFile(),
144 m_target.GetArchitecture(),
146 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
147 if (!error.Success())
150 // Fix the target architecture if necessary
151 const ArchSpec &module_arch = exe_module_sp->GetArchitecture();
152 if (module_arch.IsValid() && !m_target.GetArchitecture().IsExactMatch(module_arch))
153 m_target.SetArchitecture(module_arch);
155 // Initialize the target module list
156 m_target.SetExecutableModule (exe_module_sp, true);
158 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
166 ProcessPOSIX::DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info)
168 return DoAttachToProcessWithID(pid);
172 ProcessPOSIX::WillLaunch(Module* module)
179 ProcessPOSIX::GetFilePath(
180 const lldb_private::ProcessLaunchInfo::FileAction *file_action,
181 const char *default_path)
183 const char *pts_name = "/dev/pts/";
184 const char *path = NULL;
188 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen)
189 path = file_action->GetPath();
190 // By default the stdio paths passed in will be pseudo-terminal
191 // (/dev/pts). If so, convert to using a different default path
192 // instead to redirect I/O to the debugger console. This should
193 // also handle user overrides to /dev/null or a different file.
194 if (::strncmp(path, pts_name, ::strlen(pts_name)) == 0)
202 ProcessPOSIX::DoLaunch (Module *module,
203 const ProcessLaunchInfo &launch_info)
206 assert(m_monitor == NULL);
208 const char* working_dir = launch_info.GetWorkingDirectory();
210 FileSpec WorkingDir(working_dir, true);
211 if (!WorkingDir || WorkingDir.GetFileType() != FileSpec::eFileTypeDirectory)
213 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
218 SetPrivateState(eStateLaunching);
220 const lldb_private::ProcessLaunchInfo::FileAction *file_action;
222 // Default of NULL will mean to use existing open file descriptors
223 const char *stdin_path = NULL;
224 const char *stdout_path = NULL;
225 const char *stderr_path = NULL;
227 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
228 stdin_path = GetFilePath(file_action, stdin_path);
230 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
231 stdout_path = GetFilePath(file_action, stdout_path);
233 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
234 stderr_path = GetFilePath(file_action, stderr_path);
236 m_monitor = new ProcessMonitor (this,
238 launch_info.GetArguments().GetConstArgumentVector(),
239 launch_info.GetEnvironmentEntries().GetConstArgumentVector(),
248 if (!error.Success())
251 SetSTDIOFileDescriptor(m_monitor->GetTerminalFD());
253 SetID(m_monitor->GetPID());
258 ProcessPOSIX::DidLaunch()
263 ProcessPOSIX::DoResume()
265 StateType state = GetPrivateState();
267 assert(state == eStateStopped);
269 SetPrivateState(eStateRunning);
271 bool did_resume = false;
273 Mutex::Locker lock(m_thread_list.GetMutex());
275 uint32_t thread_count = m_thread_list.GetSize(false);
276 for (uint32_t i = 0; i < thread_count; ++i)
278 POSIXThread *thread = static_cast<POSIXThread*>(
279 m_thread_list.GetThreadAtIndex(i, false).get());
280 did_resume = thread->Resume() || did_resume;
282 assert(did_resume && "Process resume failed!");
288 ProcessPOSIX::GetImageInfoAddress()
290 Target *target = &GetTarget();
291 ObjectFile *obj_file = target->GetExecutableModule()->GetObjectFile();
292 Address addr = obj_file->GetImageInfoAddress(target);
295 return addr.GetLoadAddress(target);
296 return LLDB_INVALID_ADDRESS;
300 ProcessPOSIX::DoHalt(bool &caused_stop)
308 else if (kill(GetID(), SIGSTOP))
311 error.SetErrorToErrno();
321 ProcessPOSIX::DoSignal(int signal)
325 if (kill(GetID(), signal))
326 error.SetErrorToErrno();
332 ProcessPOSIX::DoDestroy()
338 // Drive the exit event to completion (do not keep the inferior in
342 if ((m_monitor == NULL || kill(m_monitor->GetPID(), SIGKILL)) && error.Success())
344 error.SetErrorToErrno();
348 SetPrivateState(eStateExited);
355 ProcessPOSIX::DoDidExec()
357 Target *target = &GetTarget();
360 PlatformSP platform_sp (target->GetPlatform());
361 assert (platform_sp.get());
364 ProcessInstanceInfo process_info;
365 platform_sp->GetProcessInfo(GetID(), process_info);
366 ModuleSP exe_module_sp;
367 FileSpecList executable_search_paths (Target::GetDefaultExecutableSearchPaths());
368 Error error = platform_sp->ResolveExecutable(process_info.GetExecutableFile(),
369 target->GetArchitecture(),
371 executable_search_paths.GetSize() ? &executable_search_paths : NULL);
372 if (!error.Success())
374 target->SetExecutableModule(exe_module_sp, true);
380 ProcessPOSIX::SendMessage(const ProcessMessage &message)
382 Mutex::Locker lock(m_message_mutex);
384 Mutex::Locker thread_lock(m_thread_list.GetMutex());
386 POSIXThread *thread = static_cast<POSIXThread*>(
387 m_thread_list.FindThreadByID(message.GetTID(), false).get());
389 switch (message.GetKind())
391 case ProcessMessage::eInvalidMessage:
394 case ProcessMessage::eAttachMessage:
395 SetPrivateState(eStateStopped);
398 case ProcessMessage::eLimboMessage:
400 thread->SetState(eStateStopped);
401 if (message.GetTID() == GetID())
403 m_exit_status = message.GetExitStatus();
406 SetPrivateState(eStateExited);
407 m_monitor->Detach(GetID());
411 StopAllThreads(message.GetTID());
412 SetPrivateState(eStateStopped);
417 StopAllThreads(message.GetTID());
418 SetPrivateState(eStateStopped);
422 case ProcessMessage::eExitMessage:
424 thread->SetState(eStateExited);
425 // FIXME: I'm not sure we need to do this.
426 if (message.GetTID() == GetID())
428 m_exit_status = message.GetExitStatus();
429 SetExitStatus(m_exit_status, NULL);
431 else if (!IsAThreadRunning())
432 SetPrivateState(eStateStopped);
435 case ProcessMessage::eSignalMessage:
436 case ProcessMessage::eSignalDeliveredMessage:
437 if (message.GetSignal() == SIGSTOP &&
438 AddThreadForInitialStopIfNeeded(message.GetTID()))
440 // Intentional fall-through
442 case ProcessMessage::eBreakpointMessage:
443 case ProcessMessage::eTraceMessage:
444 case ProcessMessage::eWatchpointMessage:
445 case ProcessMessage::eCrashMessage:
447 thread->SetState(eStateStopped);
448 StopAllThreads(message.GetTID());
449 SetPrivateState(eStateStopped);
452 case ProcessMessage::eNewThreadMessage:
454 lldb::tid_t new_tid = message.GetChildTID();
455 if (WaitingForInitialStop(new_tid))
457 m_monitor->WaitForInitialTIDStop(new_tid);
460 thread->SetState(eStateStopped);
461 StopAllThreads(message.GetTID());
462 SetPrivateState(eStateStopped);
466 case ProcessMessage::eExecMessage:
469 thread->SetState(eStateStopped);
470 StopAllThreads(message.GetTID());
471 SetPrivateState(eStateStopped);
477 m_message_queue.push(message);
481 ProcessPOSIX::StopAllThreads(lldb::tid_t stop_tid)
483 // FIXME: Will this work the same way on FreeBSD and Linux?
487 ProcessPOSIX::AddThreadForInitialStopIfNeeded(lldb::tid_t stop_tid)
489 bool added_to_set = false;
490 ThreadStopSet::iterator it = m_seen_initial_stop.find(stop_tid);
491 if (it == m_seen_initial_stop.end())
493 m_seen_initial_stop.insert(stop_tid);
500 ProcessPOSIX::WaitingForInitialStop(lldb::tid_t stop_tid)
502 return (m_seen_initial_stop.find(stop_tid) == m_seen_initial_stop.end());
506 ProcessPOSIX::CreateNewPOSIXThread(lldb_private::Process &process, lldb::tid_t tid)
508 return new POSIXThread(process, tid);
512 ProcessPOSIX::RefreshStateAfterStop()
514 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS));
515 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
516 log->Printf ("ProcessPOSIX::%s(), message_queue size = %d", __FUNCTION__, (int)m_message_queue.size());
518 Mutex::Locker lock(m_message_mutex);
520 // This method used to only handle one message. Changing it to loop allows
521 // it to handle the case where we hit a breakpoint while handling a different
523 while (!m_message_queue.empty())
525 ProcessMessage &message = m_message_queue.front();
527 // Resolve the thread this message corresponds to and pass it along.
528 lldb::tid_t tid = message.GetTID();
530 log->Printf ("ProcessPOSIX::%s(), message_queue size = %d, pid = %" PRIi64, __FUNCTION__, (int)m_message_queue.size(), tid);
532 if (message.GetKind() == ProcessMessage::eNewThreadMessage)
535 log->Printf ("ProcessPOSIX::%s() adding thread, tid = %" PRIi64, __FUNCTION__, message.GetChildTID());
536 lldb::tid_t child_tid = message.GetChildTID();
538 thread_sp.reset(CreateNewPOSIXThread(*this, child_tid));
540 Mutex::Locker lock(m_thread_list.GetMutex());
542 m_thread_list.AddThread(thread_sp);
545 m_thread_list.RefreshStateAfterStop();
547 POSIXThread *thread = static_cast<POSIXThread*>(
548 GetThreadList().FindThreadByID(tid, false).get());
550 thread->Notify(message);
552 if (message.GetKind() == ProcessMessage::eExitMessage)
554 // FIXME: We should tell the user about this, but the limbo message is probably better for that.
556 log->Printf ("ProcessPOSIX::%s() removing thread, tid = %" PRIi64, __FUNCTION__, tid);
558 Mutex::Locker lock(m_thread_list.GetMutex());
560 ThreadSP thread_sp = m_thread_list.RemoveThreadByID(tid, false);
562 m_seen_initial_stop.erase(tid);
565 m_message_queue.pop();
570 ProcessPOSIX::IsAlive()
572 StateType state = GetPrivateState();
573 return state != eStateDetached
574 && state != eStateExited
575 && state != eStateInvalid
576 && state != eStateUnloaded;
580 ProcessPOSIX::DoReadMemory(addr_t vm_addr,
581 void *buf, size_t size, Error &error)
584 return m_monitor->ReadMemory(vm_addr, buf, size, error);
588 ProcessPOSIX::DoWriteMemory(addr_t vm_addr, const void *buf, size_t size,
592 return m_monitor->WriteMemory(vm_addr, buf, size, error);
596 ProcessPOSIX::DoAllocateMemory(size_t size, uint32_t permissions,
599 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
602 if (permissions & lldb::ePermissionsReadable)
603 prot |= eMmapProtRead;
604 if (permissions & lldb::ePermissionsWritable)
605 prot |= eMmapProtWrite;
606 if (permissions & lldb::ePermissionsExecutable)
607 prot |= eMmapProtExec;
609 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
610 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) {
611 m_addr_to_mmap_size[allocated_addr] = size;
614 allocated_addr = LLDB_INVALID_ADDRESS;
615 error.SetErrorStringWithFormat("unable to allocate %zu bytes of memory with permissions %s", size, GetPermissionsAsCString (permissions));
618 return allocated_addr;
622 ProcessPOSIX::DoDeallocateMemory(lldb::addr_t addr)
625 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
626 if (pos != m_addr_to_mmap_size.end() &&
627 InferiorCallMunmap(this, addr, pos->second))
628 m_addr_to_mmap_size.erase (pos);
630 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
636 ProcessPOSIX::ResolveIndirectFunction(const Address *address, Error &error)
638 addr_t function_addr = LLDB_INVALID_ADDRESS;
639 if (address == NULL) {
640 error.SetErrorStringWithFormat("unable to determine direct function call for NULL address");
641 } else if (!InferiorCall(this, address, function_addr)) {
642 function_addr = LLDB_INVALID_ADDRESS;
643 error.SetErrorStringWithFormat("unable to determine direct function call for indirect function %s",
644 address->CalculateSymbolContextSymbol()->GetName().AsCString());
646 return function_addr;
650 ProcessPOSIX::GetSoftwareBreakpointTrapOpcode(BreakpointSite* bp_site)
652 static const uint8_t g_i386_opcode[] = { 0xCC };
654 ArchSpec arch = GetTarget().GetArchitecture();
655 const uint8_t *opcode = NULL;
656 size_t opcode_size = 0;
658 switch (arch.GetCore())
661 assert(false && "CPU type not supported!");
664 case ArchSpec::eCore_x86_32_i386:
665 case ArchSpec::eCore_x86_64_x86_64:
666 opcode = g_i386_opcode;
667 opcode_size = sizeof(g_i386_opcode);
671 bp_site->SetTrapOpcode(opcode, opcode_size);
676 ProcessPOSIX::EnableBreakpointSite(BreakpointSite *bp_site)
678 return EnableSoftwareBreakpoint(bp_site);
682 ProcessPOSIX::DisableBreakpointSite(BreakpointSite *bp_site)
684 return DisableSoftwareBreakpoint(bp_site);
688 ProcessPOSIX::EnableWatchpoint(Watchpoint *wp, bool notify)
693 user_id_t watchID = wp->GetID();
694 addr_t addr = wp->GetLoadAddress();
695 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
697 log->Printf ("ProcessPOSIX::EnableWatchpoint(watchID = %" PRIu64 ")",
702 log->Printf("ProcessPOSIX::EnableWatchpoint(watchID = %" PRIu64
703 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
704 watchID, (uint64_t)addr);
708 // Try to find a vacant watchpoint slot in the inferiors' main thread
709 uint32_t wp_hw_index = LLDB_INVALID_INDEX32;
710 Mutex::Locker lock(m_thread_list.GetMutex());
711 POSIXThread *thread = static_cast<POSIXThread*>(
712 m_thread_list.GetThreadAtIndex(0, false).get());
715 wp_hw_index = thread->FindVacantWatchpointIndex();
717 if (wp_hw_index == LLDB_INVALID_INDEX32)
719 error.SetErrorString("Setting hardware watchpoint failed.");
723 wp->SetHardwareIndex(wp_hw_index);
724 bool wp_enabled = true;
725 uint32_t thread_count = m_thread_list.GetSize(false);
726 for (uint32_t i = 0; i < thread_count; ++i)
728 thread = static_cast<POSIXThread*>(
729 m_thread_list.GetThreadAtIndex(i, false).get());
731 wp_enabled &= thread->EnableHardwareWatchpoint(wp);
737 wp->SetEnabled(true, notify);
742 // Watchpoint enabling failed on at least one
743 // of the threads so roll back all of them
744 DisableWatchpoint(wp, false);
745 error.SetErrorString("Setting hardware watchpoint failed");
750 error.SetErrorString("Watchpoint argument was NULL.");
755 ProcessPOSIX::DisableWatchpoint(Watchpoint *wp, bool notify)
760 user_id_t watchID = wp->GetID();
761 addr_t addr = wp->GetLoadAddress();
762 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
764 log->Printf("ProcessPOSIX::DisableWatchpoint(watchID = %" PRIu64 ")",
766 if (!wp->IsEnabled())
769 log->Printf("ProcessPOSIX::DisableWatchpoint(watchID = %" PRIu64
770 ") addr = 0x%8.8" PRIx64 ": watchpoint already disabled.",
771 watchID, (uint64_t)addr);
772 // This is needed (for now) to keep watchpoints disabled correctly
773 wp->SetEnabled(false, notify);
777 if (wp->IsHardware())
779 bool wp_disabled = true;
780 Mutex::Locker lock(m_thread_list.GetMutex());
781 uint32_t thread_count = m_thread_list.GetSize(false);
782 for (uint32_t i = 0; i < thread_count; ++i)
784 POSIXThread *thread = static_cast<POSIXThread*>(
785 m_thread_list.GetThreadAtIndex(i, false).get());
787 wp_disabled &= thread->DisableHardwareWatchpoint(wp);
793 wp->SetHardwareIndex(LLDB_INVALID_INDEX32);
794 wp->SetEnabled(false, notify);
798 error.SetErrorString("Disabling hardware watchpoint failed");
802 error.SetErrorString("Watchpoint argument was NULL.");
807 ProcessPOSIX::GetWatchpointSupportInfo(uint32_t &num)
810 Mutex::Locker lock(m_thread_list.GetMutex());
811 POSIXThread *thread = static_cast<POSIXThread*>(
812 m_thread_list.GetThreadAtIndex(0, false).get());
814 num = thread->NumSupportedHardwareWatchpoints();
816 error.SetErrorString("Process does not exist.");
821 ProcessPOSIX::GetWatchpointSupportInfo(uint32_t &num, bool &after)
823 Error error = GetWatchpointSupportInfo(num);
824 // Watchpoints trigger and halt the inferior after
825 // the corresponding instruction has been executed.
831 ProcessPOSIX::UpdateThreadListIfNeeded()
833 Mutex::Locker lock(m_thread_list.GetMutex());
834 // Do not allow recursive updates.
835 return m_thread_list.GetSize(false);
839 ProcessPOSIX::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list)
841 Log *log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_THREAD));
842 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
843 log->Printf ("ProcessPOSIX::%s() (pid = %" PRIi64 ")", __FUNCTION__, GetID());
845 bool has_updated = false;
846 // Update the process thread list with this new thread.
847 // FIXME: We should be using tid, not pid.
849 ThreadSP thread_sp (old_thread_list.FindThreadByID (GetID(), false));
851 thread_sp.reset(CreateNewPOSIXThread(*this, GetID()));
855 if (log && log->GetMask().Test(POSIX_LOG_VERBOSE))
856 log->Printf ("ProcessPOSIX::%s() updated pid = %" PRIi64, __FUNCTION__, GetID());
857 new_thread_list.AddThread(thread_sp);
859 return has_updated; // the list has been updated
863 ProcessPOSIX::GetByteOrder() const
865 // FIXME: We should be able to extract this value directly. See comment in
871 ProcessPOSIX::PutSTDIN(const char *buf, size_t len, Error &error)
874 if ((status = write(m_monitor->GetTerminalFD(), buf, len)) < 0)
876 error.SetErrorToErrno();
883 ProcessPOSIX::GetUnixSignals()
888 //------------------------------------------------------------------------------
889 // Utility functions.
892 ProcessPOSIX::HasExited()
894 switch (GetPrivateState())
908 ProcessPOSIX::IsStopped()
910 switch (GetPrivateState())
917 case eStateSuspended:
925 ProcessPOSIX::IsAThreadRunning()
927 bool is_running = false;
928 Mutex::Locker lock(m_thread_list.GetMutex());
929 uint32_t thread_count = m_thread_list.GetSize(false);
930 for (uint32_t i = 0; i < thread_count; ++i)
932 POSIXThread *thread = static_cast<POSIXThread*>(
933 m_thread_list.GetThreadAtIndex(i, false).get());
934 StateType thread_state = thread->GetState();
935 if (thread_state == eStateRunning || thread_state == eStateStepping)