| //===-- Process.cpp -------------------------------------------------------===// |
| // |
| // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| // See https://llvm.org/LICENSE.txt for license information. |
| // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| // |
| //===----------------------------------------------------------------------===// |
| |
| #include <atomic> |
| #include <memory> |
| #include <mutex> |
| |
| #include "llvm/ADT/ScopeExit.h" |
| #include "llvm/Support/ScopedPrinter.h" |
| #include "llvm/Support/Threading.h" |
| |
| #include "lldb/Breakpoint/BreakpointLocation.h" |
| #include "lldb/Breakpoint/StoppointCallbackContext.h" |
| #include "lldb/Core/Debugger.h" |
| #include "lldb/Core/Module.h" |
| #include "lldb/Core/ModuleSpec.h" |
| #include "lldb/Core/PluginManager.h" |
| #include "lldb/Core/StreamFile.h" |
| #include "lldb/Expression/DiagnosticManager.h" |
| #include "lldb/Expression/DynamicCheckerFunctions.h" |
| #include "lldb/Expression/UserExpression.h" |
| #include "lldb/Expression/UtilityFunction.h" |
| #include "lldb/Host/ConnectionFileDescriptor.h" |
| #include "lldb/Host/FileSystem.h" |
| #include "lldb/Host/Host.h" |
| #include "lldb/Host/HostInfo.h" |
| #include "lldb/Host/OptionParser.h" |
| #include "lldb/Host/Pipe.h" |
| #include "lldb/Host/Terminal.h" |
| #include "lldb/Host/ThreadLauncher.h" |
| #include "lldb/Interpreter/CommandInterpreter.h" |
| #include "lldb/Interpreter/OptionArgParser.h" |
| #include "lldb/Interpreter/OptionValueProperties.h" |
| #include "lldb/Symbol/Function.h" |
| #include "lldb/Symbol/Symbol.h" |
| #include "lldb/Target/ABI.h" |
| #include "lldb/Target/AssertFrameRecognizer.h" |
| #include "lldb/Target/DynamicLoader.h" |
| #include "lldb/Target/InstrumentationRuntime.h" |
| #include "lldb/Target/JITLoader.h" |
| #include "lldb/Target/JITLoaderList.h" |
| #include "lldb/Target/Language.h" |
| #include "lldb/Target/LanguageRuntime.h" |
| #include "lldb/Target/MemoryHistory.h" |
| #include "lldb/Target/MemoryRegionInfo.h" |
| #include "lldb/Target/OperatingSystem.h" |
| #include "lldb/Target/Platform.h" |
| #include "lldb/Target/Process.h" |
| #include "lldb/Target/RegisterContext.h" |
| #include "lldb/Target/StopInfo.h" |
| #include "lldb/Target/StructuredDataPlugin.h" |
| #include "lldb/Target/SystemRuntime.h" |
| #include "lldb/Target/Target.h" |
| #include "lldb/Target/TargetList.h" |
| #include "lldb/Target/Thread.h" |
| #include "lldb/Target/ThreadPlan.h" |
| #include "lldb/Target/ThreadPlanBase.h" |
| #include "lldb/Target/ThreadPlanCallFunction.h" |
| #include "lldb/Target/ThreadPlanStack.h" |
| #include "lldb/Target/UnixSignals.h" |
| #include "lldb/Utility/Event.h" |
| #include "lldb/Utility/Log.h" |
| #include "lldb/Utility/NameMatches.h" |
| #include "lldb/Utility/ProcessInfo.h" |
| #include "lldb/Utility/SelectHelper.h" |
| #include "lldb/Utility/State.h" |
| #include "lldb/Utility/Timer.h" |
| |
| using namespace lldb; |
| using namespace lldb_private; |
| using namespace std::chrono; |
| |
| // Comment out line below to disable memory caching, overriding the process |
| // setting target.process.disable-memory-cache |
| #define ENABLE_MEMORY_CACHING |
| |
| #ifdef ENABLE_MEMORY_CACHING |
| #define DISABLE_MEM_CACHE_DEFAULT false |
| #else |
| #define DISABLE_MEM_CACHE_DEFAULT true |
| #endif |
| |
| class ProcessOptionValueProperties |
| : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> { |
| public: |
| ProcessOptionValueProperties(ConstString name) : Cloneable(name) {} |
| |
| const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx, |
| bool will_modify, |
| uint32_t idx) const override { |
| // When getting the value for a key from the process options, we will |
| // always try and grab the setting from the current process if there is |
| // one. Else we just use the one from this instance. |
| if (exe_ctx) { |
| Process *process = exe_ctx->GetProcessPtr(); |
| if (process) { |
| ProcessOptionValueProperties *instance_properties = |
| static_cast<ProcessOptionValueProperties *>( |
| process->GetValueProperties().get()); |
| if (this != instance_properties) |
| return instance_properties->ProtectedGetPropertyAtIndex(idx); |
| } |
| } |
| return ProtectedGetPropertyAtIndex(idx); |
| } |
| }; |
| |
| static constexpr OptionEnumValueElement g_follow_fork_mode_values[] = { |
| { |
| eFollowParent, |
| "parent", |
| "Continue tracing the parent process and detach the child.", |
| }, |
| { |
| eFollowChild, |
| "child", |
| "Trace the child process and detach the parent.", |
| }, |
| }; |
| |
| #define LLDB_PROPERTIES_process |
| #include "TargetProperties.inc" |
| |
| enum { |
| #define LLDB_PROPERTIES_process |
| #include "TargetPropertiesEnum.inc" |
| ePropertyExperimental, |
| }; |
| |
| #define LLDB_PROPERTIES_process_experimental |
| #include "TargetProperties.inc" |
| |
| enum { |
| #define LLDB_PROPERTIES_process_experimental |
| #include "TargetPropertiesEnum.inc" |
| }; |
| |
| class ProcessExperimentalOptionValueProperties |
| : public Cloneable<ProcessExperimentalOptionValueProperties, |
| OptionValueProperties> { |
| public: |
| ProcessExperimentalOptionValueProperties() |
| : Cloneable( |
| ConstString(Properties::GetExperimentalSettingsName())) {} |
| }; |
| |
| ProcessExperimentalProperties::ProcessExperimentalProperties() |
| : Properties(OptionValuePropertiesSP( |
| new ProcessExperimentalOptionValueProperties())) { |
| m_collection_sp->Initialize(g_process_experimental_properties); |
| } |
| |
| ProcessProperties::ProcessProperties(lldb_private::Process *process) |
| : Properties(), |
| m_process(process) // Can be nullptr for global ProcessProperties |
| { |
| if (process == nullptr) { |
| // Global process properties, set them up one time |
| m_collection_sp = |
| std::make_shared<ProcessOptionValueProperties>(ConstString("process")); |
| m_collection_sp->Initialize(g_process_properties); |
| m_collection_sp->AppendProperty( |
| ConstString("thread"), ConstString("Settings specific to threads."), |
| true, Thread::GetGlobalProperties().GetValueProperties()); |
| } else { |
| m_collection_sp = |
| OptionValueProperties::CreateLocalCopy(Process::GetGlobalProperties()); |
| m_collection_sp->SetValueChangedCallback( |
| ePropertyPythonOSPluginPath, |
| [this] { m_process->LoadOperatingSystemPlugin(true); }); |
| } |
| |
| m_experimental_properties_up = |
| std::make_unique<ProcessExperimentalProperties>(); |
| m_collection_sp->AppendProperty( |
| ConstString(Properties::GetExperimentalSettingsName()), |
| ConstString("Experimental settings - setting these won't produce " |
| "errors if the setting is not present."), |
| true, m_experimental_properties_up->GetValueProperties()); |
| } |
| |
| ProcessProperties::~ProcessProperties() = default; |
| |
| bool ProcessProperties::GetDisableMemoryCache() const { |
| const uint32_t idx = ePropertyDisableMemCache; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| uint64_t ProcessProperties::GetMemoryCacheLineSize() const { |
| const uint32_t idx = ePropertyMemCacheLineSize; |
| return m_collection_sp->GetPropertyAtIndexAsUInt64( |
| nullptr, idx, g_process_properties[idx].default_uint_value); |
| } |
| |
| Args ProcessProperties::GetExtraStartupCommands() const { |
| Args args; |
| const uint32_t idx = ePropertyExtraStartCommand; |
| m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args); |
| return args; |
| } |
| |
| void ProcessProperties::SetExtraStartupCommands(const Args &args) { |
| const uint32_t idx = ePropertyExtraStartCommand; |
| m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args); |
| } |
| |
| FileSpec ProcessProperties::GetPythonOSPluginPath() const { |
| const uint32_t idx = ePropertyPythonOSPluginPath; |
| return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); |
| } |
| |
| uint32_t ProcessProperties::GetVirtualAddressableBits() const { |
| const uint32_t idx = ePropertyVirtualAddressableBits; |
| return m_collection_sp->GetPropertyAtIndexAsUInt64( |
| nullptr, idx, g_process_properties[idx].default_uint_value); |
| } |
| |
| void ProcessProperties::SetVirtualAddressableBits(uint32_t bits) { |
| const uint32_t idx = ePropertyVirtualAddressableBits; |
| m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, bits); |
| } |
| void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) { |
| const uint32_t idx = ePropertyPythonOSPluginPath; |
| m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file); |
| } |
| |
| bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const { |
| const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) { |
| const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions; |
| m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore); |
| } |
| |
| bool ProcessProperties::GetUnwindOnErrorInExpressions() const { |
| const uint32_t idx = ePropertyUnwindOnErrorInExpressions; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) { |
| const uint32_t idx = ePropertyUnwindOnErrorInExpressions; |
| m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore); |
| } |
| |
| bool ProcessProperties::GetStopOnSharedLibraryEvents() const { |
| const uint32_t idx = ePropertyStopOnSharedLibraryEvents; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) { |
| const uint32_t idx = ePropertyStopOnSharedLibraryEvents; |
| m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop); |
| } |
| |
| bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const { |
| const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable) { |
| const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans; |
| m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, disable); |
| m_process->Flush(); |
| } |
| |
| bool ProcessProperties::GetDetachKeepsStopped() const { |
| const uint32_t idx = ePropertyDetachKeepsStopped; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| void ProcessProperties::SetDetachKeepsStopped(bool stop) { |
| const uint32_t idx = ePropertyDetachKeepsStopped; |
| m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop); |
| } |
| |
| bool ProcessProperties::GetWarningsOptimization() const { |
| const uint32_t idx = ePropertyWarningOptimization; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| bool ProcessProperties::GetWarningsUnsupportedLanguage() const { |
| const uint32_t idx = ePropertyWarningUnsupportedLanguage; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| bool ProcessProperties::GetStopOnExec() const { |
| const uint32_t idx = ePropertyStopOnExec; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const { |
| const uint32_t idx = ePropertyUtilityExpressionTimeout; |
| uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64( |
| nullptr, idx, g_process_properties[idx].default_uint_value); |
| return std::chrono::seconds(value); |
| } |
| |
| std::chrono::seconds ProcessProperties::GetInterruptTimeout() const { |
| const uint32_t idx = ePropertyInterruptTimeout; |
| uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64( |
| nullptr, idx, g_process_properties[idx].default_uint_value); |
| return std::chrono::seconds(value); |
| } |
| |
| bool ProcessProperties::GetSteppingRunsAllThreads() const { |
| const uint32_t idx = ePropertySteppingRunsAllThreads; |
| return m_collection_sp->GetPropertyAtIndexAsBoolean( |
| nullptr, idx, g_process_properties[idx].default_uint_value != 0); |
| } |
| |
| bool ProcessProperties::GetOSPluginReportsAllThreads() const { |
| const bool fail_value = true; |
| const Property *exp_property = |
| m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental); |
| OptionValueProperties *exp_values = |
| exp_property->GetValue()->GetAsProperties(); |
| if (!exp_values) |
| return fail_value; |
| |
| return exp_values->GetPropertyAtIndexAsBoolean( |
| nullptr, ePropertyOSPluginReportsAllThreads, fail_value); |
| } |
| |
| void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) { |
| const Property *exp_property = |
| m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental); |
| OptionValueProperties *exp_values = |
| exp_property->GetValue()->GetAsProperties(); |
| if (exp_values) |
| exp_values->SetPropertyAtIndexAsBoolean( |
| nullptr, ePropertyOSPluginReportsAllThreads, does_report); |
| } |
| |
| FollowForkMode ProcessProperties::GetFollowForkMode() const { |
| const uint32_t idx = ePropertyFollowForkMode; |
| return (FollowForkMode)m_collection_sp->GetPropertyAtIndexAsEnumeration( |
| nullptr, idx, g_process_properties[idx].default_uint_value); |
| } |
| |
| ProcessSP Process::FindPlugin(lldb::TargetSP target_sp, |
| llvm::StringRef plugin_name, |
| ListenerSP listener_sp, |
| const FileSpec *crash_file_path, |
| bool can_connect) { |
| static uint32_t g_process_unique_id = 0; |
| |
| ProcessSP process_sp; |
| ProcessCreateInstance create_callback = nullptr; |
| if (!plugin_name.empty()) { |
| create_callback = |
| PluginManager::GetProcessCreateCallbackForPluginName(plugin_name); |
| if (create_callback) { |
| process_sp = create_callback(target_sp, listener_sp, crash_file_path, |
| can_connect); |
| if (process_sp) { |
| if (process_sp->CanDebug(target_sp, true)) { |
| process_sp->m_process_unique_id = ++g_process_unique_id; |
| } else |
| process_sp.reset(); |
| } |
| } |
| } else { |
| for (uint32_t idx = 0; |
| (create_callback = |
| PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr; |
| ++idx) { |
| process_sp = create_callback(target_sp, listener_sp, crash_file_path, |
| can_connect); |
| if (process_sp) { |
| if (process_sp->CanDebug(target_sp, false)) { |
| process_sp->m_process_unique_id = ++g_process_unique_id; |
| break; |
| } else |
| process_sp.reset(); |
| } |
| } |
| } |
| return process_sp; |
| } |
| |
| ConstString &Process::GetStaticBroadcasterClass() { |
| static ConstString class_name("lldb.process"); |
| return class_name; |
| } |
| |
| Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp) |
| : Process(target_sp, listener_sp, |
| UnixSignals::Create(HostInfo::GetArchitecture())) { |
| // This constructor just delegates to the full Process constructor, |
| // defaulting to using the Host's UnixSignals. |
| } |
| |
| Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp, |
| const UnixSignalsSP &unix_signals_sp) |
| : ProcessProperties(this), |
| Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()), |
| Process::GetStaticBroadcasterClass().AsCString()), |
| m_target_wp(target_sp), m_public_state(eStateUnloaded), |
| m_private_state(eStateUnloaded), |
| m_private_state_broadcaster(nullptr, |
| "lldb.process.internal_state_broadcaster"), |
| m_private_state_control_broadcaster( |
| nullptr, "lldb.process.internal_state_control_broadcaster"), |
| m_private_state_listener_sp( |
| Listener::MakeListener("lldb.process.internal_state_listener")), |
| m_mod_id(), m_process_unique_id(0), m_thread_index_id(0), |
| m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(), |
| m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this), |
| m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this), |
| m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0), |
| m_notifications(), m_image_tokens(), m_listener_sp(listener_sp), |
| m_breakpoint_site_list(), m_dynamic_checkers_up(), |
| m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(), |
| m_stdio_communication("process.stdio"), m_stdio_communication_mutex(), |
| m_stdin_forward(false), m_stdout_data(), m_stderr_data(), |
| m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0), |
| m_memory_cache(*this), m_allocated_memory_cache(*this), |
| m_should_detach(false), m_next_event_action_up(), m_public_run_lock(), |
| m_private_run_lock(), m_finalizing(false), |
| m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false), |
| m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false), |
| m_can_interpret_function_calls(false), m_warnings_issued(), |
| m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) { |
| CheckInWithManager(); |
| |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); |
| LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this)); |
| |
| if (!m_unix_signals_sp) |
| m_unix_signals_sp = std::make_shared<UnixSignals>(); |
| |
| SetEventName(eBroadcastBitStateChanged, "state-changed"); |
| SetEventName(eBroadcastBitInterrupt, "interrupt"); |
| SetEventName(eBroadcastBitSTDOUT, "stdout-available"); |
| SetEventName(eBroadcastBitSTDERR, "stderr-available"); |
| SetEventName(eBroadcastBitProfileData, "profile-data-available"); |
| SetEventName(eBroadcastBitStructuredData, "structured-data-available"); |
| |
| m_private_state_control_broadcaster.SetEventName( |
| eBroadcastInternalStateControlStop, "control-stop"); |
| m_private_state_control_broadcaster.SetEventName( |
| eBroadcastInternalStateControlPause, "control-pause"); |
| m_private_state_control_broadcaster.SetEventName( |
| eBroadcastInternalStateControlResume, "control-resume"); |
| |
| m_listener_sp->StartListeningForEvents( |
| this, eBroadcastBitStateChanged | eBroadcastBitInterrupt | |
| eBroadcastBitSTDOUT | eBroadcastBitSTDERR | |
| eBroadcastBitProfileData | eBroadcastBitStructuredData); |
| |
| m_private_state_listener_sp->StartListeningForEvents( |
| &m_private_state_broadcaster, |
| eBroadcastBitStateChanged | eBroadcastBitInterrupt); |
| |
| m_private_state_listener_sp->StartListeningForEvents( |
| &m_private_state_control_broadcaster, |
| eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause | |
| eBroadcastInternalStateControlResume); |
| // We need something valid here, even if just the default UnixSignalsSP. |
| assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization"); |
| |
| // Allow the platform to override the default cache line size |
| OptionValueSP value_sp = |
| m_collection_sp |
| ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize) |
| ->GetValue(); |
| uint32_t platform_cache_line_size = |
| target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize(); |
| if (!value_sp->OptionWasSet() && platform_cache_line_size != 0) |
| value_sp->SetUInt64Value(platform_cache_line_size); |
| |
| RegisterAssertFrameRecognizer(this); |
| } |
| |
| Process::~Process() { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); |
| LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this)); |
| StopPrivateStateThread(); |
| |
| // ThreadList::Clear() will try to acquire this process's mutex, so |
| // explicitly clear the thread list here to ensure that the mutex is not |
| // destroyed before the thread list. |
| m_thread_list.Clear(); |
| } |
| |
| ProcessProperties &Process::GetGlobalProperties() { |
| // NOTE: intentional leak so we don't crash if global destructor chain gets |
| // called as other threads still use the result of this function |
| static ProcessProperties *g_settings_ptr = |
| new ProcessProperties(nullptr); |
| return *g_settings_ptr; |
| } |
| |
| void Process::Finalize() { |
| if (m_finalizing.exchange(true)) |
| return; |
| |
| // Destroy the process. This will call the virtual function DoDestroy under |
| // the hood, giving our derived class a chance to do the ncessary tear down. |
| DestroyImpl(false); |
| |
| // Clear our broadcaster before we proceed with destroying |
| Broadcaster::Clear(); |
| |
| // Do any cleanup needed prior to being destructed... Subclasses that |
| // override this method should call this superclass method as well. |
| |
| // We need to destroy the loader before the derived Process class gets |
| // destroyed since it is very likely that undoing the loader will require |
| // access to the real process. |
| m_dynamic_checkers_up.reset(); |
| m_abi_sp.reset(); |
| m_os_up.reset(); |
| m_system_runtime_up.reset(); |
| m_dyld_up.reset(); |
| m_jit_loaders_up.reset(); |
| m_thread_plans.Clear(); |
| m_thread_list_real.Destroy(); |
| m_thread_list.Destroy(); |
| m_extended_thread_list.Destroy(); |
| m_queue_list.Clear(); |
| m_queue_list_stop_id = 0; |
| std::vector<Notifications> empty_notifications; |
| m_notifications.swap(empty_notifications); |
| m_image_tokens.clear(); |
| m_memory_cache.Clear(); |
| m_allocated_memory_cache.Clear(); |
| { |
| std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); |
| m_language_runtimes.clear(); |
| } |
| m_instrumentation_runtimes.clear(); |
| m_next_event_action_up.reset(); |
| // Clear the last natural stop ID since it has a strong reference to this |
| // process |
| m_mod_id.SetStopEventForLastNaturalStopID(EventSP()); |
| //#ifdef LLDB_CONFIGURATION_DEBUG |
| // StreamFile s(stdout, false); |
| // EventSP event_sp; |
| // while (m_private_state_listener_sp->GetNextEvent(event_sp)) |
| // { |
| // event_sp->Dump (&s); |
| // s.EOL(); |
| // } |
| //#endif |
| // We have to be very careful here as the m_private_state_listener might |
| // contain events that have ProcessSP values in them which can keep this |
| // process around forever. These events need to be cleared out. |
| m_private_state_listener_sp->Clear(); |
| m_public_run_lock.TrySetRunning(); // This will do nothing if already locked |
| m_public_run_lock.SetStopped(); |
| m_private_run_lock.TrySetRunning(); // This will do nothing if already locked |
| m_private_run_lock.SetStopped(); |
| m_structured_data_plugin_map.clear(); |
| } |
| |
| void Process::RegisterNotificationCallbacks(const Notifications &callbacks) { |
| m_notifications.push_back(callbacks); |
| if (callbacks.initialize != nullptr) |
| callbacks.initialize(callbacks.baton, this); |
| } |
| |
| bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) { |
| std::vector<Notifications>::iterator pos, end = m_notifications.end(); |
| for (pos = m_notifications.begin(); pos != end; ++pos) { |
| if (pos->baton == callbacks.baton && |
| pos->initialize == callbacks.initialize && |
| pos->process_state_changed == callbacks.process_state_changed) { |
| m_notifications.erase(pos); |
| return true; |
| } |
| } |
| return false; |
| } |
| |
| void Process::SynchronouslyNotifyStateChanged(StateType state) { |
| std::vector<Notifications>::iterator notification_pos, |
| notification_end = m_notifications.end(); |
| for (notification_pos = m_notifications.begin(); |
| notification_pos != notification_end; ++notification_pos) { |
| if (notification_pos->process_state_changed) |
| notification_pos->process_state_changed(notification_pos->baton, this, |
| state); |
| } |
| } |
| |
| // FIXME: We need to do some work on events before the general Listener sees |
| // them. |
| // For instance if we are continuing from a breakpoint, we need to ensure that |
| // we do the little "insert real insn, step & stop" trick. But we can't do |
| // that when the event is delivered by the broadcaster - since that is done on |
| // the thread that is waiting for new events, so if we needed more than one |
| // event for our handling, we would stall. So instead we do it when we fetch |
| // the event off of the queue. |
| // |
| |
| StateType Process::GetNextEvent(EventSP &event_sp) { |
| StateType state = eStateInvalid; |
| |
| if (m_listener_sp->GetEventForBroadcaster(this, event_sp, |
| std::chrono::seconds(0)) && |
| event_sp) |
| state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); |
| |
| return state; |
| } |
| |
| void Process::SyncIOHandler(uint32_t iohandler_id, |
| const Timeout<std::micro> &timeout) { |
| // don't sync (potentially context switch) in case where there is no process |
| // IO |
| if (!m_process_input_reader) |
| return; |
| |
| auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout); |
| |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| if (Result) { |
| LLDB_LOG( |
| log, |
| "waited from m_iohandler_sync to change from {0}. New value is {1}.", |
| iohandler_id, *Result); |
| } else { |
| LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.", |
| iohandler_id); |
| } |
| } |
| |
| StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout, |
| EventSP *event_sp_ptr, bool wait_always, |
| ListenerSP hijack_listener_sp, |
| Stream *stream, bool use_run_lock) { |
| // We can't just wait for a "stopped" event, because the stopped event may |
| // have restarted the target. We have to actually check each event, and in |
| // the case of a stopped event check the restarted flag on the event. |
| if (event_sp_ptr) |
| event_sp_ptr->reset(); |
| StateType state = GetState(); |
| // If we are exited or detached, we won't ever get back to any other valid |
| // state... |
| if (state == eStateDetached || state == eStateExited) |
| return state; |
| |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOG(log, "timeout = {0}", timeout); |
| |
| if (!wait_always && StateIsStoppedState(state, true) && |
| StateIsStoppedState(GetPrivateState(), true)) { |
| LLDB_LOGF(log, |
| "Process::%s returning without waiting for events; process " |
| "private and public states are already 'stopped'.", |
| __FUNCTION__); |
| // We need to toggle the run lock as this won't get done in |
| // SetPublicState() if the process is hijacked. |
| if (hijack_listener_sp && use_run_lock) |
| m_public_run_lock.SetStopped(); |
| return state; |
| } |
| |
| while (state != eStateInvalid) { |
| EventSP event_sp; |
| state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp); |
| if (event_sp_ptr && event_sp) |
| *event_sp_ptr = event_sp; |
| |
| bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr); |
| Process::HandleProcessStateChangedEvent(event_sp, stream, |
| pop_process_io_handler); |
| |
| switch (state) { |
| case eStateCrashed: |
| case eStateDetached: |
| case eStateExited: |
| case eStateUnloaded: |
| // We need to toggle the run lock as this won't get done in |
| // SetPublicState() if the process is hijacked. |
| if (hijack_listener_sp && use_run_lock) |
| m_public_run_lock.SetStopped(); |
| return state; |
| case eStateStopped: |
| if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) |
| continue; |
| else { |
| // We need to toggle the run lock as this won't get done in |
| // SetPublicState() if the process is hijacked. |
| if (hijack_listener_sp && use_run_lock) |
| m_public_run_lock.SetStopped(); |
| return state; |
| } |
| default: |
| continue; |
| } |
| } |
| return state; |
| } |
| |
| bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp, |
| Stream *stream, |
| bool &pop_process_io_handler) { |
| const bool handle_pop = pop_process_io_handler; |
| |
| pop_process_io_handler = false; |
| ProcessSP process_sp = |
| Process::ProcessEventData::GetProcessFromEvent(event_sp.get()); |
| |
| if (!process_sp) |
| return false; |
| |
| StateType event_state = |
| Process::ProcessEventData::GetStateFromEvent(event_sp.get()); |
| if (event_state == eStateInvalid) |
| return false; |
| |
| switch (event_state) { |
| case eStateInvalid: |
| case eStateUnloaded: |
| case eStateAttaching: |
| case eStateLaunching: |
| case eStateStepping: |
| case eStateDetached: |
| if (stream) |
| stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(), |
| StateAsCString(event_state)); |
| if (event_state == eStateDetached) |
| pop_process_io_handler = true; |
| break; |
| |
| case eStateConnected: |
| case eStateRunning: |
| // Don't be chatty when we run... |
| break; |
| |
| case eStateExited: |
| if (stream) |
| process_sp->GetStatus(*stream); |
| pop_process_io_handler = true; |
| break; |
| |
| case eStateStopped: |
| case eStateCrashed: |
| case eStateSuspended: |
| // Make sure the program hasn't been auto-restarted: |
| if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) { |
| if (stream) { |
| size_t num_reasons = |
| Process::ProcessEventData::GetNumRestartedReasons(event_sp.get()); |
| if (num_reasons > 0) { |
| // FIXME: Do we want to report this, or would that just be annoyingly |
| // chatty? |
| if (num_reasons == 1) { |
| const char *reason = |
| Process::ProcessEventData::GetRestartedReasonAtIndex( |
| event_sp.get(), 0); |
| stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n", |
| process_sp->GetID(), |
| reason ? reason : "<UNKNOWN REASON>"); |
| } else { |
| stream->Printf("Process %" PRIu64 |
| " stopped and restarted, reasons:\n", |
| process_sp->GetID()); |
| |
| for (size_t i = 0; i < num_reasons; i++) { |
| const char *reason = |
| Process::ProcessEventData::GetRestartedReasonAtIndex( |
| event_sp.get(), i); |
| stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>"); |
| } |
| } |
| } |
| } |
| } else { |
| StopInfoSP curr_thread_stop_info_sp; |
| // Lock the thread list so it doesn't change on us, this is the scope for |
| // the locker: |
| { |
| ThreadList &thread_list = process_sp->GetThreadList(); |
| std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex()); |
| |
| ThreadSP curr_thread(thread_list.GetSelectedThread()); |
| ThreadSP thread; |
| StopReason curr_thread_stop_reason = eStopReasonInvalid; |
| bool prefer_curr_thread = false; |
| if (curr_thread && curr_thread->IsValid()) { |
| curr_thread_stop_reason = curr_thread->GetStopReason(); |
| switch (curr_thread_stop_reason) { |
| case eStopReasonNone: |
| case eStopReasonInvalid: |
| // Don't prefer the current thread if it didn't stop for a reason. |
| break; |
| case eStopReasonSignal: { |
| // We need to do the same computation we do for other threads |
| // below in case the current thread happens to be the one that |
| // stopped for the no-stop signal. |
| uint64_t signo = curr_thread->GetStopInfo()->GetValue(); |
| if (process_sp->GetUnixSignals()->GetShouldStop(signo)) |
| prefer_curr_thread = true; |
| } break; |
| default: |
| prefer_curr_thread = true; |
| break; |
| } |
| curr_thread_stop_info_sp = curr_thread->GetStopInfo(); |
| } |
| |
| if (!prefer_curr_thread) { |
| // Prefer a thread that has just completed its plan over another |
| // thread as current thread. |
| ThreadSP plan_thread; |
| ThreadSP other_thread; |
| |
| const size_t num_threads = thread_list.GetSize(); |
| size_t i; |
| for (i = 0; i < num_threads; ++i) { |
| thread = thread_list.GetThreadAtIndex(i); |
| StopReason thread_stop_reason = thread->GetStopReason(); |
| switch (thread_stop_reason) { |
| case eStopReasonInvalid: |
| case eStopReasonNone: |
| break; |
| |
| case eStopReasonSignal: { |
| // Don't select a signal thread if we weren't going to stop at |
| // that signal. We have to have had another reason for stopping |
| // here, and the user doesn't want to see this thread. |
| uint64_t signo = thread->GetStopInfo()->GetValue(); |
| if (process_sp->GetUnixSignals()->GetShouldStop(signo)) { |
| if (!other_thread) |
| other_thread = thread; |
| } |
| break; |
| } |
| case eStopReasonTrace: |
| case eStopReasonBreakpoint: |
| case eStopReasonWatchpoint: |
| case eStopReasonException: |
| case eStopReasonExec: |
| case eStopReasonFork: |
| case eStopReasonVFork: |
| case eStopReasonVForkDone: |
| case eStopReasonThreadExiting: |
| case eStopReasonInstrumentation: |
| case eStopReasonProcessorTrace: |
| if (!other_thread) |
| other_thread = thread; |
| break; |
| case eStopReasonPlanComplete: |
| if (!plan_thread) |
| plan_thread = thread; |
| break; |
| } |
| } |
| if (plan_thread) |
| thread_list.SetSelectedThreadByID(plan_thread->GetID()); |
| else if (other_thread) |
| thread_list.SetSelectedThreadByID(other_thread->GetID()); |
| else { |
| if (curr_thread && curr_thread->IsValid()) |
| thread = curr_thread; |
| else |
| thread = thread_list.GetThreadAtIndex(0); |
| |
| if (thread) |
| thread_list.SetSelectedThreadByID(thread->GetID()); |
| } |
| } |
| } |
| // Drop the ThreadList mutex by here, since GetThreadStatus below might |
| // have to run code, e.g. for Data formatters, and if we hold the |
| // ThreadList mutex, then the process is going to have a hard time |
| // restarting the process. |
| if (stream) { |
| Debugger &debugger = process_sp->GetTarget().GetDebugger(); |
| if (debugger.GetTargetList().GetSelectedTarget().get() == |
| &process_sp->GetTarget()) { |
| ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread(); |
| |
| if (!thread_sp || !thread_sp->IsValid()) |
| return false; |
| |
| const bool only_threads_with_stop_reason = true; |
| const uint32_t start_frame = thread_sp->GetSelectedFrameIndex(); |
| const uint32_t num_frames = 1; |
| const uint32_t num_frames_with_source = 1; |
| const bool stop_format = true; |
| |
| process_sp->GetStatus(*stream); |
| process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason, |
| start_frame, num_frames, |
| num_frames_with_source, |
| stop_format); |
| if (curr_thread_stop_info_sp) { |
| lldb::addr_t crashing_address; |
| ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference( |
| curr_thread_stop_info_sp, &crashing_address); |
| if (valobj_sp) { |
| const ValueObject::GetExpressionPathFormat format = |
| ValueObject::GetExpressionPathFormat:: |
| eGetExpressionPathFormatHonorPointers; |
| stream->PutCString("Likely cause: "); |
| valobj_sp->GetExpressionPath(*stream, format); |
| stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address); |
| } |
| } |
| } else { |
| uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget( |
| process_sp->GetTarget().shared_from_this()); |
| if (target_idx != UINT32_MAX) |
| stream->Printf("Target %d: (", target_idx); |
| else |
| stream->Printf("Target <unknown index>: ("); |
| process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief); |
| stream->Printf(") stopped.\n"); |
| } |
| } |
| |
| // Pop the process IO handler |
| pop_process_io_handler = true; |
| } |
| break; |
| } |
| |
| if (handle_pop && pop_process_io_handler) |
| process_sp->PopProcessIOHandler(); |
| |
| return true; |
| } |
| |
| bool Process::HijackProcessEvents(ListenerSP listener_sp) { |
| if (listener_sp) { |
| return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged | |
| eBroadcastBitInterrupt); |
| } else |
| return false; |
| } |
| |
| void Process::RestoreProcessEvents() { RestoreBroadcaster(); } |
| |
| StateType Process::GetStateChangedEvents(EventSP &event_sp, |
| const Timeout<std::micro> &timeout, |
| ListenerSP hijack_listener_sp) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); |
| |
| ListenerSP listener_sp = hijack_listener_sp; |
| if (!listener_sp) |
| listener_sp = m_listener_sp; |
| |
| StateType state = eStateInvalid; |
| if (listener_sp->GetEventForBroadcasterWithType( |
| this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp, |
| timeout)) { |
| if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) |
| state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); |
| else |
| LLDB_LOG(log, "got no event or was interrupted."); |
| } |
| |
| LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state); |
| return state; |
| } |
| |
| Event *Process::PeekAtStateChangedEvents() { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| |
| LLDB_LOGF(log, "Process::%s...", __FUNCTION__); |
| |
| Event *event_ptr; |
| event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType( |
| this, eBroadcastBitStateChanged); |
| if (log) { |
| if (event_ptr) { |
| LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__, |
| StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr))); |
| } else { |
| LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__); |
| } |
| } |
| return event_ptr; |
| } |
| |
| StateType |
| Process::GetStateChangedEventsPrivate(EventSP &event_sp, |
| const Timeout<std::micro> &timeout) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); |
| |
| StateType state = eStateInvalid; |
| if (m_private_state_listener_sp->GetEventForBroadcasterWithType( |
| &m_private_state_broadcaster, |
| eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp, |
| timeout)) |
| if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged) |
| state = Process::ProcessEventData::GetStateFromEvent(event_sp.get()); |
| |
| LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, |
| state == eStateInvalid ? "TIMEOUT" : StateAsCString(state)); |
| return state; |
| } |
| |
| bool Process::GetEventsPrivate(EventSP &event_sp, |
| const Timeout<std::micro> &timeout, |
| bool control_only) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout); |
| |
| if (control_only) |
| return m_private_state_listener_sp->GetEventForBroadcaster( |
| &m_private_state_control_broadcaster, event_sp, timeout); |
| else |
| return m_private_state_listener_sp->GetEvent(event_sp, timeout); |
| } |
| |
| bool Process::IsRunning() const { |
| return StateIsRunningState(m_public_state.GetValue()); |
| } |
| |
| int Process::GetExitStatus() { |
| std::lock_guard<std::mutex> guard(m_exit_status_mutex); |
| |
| if (m_public_state.GetValue() == eStateExited) |
| return m_exit_status; |
| return -1; |
| } |
| |
| const char *Process::GetExitDescription() { |
| std::lock_guard<std::mutex> guard(m_exit_status_mutex); |
| |
| if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty()) |
| return m_exit_string.c_str(); |
| return nullptr; |
| } |
| |
| bool Process::SetExitStatus(int status, const char *cstr) { |
| // Use a mutex to protect setting the exit status. |
| std::lock_guard<std::mutex> guard(m_exit_status_mutex); |
| |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | |
| LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF( |
| log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)", |
| status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : ""); |
| |
| // We were already in the exited state |
| if (m_private_state.GetValue() == eStateExited) { |
| LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because " |
| "state was already set to eStateExited"); |
| return false; |
| } |
| |
| m_exit_status = status; |
| if (cstr) |
| m_exit_string = cstr; |
| else |
| m_exit_string.clear(); |
| |
| // Clear the last natural stop ID since it has a strong reference to this |
| // process |
| m_mod_id.SetStopEventForLastNaturalStopID(EventSP()); |
| |
| SetPrivateState(eStateExited); |
| |
| // Allow subclasses to do some cleanup |
| DidExit(); |
| |
| return true; |
| } |
| |
| bool Process::IsAlive() { |
| switch (m_private_state.GetValue()) { |
| case eStateConnected: |
| case eStateAttaching: |
| case eStateLaunching: |
| case eStateStopped: |
| case eStateRunning: |
| case eStateStepping: |
| case eStateCrashed: |
| case eStateSuspended: |
| return true; |
| default: |
| return false; |
| } |
| } |
| |
| // This static callback can be used to watch for local child processes on the |
| // current host. The child process exits, the process will be found in the |
| // global target list (we want to be completely sure that the |
| // lldb_private::Process doesn't go away before we can deliver the signal. |
| bool Process::SetProcessExitStatus( |
| lldb::pid_t pid, bool exited, |
| int signo, // Zero for no signal |
| int exit_status // Exit value of process if signal is zero |
| ) { |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, |
| "Process::SetProcessExitStatus (pid=%" PRIu64 |
| ", exited=%i, signal=%i, exit_status=%i)\n", |
| pid, exited, signo, exit_status); |
| |
| if (exited) { |
| TargetSP target_sp(Debugger::FindTargetWithProcessID(pid)); |
| if (target_sp) { |
| ProcessSP process_sp(target_sp->GetProcessSP()); |
| if (process_sp) { |
| const char *signal_cstr = nullptr; |
| if (signo) |
| signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo); |
| |
| process_sp->SetExitStatus(exit_status, signal_cstr); |
| } |
| } |
| return true; |
| } |
| return false; |
| } |
| |
| bool Process::UpdateThreadList(ThreadList &old_thread_list, |
| ThreadList &new_thread_list) { |
| m_thread_plans.ClearThreadCache(); |
| return DoUpdateThreadList(old_thread_list, new_thread_list); |
| } |
| |
| void Process::UpdateThreadListIfNeeded() { |
| const uint32_t stop_id = GetStopID(); |
| if (m_thread_list.GetSize(false) == 0 || |
| stop_id != m_thread_list.GetStopID()) { |
| bool clear_unused_threads = true; |
| const StateType state = GetPrivateState(); |
| if (StateIsStoppedState(state, true)) { |
| std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex()); |
| m_thread_list.SetStopID(stop_id); |
| |
| // m_thread_list does have its own mutex, but we need to hold onto the |
| // mutex between the call to UpdateThreadList(...) and the |
| // os->UpdateThreadList(...) so it doesn't change on us |
| ThreadList &old_thread_list = m_thread_list; |
| ThreadList real_thread_list(this); |
| ThreadList new_thread_list(this); |
| // Always update the thread list with the protocol specific thread list, |
| // but only update if "true" is returned |
| if (UpdateThreadList(m_thread_list_real, real_thread_list)) { |
| // Don't call into the OperatingSystem to update the thread list if we |
| // are shutting down, since that may call back into the SBAPI's, |
| // requiring the API lock which is already held by whoever is shutting |
| // us down, causing a deadlock. |
| OperatingSystem *os = GetOperatingSystem(); |
| if (os && !m_destroy_in_process) { |
| // Clear any old backing threads where memory threads might have been |
| // backed by actual threads from the lldb_private::Process subclass |
| size_t num_old_threads = old_thread_list.GetSize(false); |
| for (size_t i = 0; i < num_old_threads; ++i) |
| old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread(); |
| // See if the OS plugin reports all threads. If it does, then |
| // it is safe to clear unseen thread's plans here. Otherwise we |
| // should preserve them in case they show up again: |
| clear_unused_threads = GetOSPluginReportsAllThreads(); |
| |
| // Turn off dynamic types to ensure we don't run any expressions. |
| // Objective-C can run an expression to determine if a SBValue is a |
| // dynamic type or not and we need to avoid this. OperatingSystem |
| // plug-ins can't run expressions that require running code... |
| |
| Target &target = GetTarget(); |
| const lldb::DynamicValueType saved_prefer_dynamic = |
| target.GetPreferDynamicValue(); |
| if (saved_prefer_dynamic != lldb::eNoDynamicValues) |
| target.SetPreferDynamicValue(lldb::eNoDynamicValues); |
| |
| // Now let the OperatingSystem plug-in update the thread list |
| |
| os->UpdateThreadList( |
| old_thread_list, // Old list full of threads created by OS plug-in |
| real_thread_list, // The actual thread list full of threads |
| // created by each lldb_private::Process |
| // subclass |
| new_thread_list); // The new thread list that we will show to the |
| // user that gets filled in |
| |
| if (saved_prefer_dynamic != lldb::eNoDynamicValues) |
| target.SetPreferDynamicValue(saved_prefer_dynamic); |
| } else { |
| // No OS plug-in, the new thread list is the same as the real thread |
| // list. |
| new_thread_list = real_thread_list; |
| } |
| |
| m_thread_list_real.Update(real_thread_list); |
| m_thread_list.Update(new_thread_list); |
| m_thread_list.SetStopID(stop_id); |
| |
| if (GetLastNaturalStopID() != m_extended_thread_stop_id) { |
| // Clear any extended threads that we may have accumulated previously |
| m_extended_thread_list.Clear(); |
| m_extended_thread_stop_id = GetLastNaturalStopID(); |
| |
| m_queue_list.Clear(); |
| m_queue_list_stop_id = GetLastNaturalStopID(); |
| } |
| } |
| // Now update the plan stack map. |
| // If we do have an OS plugin, any absent real threads in the |
| // m_thread_list have already been removed from the ThreadPlanStackMap. |
| // So any remaining threads are OS Plugin threads, and those we want to |
| // preserve in case they show up again. |
| m_thread_plans.Update(m_thread_list, clear_unused_threads); |
| } |
| } |
| } |
| |
| ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) { |
| return m_thread_plans.Find(tid); |
| } |
| |
| bool Process::PruneThreadPlansForTID(lldb::tid_t tid) { |
| return m_thread_plans.PrunePlansForTID(tid); |
| } |
| |
| void Process::PruneThreadPlans() { |
| m_thread_plans.Update(GetThreadList(), true, false); |
| } |
| |
| bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid, |
| lldb::DescriptionLevel desc_level, |
| bool internal, bool condense_trivial, |
| bool skip_unreported_plans) { |
| return m_thread_plans.DumpPlansForTID( |
| strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans); |
| } |
| void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level, |
| bool internal, bool condense_trivial, |
| bool skip_unreported_plans) { |
| m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial, |
| skip_unreported_plans); |
| } |
| |
| void Process::UpdateQueueListIfNeeded() { |
| if (m_system_runtime_up) { |
| if (m_queue_list.GetSize() == 0 || |
| m_queue_list_stop_id != GetLastNaturalStopID()) { |
| const StateType state = GetPrivateState(); |
| if (StateIsStoppedState(state, true)) { |
| m_system_runtime_up->PopulateQueueList(m_queue_list); |
| m_queue_list_stop_id = GetLastNaturalStopID(); |
| } |
| } |
| } |
| } |
| |
| ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) { |
| OperatingSystem *os = GetOperatingSystem(); |
| if (os) |
| return os->CreateThread(tid, context); |
| return ThreadSP(); |
| } |
| |
| uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) { |
| return AssignIndexIDToThread(thread_id); |
| } |
| |
| bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) { |
| return (m_thread_id_to_index_id_map.find(thread_id) != |
| m_thread_id_to_index_id_map.end()); |
| } |
| |
| uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) { |
| uint32_t result = 0; |
| std::map<uint64_t, uint32_t>::iterator iterator = |
| m_thread_id_to_index_id_map.find(thread_id); |
| if (iterator == m_thread_id_to_index_id_map.end()) { |
| result = ++m_thread_index_id; |
| m_thread_id_to_index_id_map[thread_id] = result; |
| } else { |
| result = iterator->second; |
| } |
| |
| return result; |
| } |
| |
| StateType Process::GetState() { |
| return m_public_state.GetValue(); |
| } |
| |
| void Process::SetPublicState(StateType new_state, bool restarted) { |
| const bool new_state_is_stopped = StateIsStoppedState(new_state, false); |
| if (new_state_is_stopped) { |
| // This will only set the time if the public stop time has no value, so |
| // it is ok to call this multiple times. With a public stop we can't look |
| // at the stop ID because many private stops might have happened, so we |
| // can't check for a stop ID of zero. This allows the "statistics" command |
| // to dump the time it takes to reach somewhere in your code, like a |
| // breakpoint you set. |
| GetTarget().GetStatistics().SetFirstPublicStopTime(); |
| } |
| |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | |
| LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)", |
| StateAsCString(new_state), restarted); |
| const StateType old_state = m_public_state.GetValue(); |
| m_public_state.SetValue(new_state); |
| |
| // On the transition from Run to Stopped, we unlock the writer end of the run |
| // lock. The lock gets locked in Resume, which is the public API to tell the |
| // program to run. |
| if (!StateChangedIsExternallyHijacked()) { |
| if (new_state == eStateDetached) { |
| LLDB_LOGF(log, |
| "Process::SetPublicState (%s) -- unlocking run lock for detach", |
| StateAsCString(new_state)); |
| m_public_run_lock.SetStopped(); |
| } else { |
| const bool old_state_is_stopped = StateIsStoppedState(old_state, false); |
| if ((old_state_is_stopped != new_state_is_stopped)) { |
| if (new_state_is_stopped && !restarted) { |
| LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock", |
| StateAsCString(new_state)); |
| m_public_run_lock.SetStopped(); |
| } |
| } |
| } |
| } |
| } |
| |
| Status Process::Resume() { |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | |
| LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, "Process::Resume -- locking run lock"); |
| if (!m_public_run_lock.TrySetRunning()) { |
| Status error("Resume request failed - process still running."); |
| LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming."); |
| return error; |
| } |
| Status error = PrivateResume(); |
| if (!error.Success()) { |
| // Undo running state change |
| m_public_run_lock.SetStopped(); |
| } |
| return error; |
| } |
| |
| static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack"; |
| |
| Status Process::ResumeSynchronous(Stream *stream) { |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE | |
| LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock"); |
| if (!m_public_run_lock.TrySetRunning()) { |
| Status error("Resume request failed - process still running."); |
| LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming."); |
| return error; |
| } |
| |
| ListenerSP listener_sp( |
| Listener::MakeListener(g_resume_sync_name)); |
| HijackProcessEvents(listener_sp); |
| |
| Status error = PrivateResume(); |
| if (error.Success()) { |
| StateType state = WaitForProcessToStop(llvm::None, nullptr, true, |
| listener_sp, stream); |
| const bool must_be_alive = |
| false; // eStateExited is ok, so this must be false |
| if (!StateIsStoppedState(state, must_be_alive)) |
| error.SetErrorStringWithFormat( |
| "process not in stopped state after synchronous resume: %s", |
| StateAsCString(state)); |
| } else { |
| // Undo running state change |
| m_public_run_lock.SetStopped(); |
| } |
| |
| // Undo the hijacking of process events... |
| RestoreProcessEvents(); |
| |
| return error; |
| } |
| |
| bool Process::StateChangedIsExternallyHijacked() { |
| if (IsHijackedForEvent(eBroadcastBitStateChanged)) { |
| const char *hijacking_name = GetHijackingListenerName(); |
| if (hijacking_name && |
| strcmp(hijacking_name, g_resume_sync_name)) |
| return true; |
| } |
| return false; |
| } |
| |
| bool Process::StateChangedIsHijackedForSynchronousResume() { |
| if (IsHijackedForEvent(eBroadcastBitStateChanged)) { |
| const char *hijacking_name = GetHijackingListenerName(); |
| if (hijacking_name && |
| strcmp(hijacking_name, g_resume_sync_name) == 0) |
| return true; |
| } |
| return false; |
| } |
| |
| StateType Process::GetPrivateState() { return m_private_state.GetValue(); } |
| |
| void Process::SetPrivateState(StateType new_state) { |
| if (m_finalizing) |
| return; |
| |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet( |
| LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_UNWIND)); |
| bool state_changed = false; |
| |
| LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state)); |
| |
| std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex()); |
| std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex()); |
| |
| const StateType old_state = m_private_state.GetValueNoLock(); |
| state_changed = old_state != new_state; |
| |
| const bool old_state_is_stopped = StateIsStoppedState(old_state, false); |
| const bool new_state_is_stopped = StateIsStoppedState(new_state, false); |
| if (old_state_is_stopped != new_state_is_stopped) { |
| if (new_state_is_stopped) |
| m_private_run_lock.SetStopped(); |
| else |
| m_private_run_lock.SetRunning(); |
| } |
| |
| if (state_changed) { |
| m_private_state.SetValueNoLock(new_state); |
| EventSP event_sp( |
| new Event(eBroadcastBitStateChanged, |
| new ProcessEventData(shared_from_this(), new_state))); |
| if (StateIsStoppedState(new_state, false)) { |
| // Note, this currently assumes that all threads in the list stop when |
| // the process stops. In the future we will want to support a debugging |
| // model where some threads continue to run while others are stopped. |
| // When that happens we will either need a way for the thread list to |
| // identify which threads are stopping or create a special thread list |
| // containing only threads which actually stopped. |
| // |
| // The process plugin is responsible for managing the actual behavior of |
| // the threads and should have stopped any threads that are going to stop |
| // before we get here. |
| m_thread_list.DidStop(); |
| |
| if (m_mod_id.BumpStopID() == 0) |
| GetTarget().GetStatistics().SetFirstPrivateStopTime(); |
| |
| if (!m_mod_id.IsLastResumeForUserExpression()) |
| m_mod_id.SetStopEventForLastNaturalStopID(event_sp); |
| m_memory_cache.Clear(); |
| LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u", |
| StateAsCString(new_state), m_mod_id.GetStopID()); |
| } |
| |
| m_private_state_broadcaster.BroadcastEvent(event_sp); |
| } else { |
| LLDB_LOGF(log, |
| "Process::SetPrivateState (%s) state didn't change. Ignoring...", |
| StateAsCString(new_state)); |
| } |
| } |
| |
| void Process::SetRunningUserExpression(bool on) { |
| m_mod_id.SetRunningUserExpression(on); |
| } |
| |
| void Process::SetRunningUtilityFunction(bool on) { |
| m_mod_id.SetRunningUtilityFunction(on); |
| } |
| |
| addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; } |
| |
| const lldb::ABISP &Process::GetABI() { |
| if (!m_abi_sp) |
| m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture()); |
| return m_abi_sp; |
| } |
| |
| std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() { |
| std::vector<LanguageRuntime *> language_runtimes; |
| |
| if (m_finalizing) |
| return language_runtimes; |
| |
| std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); |
| // Before we pass off a copy of the language runtimes, we must make sure that |
| // our collection is properly populated. It's possible that some of the |
| // language runtimes were not loaded yet, either because nobody requested it |
| // yet or the proper condition for loading wasn't yet met (e.g. libc++.so |
| // hadn't been loaded). |
| for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) { |
| if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type)) |
| language_runtimes.emplace_back(runtime); |
| } |
| |
| return language_runtimes; |
| } |
| |
| LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) { |
| if (m_finalizing) |
| return nullptr; |
| |
| LanguageRuntime *runtime = nullptr; |
| |
| std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex); |
| LanguageRuntimeCollection::iterator pos; |
| pos = m_language_runtimes.find(language); |
| if (pos == m_language_runtimes.end() || !pos->second) { |
| lldb::LanguageRuntimeSP runtime_sp( |
| LanguageRuntime::FindPlugin(this, language)); |
| |
| m_language_runtimes[language] = runtime_sp; |
| runtime = runtime_sp.get(); |
| } else |
| runtime = pos->second.get(); |
| |
| if (runtime) |
| // It's possible that a language runtime can support multiple LanguageTypes, |
| // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus, |
| // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the |
| // primary language type and make sure that our runtime supports it. |
| assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language)); |
| |
| return runtime; |
| } |
| |
| bool Process::IsPossibleDynamicValue(ValueObject &in_value) { |
| if (m_finalizing) |
| return false; |
| |
| if (in_value.IsDynamic()) |
| return false; |
| LanguageType known_type = in_value.GetObjectRuntimeLanguage(); |
| |
| if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) { |
| LanguageRuntime *runtime = GetLanguageRuntime(known_type); |
| return runtime ? runtime->CouldHaveDynamicValue(in_value) : false; |
| } |
| |
| for (LanguageRuntime *runtime : GetLanguageRuntimes()) { |
| if (runtime->CouldHaveDynamicValue(in_value)) |
| return true; |
| } |
| |
| return false; |
| } |
| |
| void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) { |
| m_dynamic_checkers_up.reset(dynamic_checkers); |
| } |
| |
| BreakpointSiteList &Process::GetBreakpointSiteList() { |
| return m_breakpoint_site_list; |
| } |
| |
| const BreakpointSiteList &Process::GetBreakpointSiteList() const { |
| return m_breakpoint_site_list; |
| } |
| |
| void Process::DisableAllBreakpointSites() { |
| m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void { |
| // bp_site->SetEnabled(true); |
| DisableBreakpointSite(bp_site); |
| }); |
| } |
| |
| Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) { |
| Status error(DisableBreakpointSiteByID(break_id)); |
| |
| if (error.Success()) |
| m_breakpoint_site_list.Remove(break_id); |
| |
| return error; |
| } |
| |
| Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) { |
| Status error; |
| BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); |
| if (bp_site_sp) { |
| if (bp_site_sp->IsEnabled()) |
| error = DisableBreakpointSite(bp_site_sp.get()); |
| } else { |
| error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, |
| break_id); |
| } |
| |
| return error; |
| } |
| |
| Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) { |
| Status error; |
| BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id); |
| if (bp_site_sp) { |
| if (!bp_site_sp->IsEnabled()) |
| error = EnableBreakpointSite(bp_site_sp.get()); |
| } else { |
| error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64, |
| break_id); |
| } |
| return error; |
| } |
| |
| lldb::break_id_t |
| Process::CreateBreakpointSite(const BreakpointLocationSP &owner, |
| bool use_hardware) { |
| addr_t load_addr = LLDB_INVALID_ADDRESS; |
| |
| bool show_error = true; |
| switch (GetState()) { |
| case eStateInvalid: |
| case eStateUnloaded: |
| case eStateConnected: |
| case eStateAttaching: |
| case eStateLaunching: |
| case eStateDetached: |
| case eStateExited: |
| show_error = false; |
| break; |
| |
| case eStateStopped: |
| case eStateRunning: |
| case eStateStepping: |
| case eStateCrashed: |
| case eStateSuspended: |
| show_error = IsAlive(); |
| break; |
| } |
| |
| // Reset the IsIndirect flag here, in case the location changes from pointing |
| // to a indirect symbol to a regular symbol. |
| owner->SetIsIndirect(false); |
| |
| if (owner->ShouldResolveIndirectFunctions()) { |
| Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol(); |
| if (symbol && symbol->IsIndirect()) { |
| Status error; |
| Address symbol_address = symbol->GetAddress(); |
| load_addr = ResolveIndirectFunction(&symbol_address, error); |
| if (!error.Success() && show_error) { |
| GetTarget().GetDebugger().GetErrorStream().Printf( |
| "warning: failed to resolve indirect function at 0x%" PRIx64 |
| " for breakpoint %i.%i: %s\n", |
| symbol->GetLoadAddress(&GetTarget()), |
| owner->GetBreakpoint().GetID(), owner->GetID(), |
| error.AsCString() ? error.AsCString() : "unknown error"); |
| return LLDB_INVALID_BREAK_ID; |
| } |
| Address resolved_address(load_addr); |
| load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget()); |
| owner->SetIsIndirect(true); |
| } else |
| load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget()); |
| } else |
| load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget()); |
| |
| if (load_addr != LLDB_INVALID_ADDRESS) { |
| BreakpointSiteSP bp_site_sp; |
| |
| // Look up this breakpoint site. If it exists, then add this new owner, |
| // otherwise create a new breakpoint site and add it. |
| |
| bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr); |
| |
| if (bp_site_sp) { |
| bp_site_sp->AddOwner(owner); |
| owner->SetBreakpointSite(bp_site_sp); |
| return bp_site_sp->GetID(); |
| } else { |
| bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner, |
| load_addr, use_hardware)); |
| if (bp_site_sp) { |
| Status error = EnableBreakpointSite(bp_site_sp.get()); |
| if (error.Success()) { |
| owner->SetBreakpointSite(bp_site_sp); |
| return m_breakpoint_site_list.Add(bp_site_sp); |
| } else { |
| if (show_error || use_hardware) { |
| // Report error for setting breakpoint... |
| GetTarget().GetDebugger().GetErrorStream().Printf( |
| "warning: failed to set breakpoint site at 0x%" PRIx64 |
| " for breakpoint %i.%i: %s\n", |
| load_addr, owner->GetBreakpoint().GetID(), owner->GetID(), |
| error.AsCString() ? error.AsCString() : "unknown error"); |
| } |
| } |
| } |
| } |
| } |
| // We failed to enable the breakpoint |
| return LLDB_INVALID_BREAK_ID; |
| } |
| |
| void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id, |
| lldb::user_id_t owner_loc_id, |
| BreakpointSiteSP &bp_site_sp) { |
| uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id); |
| if (num_owners == 0) { |
| // Don't try to disable the site if we don't have a live process anymore. |
| if (IsAlive()) |
| DisableBreakpointSite(bp_site_sp.get()); |
| m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress()); |
| } |
| } |
| |
| size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size, |
| uint8_t *buf) const { |
| size_t bytes_removed = 0; |
| BreakpointSiteList bp_sites_in_range; |
| |
| if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size, |
| bp_sites_in_range)) { |
| bp_sites_in_range.ForEach([bp_addr, size, |
| buf](BreakpointSite *bp_site) -> void { |
| if (bp_site->GetType() == BreakpointSite::eSoftware) { |
| addr_t intersect_addr; |
| size_t intersect_size; |
| size_t opcode_offset; |
| if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr, |
| &intersect_size, &opcode_offset)) { |
| assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size); |
| assert(bp_addr < intersect_addr + intersect_size && |
| intersect_addr + intersect_size <= bp_addr + size); |
| assert(opcode_offset + intersect_size <= bp_site->GetByteSize()); |
| size_t buf_offset = intersect_addr - bp_addr; |
| ::memcpy(buf + buf_offset, |
| bp_site->GetSavedOpcodeBytes() + opcode_offset, |
| intersect_size); |
| } |
| } |
| }); |
| } |
| return bytes_removed; |
| } |
| |
| size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) { |
| PlatformSP platform_sp(GetTarget().GetPlatform()); |
| if (platform_sp) |
| return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site); |
| return 0; |
| } |
| |
| Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) { |
| Status error; |
| assert(bp_site != nullptr); |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); |
| const addr_t bp_addr = bp_site->GetLoadAddress(); |
| LLDB_LOGF( |
| log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64, |
| bp_site->GetID(), (uint64_t)bp_addr); |
| if (bp_site->IsEnabled()) { |
| LLDB_LOGF( |
| log, |
| "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 |
| " -- already enabled", |
| bp_site->GetID(), (uint64_t)bp_addr); |
| return error; |
| } |
| |
| if (bp_addr == LLDB_INVALID_ADDRESS) { |
| error.SetErrorString("BreakpointSite contains an invalid load address."); |
| return error; |
| } |
| // Ask the lldb::Process subclass to fill in the correct software breakpoint |
| // trap for the breakpoint site |
| const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site); |
| |
| if (bp_opcode_size == 0) { |
| error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() " |
| "returned zero, unable to get breakpoint " |
| "trap for address 0x%" PRIx64, |
| bp_addr); |
| } else { |
| const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes(); |
| |
| if (bp_opcode_bytes == nullptr) { |
| error.SetErrorString( |
| "BreakpointSite doesn't contain a valid breakpoint trap opcode."); |
| return error; |
| } |
| |
| // Save the original opcode by reading it |
| if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size, |
| error) == bp_opcode_size) { |
| // Write a software breakpoint in place of the original opcode |
| if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) == |
| bp_opcode_size) { |
| uint8_t verify_bp_opcode_bytes[64]; |
| if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size, |
| error) == bp_opcode_size) { |
| if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes, |
| bp_opcode_size) == 0) { |
| bp_site->SetEnabled(true); |
| bp_site->SetType(BreakpointSite::eSoftware); |
| LLDB_LOGF(log, |
| "Process::EnableSoftwareBreakpoint (site_id = %d) " |
| "addr = 0x%" PRIx64 " -- SUCCESS", |
| bp_site->GetID(), (uint64_t)bp_addr); |
| } else |
| error.SetErrorString( |
| "failed to verify the breakpoint trap in memory."); |
| } else |
| error.SetErrorString( |
| "Unable to read memory to verify breakpoint trap."); |
| } else |
| error.SetErrorString("Unable to write breakpoint trap to memory."); |
| } else |
| error.SetErrorString("Unable to read memory at breakpoint address."); |
| } |
| if (log && error.Fail()) |
| LLDB_LOGF( |
| log, |
| "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 |
| " -- FAILED: %s", |
| bp_site->GetID(), (uint64_t)bp_addr, error.AsCString()); |
| return error; |
| } |
| |
| Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) { |
| Status error; |
| assert(bp_site != nullptr); |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); |
| addr_t bp_addr = bp_site->GetLoadAddress(); |
| lldb::user_id_t breakID = bp_site->GetID(); |
| LLDB_LOGF(log, |
| "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64 |
| ") addr = 0x%" PRIx64, |
| breakID, (uint64_t)bp_addr); |
| |
| if (bp_site->IsHardware()) { |
| error.SetErrorString("Breakpoint site is a hardware breakpoint."); |
| } else if (bp_site->IsEnabled()) { |
| const size_t break_op_size = bp_site->GetByteSize(); |
| const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes(); |
| if (break_op_size > 0) { |
| // Clear a software breakpoint instruction |
| uint8_t curr_break_op[8]; |
| assert(break_op_size <= sizeof(curr_break_op)); |
| bool break_op_found = false; |
| |
| // Read the breakpoint opcode |
| if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) == |
| break_op_size) { |
| bool verify = false; |
| // Make sure the breakpoint opcode exists at this address |
| if (::memcmp(curr_break_op, break_op, break_op_size) == 0) { |
| break_op_found = true; |
| // We found a valid breakpoint opcode at this address, now restore |
| // the saved opcode. |
| if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), |
| break_op_size, error) == break_op_size) { |
| verify = true; |
| } else |
| error.SetErrorString( |
| "Memory write failed when restoring original opcode."); |
| } else { |
| error.SetErrorString( |
| "Original breakpoint trap is no longer in memory."); |
| // Set verify to true and so we can check if the original opcode has |
| // already been restored |
| verify = true; |
| } |
| |
| if (verify) { |
| uint8_t verify_opcode[8]; |
| assert(break_op_size < sizeof(verify_opcode)); |
| // Verify that our original opcode made it back to the inferior |
| if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) == |
| break_op_size) { |
| // compare the memory we just read with the original opcode |
| if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode, |
| break_op_size) == 0) { |
| // SUCCESS |
| bp_site->SetEnabled(false); |
| LLDB_LOGF(log, |
| "Process::DisableSoftwareBreakpoint (site_id = %d) " |
| "addr = 0x%" PRIx64 " -- SUCCESS", |
| bp_site->GetID(), (uint64_t)bp_addr); |
| return error; |
| } else { |
| if (break_op_found) |
| error.SetErrorString("Failed to restore original opcode."); |
| } |
| } else |
| error.SetErrorString("Failed to read memory to verify that " |
| "breakpoint trap was restored."); |
| } |
| } else |
| error.SetErrorString( |
| "Unable to read memory that should contain the breakpoint trap."); |
| } |
| } else { |
| LLDB_LOGF( |
| log, |
| "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 |
| " -- already disabled", |
| bp_site->GetID(), (uint64_t)bp_addr); |
| return error; |
| } |
| |
| LLDB_LOGF( |
| log, |
| "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64 |
| " -- FAILED: %s", |
| bp_site->GetID(), (uint64_t)bp_addr, error.AsCString()); |
| return error; |
| } |
| |
| // Uncomment to verify memory caching works after making changes to caching |
| // code |
| //#define VERIFY_MEMORY_READS |
| |
| size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) { |
| error.Clear(); |
| if (!GetDisableMemoryCache()) { |
| #if defined(VERIFY_MEMORY_READS) |
| // Memory caching is enabled, with debug verification |
| |
| if (buf && size) { |
| // Uncomment the line below to make sure memory caching is working. |
| // I ran this through the test suite and got no assertions, so I am |
| // pretty confident this is working well. If any changes are made to |
| // memory caching, uncomment the line below and test your changes! |
| |
| // Verify all memory reads by using the cache first, then redundantly |
| // reading the same memory from the inferior and comparing to make sure |
| // everything is exactly the same. |
| std::string verify_buf(size, '\0'); |
| assert(verify_buf.size() == size); |
| const size_t cache_bytes_read = |
| m_memory_cache.Read(this, addr, buf, size, error); |
| Status verify_error; |
| const size_t verify_bytes_read = |
| ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()), |
| verify_buf.size(), verify_error); |
| assert(cache_bytes_read == verify_bytes_read); |
| assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0); |
| assert(verify_error.Success() == error.Success()); |
| return cache_bytes_read; |
| } |
| return 0; |
| #else // !defined(VERIFY_MEMORY_READS) |
| // Memory caching is enabled, without debug verification |
| |
| return m_memory_cache.Read(addr, buf, size, error); |
| #endif // defined (VERIFY_MEMORY_READS) |
| } else { |
| // Memory caching is disabled |
| |
| return ReadMemoryFromInferior(addr, buf, size, error); |
| } |
| } |
| |
| size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str, |
| Status &error) { |
| char buf[256]; |
| out_str.clear(); |
| addr_t curr_addr = addr; |
| while (true) { |
| size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error); |
| if (length == 0) |
| break; |
| out_str.append(buf, length); |
| // If we got "length - 1" bytes, we didn't get the whole C string, we need |
| // to read some more characters |
| if (length == sizeof(buf) - 1) |
| curr_addr += length; |
| else |
| break; |
| } |
| return out_str.size(); |
| } |
| |
| // Deprecated in favor of ReadStringFromMemory which has wchar support and |
| // correct code to find null terminators. |
| size_t Process::ReadCStringFromMemory(addr_t addr, char *dst, |
| size_t dst_max_len, |
| Status &result_error) { |
| size_t total_cstr_len = 0; |
| if (dst && dst_max_len) { |
| result_error.Clear(); |
| // NULL out everything just to be safe |
| memset(dst, 0, dst_max_len); |
| Status error; |
| addr_t curr_addr = addr; |
| const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize(); |
| size_t bytes_left = dst_max_len - 1; |
| char *curr_dst = dst; |
| |
| while (bytes_left > 0) { |
| addr_t cache_line_bytes_left = |
| cache_line_size - (curr_addr % cache_line_size); |
| addr_t bytes_to_read = |
| std::min<addr_t>(bytes_left, cache_line_bytes_left); |
| size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error); |
| |
| if (bytes_read == 0) { |
| result_error = error; |
| dst[total_cstr_len] = '\0'; |
| break; |
| } |
| const size_t len = strlen(curr_dst); |
| |
| total_cstr_len += len; |
| |
| if (len < bytes_to_read) |
| break; |
| |
| curr_dst += bytes_read; |
| curr_addr += bytes_read; |
| bytes_left -= bytes_read; |
| } |
| } else { |
| if (dst == nullptr) |
| result_error.SetErrorString("invalid arguments"); |
| else |
| result_error.Clear(); |
| } |
| return total_cstr_len; |
| } |
| |
| size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size, |
| Status &error) { |
| LLDB_SCOPED_TIMER(); |
| |
| if (buf == nullptr || size == 0) |
| return 0; |
| |
| size_t bytes_read = 0; |
| uint8_t *bytes = (uint8_t *)buf; |
| |
| while (bytes_read < size) { |
| const size_t curr_size = size - bytes_read; |
| const size_t curr_bytes_read = |
| DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error); |
| bytes_read += curr_bytes_read; |
| if (curr_bytes_read == curr_size || curr_bytes_read == 0) |
| break; |
| } |
| |
| // Replace any software breakpoint opcodes that fall into this range back |
| // into "buf" before we return |
| if (bytes_read > 0) |
| RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf); |
| return bytes_read; |
| } |
| |
| uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr, |
| size_t integer_byte_size, |
| uint64_t fail_value, |
| Status &error) { |
| Scalar scalar; |
| if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar, |
| error)) |
| return scalar.ULongLong(fail_value); |
| return fail_value; |
| } |
| |
| int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr, |
| size_t integer_byte_size, |
| int64_t fail_value, |
| Status &error) { |
| Scalar scalar; |
| if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar, |
| error)) |
| return scalar.SLongLong(fail_value); |
| return fail_value; |
| } |
| |
| addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) { |
| Scalar scalar; |
| if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar, |
| error)) |
| return scalar.ULongLong(LLDB_INVALID_ADDRESS); |
| return LLDB_INVALID_ADDRESS; |
| } |
| |
| bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, |
| Status &error) { |
| Scalar scalar; |
| const uint32_t addr_byte_size = GetAddressByteSize(); |
| if (addr_byte_size <= 4) |
| scalar = (uint32_t)ptr_value; |
| else |
| scalar = ptr_value; |
| return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) == |
| addr_byte_size; |
| } |
| |
| size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size, |
| Status &error) { |
| size_t bytes_written = 0; |
| const uint8_t *bytes = (const uint8_t *)buf; |
| |
| while (bytes_written < size) { |
| const size_t curr_size = size - bytes_written; |
| const size_t curr_bytes_written = DoWriteMemory( |
| addr + bytes_written, bytes + bytes_written, curr_size, error); |
| bytes_written += curr_bytes_written; |
| if (curr_bytes_written == curr_size || curr_bytes_written == 0) |
| break; |
| } |
| return bytes_written; |
| } |
| |
| size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size, |
| Status &error) { |
| #if defined(ENABLE_MEMORY_CACHING) |
| m_memory_cache.Flush(addr, size); |
| #endif |
| |
| if (buf == nullptr || size == 0) |
| return 0; |
| |
| m_mod_id.BumpMemoryID(); |
| |
| // We need to write any data that would go where any current software traps |
| // (enabled software breakpoints) any software traps (breakpoints) that we |
| // may have placed in our tasks memory. |
| |
| BreakpointSiteList bp_sites_in_range; |
| if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range)) |
| return WriteMemoryPrivate(addr, buf, size, error); |
| |
| // No breakpoint sites overlap |
| if (bp_sites_in_range.IsEmpty()) |
| return WriteMemoryPrivate(addr, buf, size, error); |
| |
| const uint8_t *ubuf = (const uint8_t *)buf; |
| uint64_t bytes_written = 0; |
| |
| bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf, |
| &error](BreakpointSite *bp) -> void { |
| if (error.Fail()) |
| return; |
| |
| if (bp->GetType() != BreakpointSite::eSoftware) |
| return; |
| |
| addr_t intersect_addr; |
| size_t intersect_size; |
| size_t opcode_offset; |
| const bool intersects = bp->IntersectsRange( |
| addr, size, &intersect_addr, &intersect_size, &opcode_offset); |
| UNUSED_IF_ASSERT_DISABLED(intersects); |
| assert(intersects); |
| assert(addr <= intersect_addr && intersect_addr < addr + size); |
| assert(addr < intersect_addr + intersect_size && |
| intersect_addr + intersect_size <= addr + size); |
| assert(opcode_offset + intersect_size <= bp->GetByteSize()); |
| |
| // Check for bytes before this breakpoint |
| const addr_t curr_addr = addr + bytes_written; |
| if (intersect_addr > curr_addr) { |
| // There are some bytes before this breakpoint that we need to just |
| // write to memory |
| size_t curr_size = intersect_addr - curr_addr; |
| size_t curr_bytes_written = |
| WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error); |
| bytes_written += curr_bytes_written; |
| if (curr_bytes_written != curr_size) { |
| // We weren't able to write all of the requested bytes, we are |
| // done looping and will return the number of bytes that we have |
| // written so far. |
| if (error.Success()) |
| error.SetErrorToGenericError(); |
| } |
| } |
| // Now write any bytes that would cover up any software breakpoints |
| // directly into the breakpoint opcode buffer |
| ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, |
| intersect_size); |
| bytes_written += intersect_size; |
| }); |
| |
| // Write any remaining bytes after the last breakpoint if we have any left |
| if (bytes_written < size) |
| bytes_written += |
| WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written, |
| size - bytes_written, error); |
| |
| return bytes_written; |
| } |
| |
| size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar, |
| size_t byte_size, Status &error) { |
| if (byte_size == UINT32_MAX) |
| byte_size = scalar.GetByteSize(); |
| if (byte_size > 0) { |
| uint8_t buf[32]; |
| const size_t mem_size = |
| scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error); |
| if (mem_size > 0) |
| return WriteMemory(addr, buf, mem_size, error); |
| else |
| error.SetErrorString("failed to get scalar as memory data"); |
| } else { |
| error.SetErrorString("invalid scalar value"); |
| } |
| return 0; |
| } |
| |
| size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size, |
| bool is_signed, Scalar &scalar, |
| Status &error) { |
| uint64_t uval = 0; |
| if (byte_size == 0) { |
| error.SetErrorString("byte size is zero"); |
| } else if (byte_size & (byte_size - 1)) { |
| error.SetErrorStringWithFormat("byte size %u is not a power of 2", |
| byte_size); |
| } else if (byte_size <= sizeof(uval)) { |
| const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error); |
| if (bytes_read == byte_size) { |
| DataExtractor data(&uval, sizeof(uval), GetByteOrder(), |
| GetAddressByteSize()); |
| lldb::offset_t offset = 0; |
| if (byte_size <= 4) |
| scalar = data.GetMaxU32(&offset, byte_size); |
| else |
| scalar = data.GetMaxU64(&offset, byte_size); |
| if (is_signed) |
| scalar.SignExtend(byte_size * 8); |
| return bytes_read; |
| } |
| } else { |
| error.SetErrorStringWithFormat( |
| "byte size of %u is too large for integer scalar type", byte_size); |
| } |
| return 0; |
| } |
| |
| Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) { |
| Status error; |
| for (const auto &Entry : entries) { |
| WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(), |
| error); |
| if (!error.Success()) |
| break; |
| } |
| return error; |
| } |
| |
| #define USE_ALLOCATE_MEMORY_CACHE 1 |
| addr_t Process::AllocateMemory(size_t size, uint32_t permissions, |
| Status &error) { |
| if (GetPrivateState() != eStateStopped) { |
| error.SetErrorToGenericError(); |
| return LLDB_INVALID_ADDRESS; |
| } |
| |
| #if defined(USE_ALLOCATE_MEMORY_CACHE) |
| return m_allocated_memory_cache.AllocateMemory(size, permissions, error); |
| #else |
| addr_t allocated_addr = DoAllocateMemory(size, permissions, error); |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, |
| "Process::AllocateMemory(size=%" PRIu64 |
| ", permissions=%s) => 0x%16.16" PRIx64 |
| " (m_stop_id = %u m_memory_id = %u)", |
| (uint64_t)size, GetPermissionsAsCString(permissions), |
| (uint64_t)allocated_addr, m_mod_id.GetStopID(), |
| m_mod_id.GetMemoryID()); |
| return allocated_addr; |
| #endif |
| } |
| |
| addr_t Process::CallocateMemory(size_t size, uint32_t permissions, |
| Status &error) { |
| addr_t return_addr = AllocateMemory(size, permissions, error); |
| if (error.Success()) { |
| std::string buffer(size, 0); |
| WriteMemory(return_addr, buffer.c_str(), size, error); |
| } |
| return return_addr; |
| } |
| |
| bool Process::CanJIT() { |
| if (m_can_jit == eCanJITDontKnow) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| Status err; |
| |
| uint64_t allocated_memory = AllocateMemory( |
| 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable, |
| err); |
| |
| if (err.Success()) { |
| m_can_jit = eCanJITYes; |
| LLDB_LOGF(log, |
| "Process::%s pid %" PRIu64 |
| " allocation test passed, CanJIT () is true", |
| __FUNCTION__, GetID()); |
| } else { |
| m_can_jit = eCanJITNo; |
| LLDB_LOGF(log, |
| "Process::%s pid %" PRIu64 |
| " allocation test failed, CanJIT () is false: %s", |
| __FUNCTION__, GetID(), err.AsCString()); |
| } |
| |
| DeallocateMemory(allocated_memory); |
| } |
| |
| return m_can_jit == eCanJITYes; |
| } |
| |
| void Process::SetCanJIT(bool can_jit) { |
| m_can_jit = (can_jit ? eCanJITYes : eCanJITNo); |
| } |
| |
| void Process::SetCanRunCode(bool can_run_code) { |
| SetCanJIT(can_run_code); |
| m_can_interpret_function_calls = can_run_code; |
| } |
| |
| Status Process::DeallocateMemory(addr_t ptr) { |
| Status error; |
| #if defined(USE_ALLOCATE_MEMORY_CACHE) |
| if (!m_allocated_memory_cache.DeallocateMemory(ptr)) { |
| error.SetErrorStringWithFormat( |
| "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr); |
| } |
| #else |
| error = DoDeallocateMemory(ptr); |
| |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, |
| "Process::DeallocateMemory(addr=0x%16.16" PRIx64 |
| ") => err = %s (m_stop_id = %u, m_memory_id = %u)", |
| ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(), |
| m_mod_id.GetMemoryID()); |
| #endif |
| return error; |
| } |
| |
| ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec, |
| lldb::addr_t header_addr, |
| size_t size_to_read) { |
| Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST); |
| if (log) { |
| LLDB_LOGF(log, |
| "Process::ReadModuleFromMemory reading %s binary from memory", |
| file_spec.GetPath().c_str()); |
| } |
| ModuleSP module_sp(new Module(file_spec, ArchSpec())); |
| if (module_sp) { |
| Status error; |
| ObjectFile *objfile = module_sp->GetMemoryObjectFile( |
| shared_from_this(), header_addr, error, size_to_read); |
| if (objfile) |
| return module_sp; |
| } |
| return ModuleSP(); |
| } |
| |
| bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr, |
| uint32_t &permissions) { |
| MemoryRegionInfo range_info; |
| permissions = 0; |
| Status error(GetMemoryRegionInfo(load_addr, range_info)); |
| if (!error.Success()) |
| return false; |
| if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow || |
| range_info.GetWritable() == MemoryRegionInfo::eDontKnow || |
| range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) { |
| return false; |
| } |
| |
| if (range_info.GetReadable() == MemoryRegionInfo::eYes) |
| permissions |= lldb::ePermissionsReadable; |
| |
| if (range_info.GetWritable() == MemoryRegionInfo::eYes) |
| permissions |= lldb::ePermissionsWritable; |
| |
| if (range_info.GetExecutable() == MemoryRegionInfo::eYes) |
| permissions |= lldb::ePermissionsExecutable; |
| |
| return true; |
| } |
| |
| Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) { |
| Status error; |
| error.SetErrorString("watchpoints are not supported"); |
| return error; |
| } |
| |
| Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) { |
| Status error; |
| error.SetErrorString("watchpoints are not supported"); |
| return error; |
| } |
| |
| StateType |
| Process::WaitForProcessStopPrivate(EventSP &event_sp, |
| const Timeout<std::micro> &timeout) { |
| StateType state; |
| |
| while (true) { |
| event_sp.reset(); |
| state = GetStateChangedEventsPrivate(event_sp, timeout); |
| |
| if (StateIsStoppedState(state, false)) |
| break; |
| |
| // If state is invalid, then we timed out |
| if (state == eStateInvalid) |
| break; |
| |
| if (event_sp) |
| HandlePrivateEvent(event_sp); |
| } |
| return state; |
| } |
| |
| void Process::LoadOperatingSystemPlugin(bool flush) { |
| if (flush) |
| m_thread_list.Clear(); |
| m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr)); |
| if (flush) |
| Flush(); |
| } |
| |
| Status Process::Launch(ProcessLaunchInfo &launch_info) { |
| Status error; |
| m_abi_sp.reset(); |
| m_dyld_up.reset(); |
| m_jit_loaders_up.reset(); |
| m_system_runtime_up.reset(); |
| m_os_up.reset(); |
| m_process_input_reader.reset(); |
| |
| Module *exe_module = GetTarget().GetExecutableModulePointer(); |
| |
| // The "remote executable path" is hooked up to the local Executable |
| // module. But we should be able to debug a remote process even if the |
| // executable module only exists on the remote. However, there needs to |
| // be a way to express this path, without actually having a module. |
| // The way to do that is to set the ExecutableFile in the LaunchInfo. |
| // Figure that out here: |
| |
| FileSpec exe_spec_to_use; |
| if (!exe_module) { |
| if (!launch_info.GetExecutableFile()) { |
| error.SetErrorString("executable module does not exist"); |
| return error; |
| } |
| exe_spec_to_use = launch_info.GetExecutableFile(); |
| } else |
| exe_spec_to_use = exe_module->GetFileSpec(); |
| |
| if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) { |
| // Install anything that might need to be installed prior to launching. |
| // For host systems, this will do nothing, but if we are connected to a |
| // remote platform it will install any needed binaries |
| error = GetTarget().Install(&launch_info); |
| if (error.Fail()) |
| return error; |
| } |
| // Listen and queue events that are broadcasted during the process launch. |
| ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack")); |
| HijackProcessEvents(listener_sp); |
| auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); }); |
| |
| if (PrivateStateThreadIsValid()) |
| PausePrivateStateThread(); |
| |
| error = WillLaunch(exe_module); |
| if (error.Success()) { |
| const bool restarted = false; |
| SetPublicState(eStateLaunching, restarted); |
| m_should_detach = false; |
| |
| if (m_public_run_lock.TrySetRunning()) { |
| // Now launch using these arguments. |
| error = DoLaunch(exe_module, launch_info); |
| } else { |
| // This shouldn't happen |
| error.SetErrorString("failed to acquire process run lock"); |
| } |
| |
| if (error.Fail()) { |
| if (GetID() != LLDB_INVALID_PROCESS_ID) { |
| SetID(LLDB_INVALID_PROCESS_ID); |
| const char *error_string = error.AsCString(); |
| if (error_string == nullptr) |
| error_string = "launch failed"; |
| SetExitStatus(-1, error_string); |
| } |
| } else { |
| EventSP event_sp; |
| |
| // Now wait for the process to launch and return control to us, and then |
| // call DidLaunch: |
| StateType state = WaitForProcessStopPrivate(event_sp, seconds(10)); |
| |
| if (state == eStateInvalid || !event_sp) { |
| // We were able to launch the process, but we failed to catch the |
| // initial stop. |
| error.SetErrorString("failed to catch stop after launch"); |
| SetExitStatus(0, "failed to catch stop after launch"); |
| Destroy(false); |
| } else if (state == eStateStopped || state == eStateCrashed) { |
| DidLaunch(); |
| |
| DynamicLoader *dyld = GetDynamicLoader(); |
| if (dyld) |
| dyld->DidLaunch(); |
| |
| GetJITLoaders().DidLaunch(); |
| |
| SystemRuntime *system_runtime = GetSystemRuntime(); |
| if (system_runtime) |
| system_runtime->DidLaunch(); |
| |
| if (!m_os_up) |
| LoadOperatingSystemPlugin(false); |
| |
| // We successfully launched the process and stopped, now it the |
| // right time to set up signal filters before resuming. |
| UpdateAutomaticSignalFiltering(); |
| |
| // Note, the stop event was consumed above, but not handled. This |
| // was done to give DidLaunch a chance to run. The target is either |
| // stopped or crashed. Directly set the state. This is done to |
| // prevent a stop message with a bunch of spurious output on thread |
| // status, as well as not pop a ProcessIOHandler. |
| // We are done with the launch hijack listener, and this stop should |
| // go to the public state listener: |
| RestoreProcessEvents(); |
| SetPublicState(state, false); |
| |
| if (PrivateStateThreadIsValid()) |
| ResumePrivateStateThread(); |
| else |
| StartPrivateStateThread(); |
| |
| // Target was stopped at entry as was intended. Need to notify the |
| // listeners about it. |
| if (state == eStateStopped && |
| launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) |
| HandlePrivateEvent(event_sp); |
| } else if (state == eStateExited) { |
| // We exited while trying to launch somehow. Don't call DidLaunch |
| // as that's not likely to work, and return an invalid pid. |
| HandlePrivateEvent(event_sp); |
| } |
| } |
| } else { |
| std::string local_exec_file_path = exe_spec_to_use.GetPath(); |
| error.SetErrorStringWithFormat("file doesn't exist: '%s'", |
| local_exec_file_path.c_str()); |
| } |
| |
| return error; |
| } |
| |
| Status Process::LoadCore() { |
| Status error = DoLoadCore(); |
| if (error.Success()) { |
| ListenerSP listener_sp( |
| Listener::MakeListener("lldb.process.load_core_listener")); |
| HijackProcessEvents(listener_sp); |
| |
| if (PrivateStateThreadIsValid()) |
| ResumePrivateStateThread(); |
| else |
| StartPrivateStateThread(); |
| |
| DynamicLoader *dyld = GetDynamicLoader(); |
| if (dyld) |
| dyld->DidAttach(); |
| |
| GetJITLoaders().DidAttach(); |
| |
| SystemRuntime *system_runtime = GetSystemRuntime(); |
| if (system_runtime) |
| system_runtime->DidAttach(); |
| |
| if (!m_os_up) |
| LoadOperatingSystemPlugin(false); |
| |
| // We successfully loaded a core file, now pretend we stopped so we can |
| // show all of the threads in the core file and explore the crashed state. |
| SetPrivateState(eStateStopped); |
| |
| // Wait for a stopped event since we just posted one above... |
| lldb::EventSP event_sp; |
| StateType state = |
| WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp); |
| |
| if (!StateIsStoppedState(state, false)) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s", |
| StateAsCString(state)); |
| error.SetErrorString( |
| "Did not get stopped event after loading the core file."); |
| } |
| RestoreProcessEvents(); |
| } |
| return error; |
| } |
| |
| DynamicLoader *Process::GetDynamicLoader() { |
| if (!m_dyld_up) |
| m_dyld_up.reset(DynamicLoader::FindPlugin(this, "")); |
| return m_dyld_up.get(); |
| } |
| |
| DataExtractor Process::GetAuxvData() { return DataExtractor(); } |
| |
| llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) { |
| return false; |
| } |
| |
| JITLoaderList &Process::GetJITLoaders() { |
| if (!m_jit_loaders_up) { |
| m_jit_loaders_up = std::make_unique<JITLoaderList>(); |
| JITLoader::LoadPlugins(this, *m_jit_loaders_up); |
| } |
| return *m_jit_loaders_up; |
| } |
| |
| SystemRuntime *Process::GetSystemRuntime() { |
| if (!m_system_runtime_up) |
| m_system_runtime_up.reset(SystemRuntime::FindPlugin(this)); |
| return m_system_runtime_up.get(); |
| } |
| |
| Process::AttachCompletionHandler::AttachCompletionHandler(Process *process, |
| uint32_t exec_count) |
| : NextEventAction(process), m_exec_count(exec_count) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| LLDB_LOGF( |
| log, |
| "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32, |
| __FUNCTION__, static_cast<void *>(process), exec_count); |
| } |
| |
| Process::NextEventAction::EventActionResult |
| Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) { |
| Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); |
| |
| StateType state = ProcessEventData::GetStateFromEvent(event_sp.get()); |
| LLDB_LOGF(log, |
| "Process::AttachCompletionHandler::%s called with state %s (%d)", |
| __FUNCTION__, StateAsCString(state), static_cast<int>(state)); |
| |
| switch (state) { |
| case eStateAttaching: |
| return eEventActionSuccess; |
| |
| case eStateRunning: |
| case eStateConnected: |
| return eEventActionRetry; |
| |
| case eStateStopped: |
| case eStateCrashed: |
| // During attach, prior to sending the eStateStopped event, |
| // lldb_private::Process subclasses must set the new process ID. |
| assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID); |
| // We don't want these events to be reported, so go set the |
| // ShouldReportStop here: |
| m_process->GetThreadList().SetShouldReportStop(eVoteNo); |
| |
| if (m_exec_count > 0) { |
| --m_exec_count; |
| |
| LLDB_LOGF(log, |
| "Process::AttachCompletionHandler::%s state %s: reduced " |
| "remaining exec count to %" PRIu32 ", requesting resume", |
| __FUNCTION__, StateAsCString(state), m_exec_count); |
| |
| RequestResume(); |
| return eEventActionRetry; |
| } else { |
| LLDB_LOGF(log, |
| "Process::AttachCompletionHandler::%s state %s: no more " |
| "execs expected to start, continuing with attach", |
| __FUNCTION__, StateAsCString(state)); |
| |
| m_process->CompleteAttach(); |
| return eEventActionSuccess; |
| } |
| break; |
| |
| default: |
| case eStateExited: |
| case eStateInvalid: |
| break; |
| } |
| |
| m_exit_string.assign("No valid Process"); |
| return eEventActionExit; |
| } |
| |
| Process::NextEventAction::EventActionResult |
| Process::AttachCompletionHandler::HandleBeingInterrupted() { |
| return eEventActionSuccess; |
| } |
| |
| const char *Process::AttachCompletionHandler::GetExitString() { |
| return m_exit_string.c_str(); |
| } |
| |
| ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) { |
| if (m_listener_sp) |
| return m_listener_sp; |
| else |
| return debugger.GetListener(); |
| } |
| |
| Status Process::Attach(ProcessAttachInfo &attach_info) { |
| m_abi_sp.reset(); |
| m_process_input_reader.reset(); |
| m_dyld_up.reset(); |
| m_jit_loaders_up.reset(); |
| m_system_runtime_up.reset(); |
| m_os_up.reset(); |
| |
| lldb::pid_t attach_pid = attach_info.GetProcessID(); |
| Status error; |
| if (attach_pid == LLDB_INVALID_PROCESS_ID) { |
| char process_name[PATH_MAX]; |
| |
| if (attach_info.GetExecutableFile().GetPath(process_name, |
| sizeof(process_name))) { |
| const bool wait_for_launch = attach_info.GetWaitForLaunch(); |
| |
| if (wait_for_launch) { |
| error = WillAttachToProcessWithName(process_name, wait_for_launch); |
| if (error.Success()) { |
| if (m_public_run_lock.TrySetRunning()) { |
| m_should_detach = true; |
| const bool restarted = false; |
| SetPublicState(eStateAttaching, restarted); |
| // Now attach using these arguments. |
| error = DoAttachToProcessWithName(process_name, attach_info); |
| } else { |
| // This shouldn't happen |
| error.SetErrorString("failed to acquire process run lock"); |
| } |
| |
| if (error.Fail()) { |
| if (GetID() != LLDB_INVALID_PROCESS_ID) { |
| SetID(LLDB_INVALID_PROCESS_ID); |
| if (error.AsCString() == nullptr) |
| error.SetErrorString("attach failed"); |
| |
| SetExitStatus(-1, error.AsCString()); |
| } |
| } else { |
| SetNextEventAction(new Process::AttachCompletionHandler( |
| this, attach_info.GetResumeCount())); |
| StartPrivateStateThread(); |
| } |
| return error; |
| } |
| } else { |
| ProcessInstanceInfoList process_infos; |
| PlatformSP platform_sp(GetTarget().GetPlatform()); |
| |
| if (platform_sp) { |
| ProcessInstanceInfoMatch match_info; |
| match_info.GetProcessInfo() = attach_info; |
| match_info.SetNameMatchType(NameMatch::Equals); |
| platform_sp->FindProcesses(match_info, process_infos); |
| const uint32_t num_matches = process_infos.size(); |
| if (num_matches == 1) { |
| attach_pid = process_infos[0].GetProcessID(); |
| // Fall through and attach using the above process ID |
| } else { |
| match_info.GetProcessInfo().GetExecutableFile().GetPath( |
| process_name, sizeof(process_name)); |
| if (num_matches > 1) { |
| StreamString s; |
| ProcessInstanceInfo::DumpTableHeader(s, true, false); |
| for (size_t i = 0; i < num_matches; i++) { |
| process_infos[i].DumpAsTableRow( |
| s, platform_sp->GetUserIDResolver(), true, false); |
| } |
| error.SetErrorStringWithFormat( |
| "more than one process named %s:\n%s", process_name, |
| s.GetData()); |
| } else |
| error.SetErrorStringWithFormat( |
| "could not find a process named %s", process_name); |
| } |
| } else { |
| error.SetErrorString( |
| "invalid platform, can't find processes by name"); |
| return error; |
| } |
| } |
| } else { |
| error.SetErrorString("invalid process name"); |
| } |
| } |
| |
| if (attach_pid != LLDB_INVALID_PROCESS_ID) { |
| error = WillAttachToProcessWithID(attach_pid); |
| if (error.Success()) { |
| |
| if (m_public_run_lock.TrySetRunning()) { |
| // Now attach using these arguments. |
| m_should_detach = true; |
| const bool restarted = false; |
| SetPublicState(eStateAttaching, restarted); |
| error = DoAttachToProcessWithID(attach_pid, attach_info); |
| } else { |
| // This shouldn't happen |
| error.SetErrorString("failed to acquire process run lock"); |
| } |
| |
| if (error.Success()) { |
| SetNextEventAction(new Process::AttachCompletionHandler( |
| this, attach_info.GetResumeCount())); |
| StartPrivateStateThread(); |
| } else { |
| if (GetID() != LLDB_INVALID_PROCESS_ID) |
| SetID(LLDB_INVALID_PROCESS_ID); |
| |
| const char *error_string = error.AsCString(); |
| if (error_string == nullptr) |
| error_string = "attach failed"; |
| |
| SetExitStatus(-1, error_string); |
| } |
| } |
| } |
| return error; |
| } |
| |
| void Process::CompleteAttach() { |
| Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | |
| LIBLLDB_LOG_TARGET)); |
| LLDB_LOGF(log, "Process::%s()", __FUNCTION__); |
| |
| // Let the process subclass figure out at much as it can about the process |
| // before we go looking for a dynamic loader plug-in. |
| ArchSpec process_arch; |
| DidAttach(process_arch); |
| |
| if (process_arch.IsValid()) { |
| GetTarget().SetArchitecture(process_arch); |
| if (log) { |
| const char *triple_str = process_arch.GetTriple().getTriple().c_str(); |
| LLDB_LOGF(log, |
| "Process::%s replacing process architecture with DidAttach() " |
| "architecture: %s", |
| __FUNCTION__, triple_str ? triple_str : "<null>"); |
| } |
| } |
| |
| // We just attached. If we have a platform, ask it for the process |
| // architecture, and if it isn't the same as the one we've already set, |
| // switch architectures. |
| PlatformSP platform_sp(GetTarget().GetPlatform()); |
| assert(platform_sp); |
| if (platform_sp) { |
| const ArchSpec &target_arch = GetTarget().GetArchitecture(); |
| if (target_arch.IsValid() && |
| !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) { |
| ArchSpec platform_arch; |
| platform_sp = |
| platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch); |
| if (platform_sp) { |
| GetTarget().SetPlatform(platform_sp); |
| GetTarget().SetArchitecture(platform_arch); |
| LLDB_LOGF(log, |
| "Process::%s switching platform to %s and architecture " |
| "to %s based on info from attach", |
| __FUNCTION__, platform_sp->GetName().AsCString(""), |
| platform_arch.GetTriple().getTriple().c_str()); |
| } |
| } else if (!process_arch.IsValid()) { |
| ProcessInstanceInfo process_info; |
| GetProcessInfo(process_info); |
| const ArchSpec &process_arch = process_info.GetArchitecture(); |
| const ArchSpec &target_arch = GetTarget().GetArchitecture(); |
| if (process_arch.IsValid() && |
| target_arch.IsCompatibleMatch(process_arch) && |
| !target_arch.IsExactMatch(process_arch)) { |
| GetTarget().SetArchitecture(process_arch); |
| LLDB_LOGF(log, |
| "Process::%s switching architecture to %s based on info " |
| "the platform retrieved for pid %" PRIu64, |
| __FUNCTION__, process_arch.GetTriple().getTriple().c_str(), |
| GetID()); |
| } |
| } |
| } |
| |
| // We have completed the attach, now it is time to find the dynamic loader |
| // plug-in |
| DynamicLoader *dyld = GetDynamicLoader(); |
| if (dyld) { |
| dyld->DidAttach(); |
| if (log) { |
| ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); |
| LLDB_LOG(log, |
| "after DynamicLoader::DidAttach(), target " |
| "executable is {0} (using {1} plugin)", |
| exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(), |
| dyld->GetPluginName()); |
| } |
| } |
| |
| GetJITLoaders().DidAttach(); |
| |
| SystemRuntime *system_runtime = GetSystemRuntime(); |
| if (system_runtime) { |
| system_runtime->DidAttach(); |
| if (log) { |
| ModuleSP exe_module_sp = GetTarget().GetExecutableModule(); |
| LLDB_LOG(log, |
| "after SystemRuntime::DidAttach(), target " |
| "executable is {0} (using {1} plugin)", |
| exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(), |
| system_runtime->GetPluginName()); |