Path: blob/main/contrib/llvm-project/lldb/source/Target/Process.cpp
39587 views
//===-- Process.cpp -------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include <atomic>9#include <memory>10#include <mutex>11#include <optional>1213#include "llvm/ADT/ScopeExit.h"14#include "llvm/Support/ScopedPrinter.h"15#include "llvm/Support/Threading.h"1617#include "lldb/Breakpoint/BreakpointLocation.h"18#include "lldb/Breakpoint/StoppointCallbackContext.h"19#include "lldb/Core/Debugger.h"20#include "lldb/Core/Module.h"21#include "lldb/Core/ModuleSpec.h"22#include "lldb/Core/PluginManager.h"23#include "lldb/Core/Progress.h"24#include "lldb/Expression/DiagnosticManager.h"25#include "lldb/Expression/DynamicCheckerFunctions.h"26#include "lldb/Expression/UserExpression.h"27#include "lldb/Expression/UtilityFunction.h"28#include "lldb/Host/ConnectionFileDescriptor.h"29#include "lldb/Host/FileSystem.h"30#include "lldb/Host/Host.h"31#include "lldb/Host/HostInfo.h"32#include "lldb/Host/OptionParser.h"33#include "lldb/Host/Pipe.h"34#include "lldb/Host/Terminal.h"35#include "lldb/Host/ThreadLauncher.h"36#include "lldb/Interpreter/CommandInterpreter.h"37#include "lldb/Interpreter/OptionArgParser.h"38#include "lldb/Interpreter/OptionValueProperties.h"39#include "lldb/Symbol/Function.h"40#include "lldb/Symbol/Symbol.h"41#include "lldb/Target/ABI.h"42#include "lldb/Target/AssertFrameRecognizer.h"43#include "lldb/Target/DynamicLoader.h"44#include "lldb/Target/InstrumentationRuntime.h"45#include "lldb/Target/JITLoader.h"46#include "lldb/Target/JITLoaderList.h"47#include "lldb/Target/Language.h"48#include "lldb/Target/LanguageRuntime.h"49#include "lldb/Target/MemoryHistory.h"50#include "lldb/Target/MemoryRegionInfo.h"51#include "lldb/Target/OperatingSystem.h"52#include "lldb/Target/Platform.h"53#include "lldb/Target/Process.h"54#include "lldb/Target/RegisterContext.h"55#include "lldb/Target/StopInfo.h"56#include "lldb/Target/StructuredDataPlugin.h"57#include "lldb/Target/SystemRuntime.h"58#include "lldb/Target/Target.h"59#include "lldb/Target/TargetList.h"60#include "lldb/Target/Thread.h"61#include "lldb/Target/ThreadPlan.h"62#include "lldb/Target/ThreadPlanBase.h"63#include "lldb/Target/ThreadPlanCallFunction.h"64#include "lldb/Target/ThreadPlanStack.h"65#include "lldb/Target/UnixSignals.h"66#include "lldb/Target/VerboseTrapFrameRecognizer.h"67#include "lldb/Utility/AddressableBits.h"68#include "lldb/Utility/Event.h"69#include "lldb/Utility/LLDBLog.h"70#include "lldb/Utility/Log.h"71#include "lldb/Utility/NameMatches.h"72#include "lldb/Utility/ProcessInfo.h"73#include "lldb/Utility/SelectHelper.h"74#include "lldb/Utility/State.h"75#include "lldb/Utility/Timer.h"7677using namespace lldb;78using namespace lldb_private;79using namespace std::chrono;8081// Comment out line below to disable memory caching, overriding the process82// setting target.process.disable-memory-cache83#define ENABLE_MEMORY_CACHING8485#ifdef ENABLE_MEMORY_CACHING86#define DISABLE_MEM_CACHE_DEFAULT false87#else88#define DISABLE_MEM_CACHE_DEFAULT true89#endif9091class ProcessOptionValueProperties92: public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {93public:94ProcessOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}9596const Property *97GetPropertyAtIndex(size_t idx,98const ExecutionContext *exe_ctx) const override {99// When getting the value for a key from the process options, we will100// always try and grab the setting from the current process if there is101// one. Else we just use the one from this instance.102if (exe_ctx) {103Process *process = exe_ctx->GetProcessPtr();104if (process) {105ProcessOptionValueProperties *instance_properties =106static_cast<ProcessOptionValueProperties *>(107process->GetValueProperties().get());108if (this != instance_properties)109return instance_properties->ProtectedGetPropertyAtIndex(idx);110}111}112return ProtectedGetPropertyAtIndex(idx);113}114};115116class ProcessMemoryIterator {117public:118ProcessMemoryIterator(Process &process, lldb::addr_t base)119: m_process(process), m_base_addr(base) {}120121bool IsValid() { return m_is_valid; }122123uint8_t operator[](lldb::addr_t offset) {124if (!IsValid())125return 0;126127uint8_t retval = 0;128Status error;129if (0 == m_process.ReadMemory(m_base_addr + offset, &retval, 1, error)) {130m_is_valid = false;131return 0;132}133134return retval;135}136137private:138Process &m_process;139const lldb::addr_t m_base_addr;140bool m_is_valid = true;141};142143static constexpr OptionEnumValueElement g_follow_fork_mode_values[] = {144{145eFollowParent,146"parent",147"Continue tracing the parent process and detach the child.",148},149{150eFollowChild,151"child",152"Trace the child process and detach the parent.",153},154};155156#define LLDB_PROPERTIES_process157#include "TargetProperties.inc"158159enum {160#define LLDB_PROPERTIES_process161#include "TargetPropertiesEnum.inc"162ePropertyExperimental,163};164165#define LLDB_PROPERTIES_process_experimental166#include "TargetProperties.inc"167168enum {169#define LLDB_PROPERTIES_process_experimental170#include "TargetPropertiesEnum.inc"171};172173class ProcessExperimentalOptionValueProperties174: public Cloneable<ProcessExperimentalOptionValueProperties,175OptionValueProperties> {176public:177ProcessExperimentalOptionValueProperties()178: Cloneable(Properties::GetExperimentalSettingsName()) {}179};180181ProcessExperimentalProperties::ProcessExperimentalProperties()182: Properties(OptionValuePropertiesSP(183new ProcessExperimentalOptionValueProperties())) {184m_collection_sp->Initialize(g_process_experimental_properties);185}186187ProcessProperties::ProcessProperties(lldb_private::Process *process)188: Properties(),189m_process(process) // Can be nullptr for global ProcessProperties190{191if (process == nullptr) {192// Global process properties, set them up one time193m_collection_sp = std::make_shared<ProcessOptionValueProperties>("process");194m_collection_sp->Initialize(g_process_properties);195m_collection_sp->AppendProperty(196"thread", "Settings specific to threads.", true,197Thread::GetGlobalProperties().GetValueProperties());198} else {199m_collection_sp =200OptionValueProperties::CreateLocalCopy(Process::GetGlobalProperties());201m_collection_sp->SetValueChangedCallback(202ePropertyPythonOSPluginPath,203[this] { m_process->LoadOperatingSystemPlugin(true); });204}205206m_experimental_properties_up =207std::make_unique<ProcessExperimentalProperties>();208m_collection_sp->AppendProperty(209Properties::GetExperimentalSettingsName(),210"Experimental settings - setting these won't produce "211"errors if the setting is not present.",212true, m_experimental_properties_up->GetValueProperties());213}214215ProcessProperties::~ProcessProperties() = default;216217bool ProcessProperties::GetDisableMemoryCache() const {218const uint32_t idx = ePropertyDisableMemCache;219return GetPropertyAtIndexAs<bool>(220idx, g_process_properties[idx].default_uint_value != 0);221}222223uint64_t ProcessProperties::GetMemoryCacheLineSize() const {224const uint32_t idx = ePropertyMemCacheLineSize;225return GetPropertyAtIndexAs<uint64_t>(226idx, g_process_properties[idx].default_uint_value);227}228229Args ProcessProperties::GetExtraStartupCommands() const {230Args args;231const uint32_t idx = ePropertyExtraStartCommand;232m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);233return args;234}235236void ProcessProperties::SetExtraStartupCommands(const Args &args) {237const uint32_t idx = ePropertyExtraStartCommand;238m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);239}240241FileSpec ProcessProperties::GetPythonOSPluginPath() const {242const uint32_t idx = ePropertyPythonOSPluginPath;243return GetPropertyAtIndexAs<FileSpec>(idx, {});244}245246uint32_t ProcessProperties::GetVirtualAddressableBits() const {247const uint32_t idx = ePropertyVirtualAddressableBits;248return GetPropertyAtIndexAs<uint64_t>(249idx, g_process_properties[idx].default_uint_value);250}251252void ProcessProperties::SetVirtualAddressableBits(uint32_t bits) {253const uint32_t idx = ePropertyVirtualAddressableBits;254SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));255}256257uint32_t ProcessProperties::GetHighmemVirtualAddressableBits() const {258const uint32_t idx = ePropertyHighmemVirtualAddressableBits;259return GetPropertyAtIndexAs<uint64_t>(260idx, g_process_properties[idx].default_uint_value);261}262263void ProcessProperties::SetHighmemVirtualAddressableBits(uint32_t bits) {264const uint32_t idx = ePropertyHighmemVirtualAddressableBits;265SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));266}267268void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {269const uint32_t idx = ePropertyPythonOSPluginPath;270SetPropertyAtIndex(idx, file);271}272273bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {274const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;275return GetPropertyAtIndexAs<bool>(276idx, g_process_properties[idx].default_uint_value != 0);277}278279void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {280const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;281SetPropertyAtIndex(idx, ignore);282}283284bool ProcessProperties::GetUnwindOnErrorInExpressions() const {285const uint32_t idx = ePropertyUnwindOnErrorInExpressions;286return GetPropertyAtIndexAs<bool>(287idx, g_process_properties[idx].default_uint_value != 0);288}289290void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {291const uint32_t idx = ePropertyUnwindOnErrorInExpressions;292SetPropertyAtIndex(idx, ignore);293}294295bool ProcessProperties::GetStopOnSharedLibraryEvents() const {296const uint32_t idx = ePropertyStopOnSharedLibraryEvents;297return GetPropertyAtIndexAs<bool>(298idx, g_process_properties[idx].default_uint_value != 0);299}300301void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {302const uint32_t idx = ePropertyStopOnSharedLibraryEvents;303SetPropertyAtIndex(idx, stop);304}305306bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const {307const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;308return GetPropertyAtIndexAs<bool>(309idx, g_process_properties[idx].default_uint_value != 0);310}311312void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable) {313const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;314SetPropertyAtIndex(idx, disable);315m_process->Flush();316}317318bool ProcessProperties::GetDetachKeepsStopped() const {319const uint32_t idx = ePropertyDetachKeepsStopped;320return GetPropertyAtIndexAs<bool>(321idx, g_process_properties[idx].default_uint_value != 0);322}323324void ProcessProperties::SetDetachKeepsStopped(bool stop) {325const uint32_t idx = ePropertyDetachKeepsStopped;326SetPropertyAtIndex(idx, stop);327}328329bool ProcessProperties::GetWarningsOptimization() const {330const uint32_t idx = ePropertyWarningOptimization;331return GetPropertyAtIndexAs<bool>(332idx, g_process_properties[idx].default_uint_value != 0);333}334335bool ProcessProperties::GetWarningsUnsupportedLanguage() const {336const uint32_t idx = ePropertyWarningUnsupportedLanguage;337return GetPropertyAtIndexAs<bool>(338idx, g_process_properties[idx].default_uint_value != 0);339}340341bool ProcessProperties::GetStopOnExec() const {342const uint32_t idx = ePropertyStopOnExec;343return GetPropertyAtIndexAs<bool>(344idx, g_process_properties[idx].default_uint_value != 0);345}346347std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {348const uint32_t idx = ePropertyUtilityExpressionTimeout;349uint64_t value = GetPropertyAtIndexAs<uint64_t>(350idx, g_process_properties[idx].default_uint_value);351return std::chrono::seconds(value);352}353354std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {355const uint32_t idx = ePropertyInterruptTimeout;356uint64_t value = GetPropertyAtIndexAs<uint64_t>(357idx, g_process_properties[idx].default_uint_value);358return std::chrono::seconds(value);359}360361bool ProcessProperties::GetSteppingRunsAllThreads() const {362const uint32_t idx = ePropertySteppingRunsAllThreads;363return GetPropertyAtIndexAs<bool>(364idx, g_process_properties[idx].default_uint_value != 0);365}366367bool ProcessProperties::GetOSPluginReportsAllThreads() const {368const bool fail_value = true;369const Property *exp_property =370m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);371OptionValueProperties *exp_values =372exp_property->GetValue()->GetAsProperties();373if (!exp_values)374return fail_value;375376return exp_values377->GetPropertyAtIndexAs<bool>(ePropertyOSPluginReportsAllThreads)378.value_or(fail_value);379}380381void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {382const Property *exp_property =383m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);384OptionValueProperties *exp_values =385exp_property->GetValue()->GetAsProperties();386if (exp_values)387exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,388does_report);389}390391FollowForkMode ProcessProperties::GetFollowForkMode() const {392const uint32_t idx = ePropertyFollowForkMode;393return GetPropertyAtIndexAs<FollowForkMode>(394idx, static_cast<FollowForkMode>(395g_process_properties[idx].default_uint_value));396}397398ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,399llvm::StringRef plugin_name,400ListenerSP listener_sp,401const FileSpec *crash_file_path,402bool can_connect) {403static uint32_t g_process_unique_id = 0;404405ProcessSP process_sp;406ProcessCreateInstance create_callback = nullptr;407if (!plugin_name.empty()) {408create_callback =409PluginManager::GetProcessCreateCallbackForPluginName(plugin_name);410if (create_callback) {411process_sp = create_callback(target_sp, listener_sp, crash_file_path,412can_connect);413if (process_sp) {414if (process_sp->CanDebug(target_sp, true)) {415process_sp->m_process_unique_id = ++g_process_unique_id;416} else417process_sp.reset();418}419}420} else {421for (uint32_t idx = 0;422(create_callback =423PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;424++idx) {425process_sp = create_callback(target_sp, listener_sp, crash_file_path,426can_connect);427if (process_sp) {428if (process_sp->CanDebug(target_sp, false)) {429process_sp->m_process_unique_id = ++g_process_unique_id;430break;431} else432process_sp.reset();433}434}435}436return process_sp;437}438439llvm::StringRef Process::GetStaticBroadcasterClass() {440static constexpr llvm::StringLiteral class_name("lldb.process");441return class_name;442}443444Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)445: Process(target_sp, listener_sp, UnixSignals::CreateForHost()) {446// This constructor just delegates to the full Process constructor,447// defaulting to using the Host's UnixSignals.448}449450Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,451const UnixSignalsSP &unix_signals_sp)452: ProcessProperties(this),453Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),454Process::GetStaticBroadcasterClass().str()),455m_target_wp(target_sp), m_public_state(eStateUnloaded),456m_private_state(eStateUnloaded),457m_private_state_broadcaster(nullptr,458"lldb.process.internal_state_broadcaster"),459m_private_state_control_broadcaster(460nullptr, "lldb.process.internal_state_control_broadcaster"),461m_private_state_listener_sp(462Listener::MakeListener("lldb.process.internal_state_listener")),463m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),464m_thread_id_to_index_id_map(), m_exit_status(-1),465m_thread_list_real(*this), m_thread_list(*this), m_thread_plans(*this),466m_extended_thread_list(*this), m_extended_thread_stop_id(0),467m_queue_list(this), m_queue_list_stop_id(0),468m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),469m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),470m_stdin_forward(false), m_stdout_data(), m_stderr_data(),471m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),472m_memory_cache(*this), m_allocated_memory_cache(*this),473m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),474m_private_run_lock(), m_currently_handling_do_on_removals(false),475m_resume_requested(false), m_finalizing(false), m_destructing(false),476m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),477m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),478m_can_interpret_function_calls(false), m_run_thread_plan_lock(),479m_can_jit(eCanJITDontKnow) {480CheckInWithManager();481482Log *log = GetLog(LLDBLog::Object);483LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));484485if (!m_unix_signals_sp)486m_unix_signals_sp = std::make_shared<UnixSignals>();487488SetEventName(eBroadcastBitStateChanged, "state-changed");489SetEventName(eBroadcastBitInterrupt, "interrupt");490SetEventName(eBroadcastBitSTDOUT, "stdout-available");491SetEventName(eBroadcastBitSTDERR, "stderr-available");492SetEventName(eBroadcastBitProfileData, "profile-data-available");493SetEventName(eBroadcastBitStructuredData, "structured-data-available");494495m_private_state_control_broadcaster.SetEventName(496eBroadcastInternalStateControlStop, "control-stop");497m_private_state_control_broadcaster.SetEventName(498eBroadcastInternalStateControlPause, "control-pause");499m_private_state_control_broadcaster.SetEventName(500eBroadcastInternalStateControlResume, "control-resume");501502// The listener passed into process creation is the primary listener:503// It always listens for all the event bits for Process:504SetPrimaryListener(listener_sp);505506m_private_state_listener_sp->StartListeningForEvents(507&m_private_state_broadcaster,508eBroadcastBitStateChanged | eBroadcastBitInterrupt);509510m_private_state_listener_sp->StartListeningForEvents(511&m_private_state_control_broadcaster,512eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |513eBroadcastInternalStateControlResume);514// We need something valid here, even if just the default UnixSignalsSP.515assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");516517// Allow the platform to override the default cache line size518OptionValueSP value_sp =519m_collection_sp->GetPropertyAtIndex(ePropertyMemCacheLineSize)520->GetValue();521uint64_t platform_cache_line_size =522target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();523if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)524value_sp->SetValueAs(platform_cache_line_size);525526// FIXME: Frame recognizer registration should not be done in Target.527// We should have a plugin do the registration instead, for example, a528// common C LanguageRuntime plugin.529RegisterAssertFrameRecognizer(this);530RegisterVerboseTrapFrameRecognizer(*this);531}532533Process::~Process() {534Log *log = GetLog(LLDBLog::Object);535LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));536StopPrivateStateThread();537538// ThreadList::Clear() will try to acquire this process's mutex, so539// explicitly clear the thread list here to ensure that the mutex is not540// destroyed before the thread list.541m_thread_list.Clear();542}543544ProcessProperties &Process::GetGlobalProperties() {545// NOTE: intentional leak so we don't crash if global destructor chain gets546// called as other threads still use the result of this function547static ProcessProperties *g_settings_ptr =548new ProcessProperties(nullptr);549return *g_settings_ptr;550}551552void Process::Finalize(bool destructing) {553if (m_finalizing.exchange(true))554return;555if (destructing)556m_destructing.exchange(true);557558// Destroy the process. This will call the virtual function DoDestroy under559// the hood, giving our derived class a chance to do the ncessary tear down.560DestroyImpl(false);561562// Clear our broadcaster before we proceed with destroying563Broadcaster::Clear();564565// Do any cleanup needed prior to being destructed... Subclasses that566// override this method should call this superclass method as well.567568// We need to destroy the loader before the derived Process class gets569// destroyed since it is very likely that undoing the loader will require570// access to the real process.571m_dynamic_checkers_up.reset();572m_abi_sp.reset();573m_os_up.reset();574m_system_runtime_up.reset();575m_dyld_up.reset();576m_jit_loaders_up.reset();577m_thread_plans.Clear();578m_thread_list_real.Destroy();579m_thread_list.Destroy();580m_extended_thread_list.Destroy();581m_queue_list.Clear();582m_queue_list_stop_id = 0;583m_watchpoint_resource_list.Clear();584std::vector<Notifications> empty_notifications;585m_notifications.swap(empty_notifications);586m_image_tokens.clear();587m_memory_cache.Clear();588m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);589{590std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);591m_language_runtimes.clear();592}593m_instrumentation_runtimes.clear();594m_next_event_action_up.reset();595// Clear the last natural stop ID since it has a strong reference to this596// process597m_mod_id.SetStopEventForLastNaturalStopID(EventSP());598// We have to be very careful here as the m_private_state_listener might599// contain events that have ProcessSP values in them which can keep this600// process around forever. These events need to be cleared out.601m_private_state_listener_sp->Clear();602m_public_run_lock.TrySetRunning(); // This will do nothing if already locked603m_public_run_lock.SetStopped();604m_private_run_lock.TrySetRunning(); // This will do nothing if already locked605m_private_run_lock.SetStopped();606m_structured_data_plugin_map.clear();607}608609void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {610m_notifications.push_back(callbacks);611if (callbacks.initialize != nullptr)612callbacks.initialize(callbacks.baton, this);613}614615bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {616std::vector<Notifications>::iterator pos, end = m_notifications.end();617for (pos = m_notifications.begin(); pos != end; ++pos) {618if (pos->baton == callbacks.baton &&619pos->initialize == callbacks.initialize &&620pos->process_state_changed == callbacks.process_state_changed) {621m_notifications.erase(pos);622return true;623}624}625return false;626}627628void Process::SynchronouslyNotifyStateChanged(StateType state) {629std::vector<Notifications>::iterator notification_pos,630notification_end = m_notifications.end();631for (notification_pos = m_notifications.begin();632notification_pos != notification_end; ++notification_pos) {633if (notification_pos->process_state_changed)634notification_pos->process_state_changed(notification_pos->baton, this,635state);636}637}638639// FIXME: We need to do some work on events before the general Listener sees640// them.641// For instance if we are continuing from a breakpoint, we need to ensure that642// we do the little "insert real insn, step & stop" trick. But we can't do643// that when the event is delivered by the broadcaster - since that is done on644// the thread that is waiting for new events, so if we needed more than one645// event for our handling, we would stall. So instead we do it when we fetch646// the event off of the queue.647//648649StateType Process::GetNextEvent(EventSP &event_sp) {650StateType state = eStateInvalid;651652if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,653std::chrono::seconds(0)) &&654event_sp)655state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());656657return state;658}659660void Process::SyncIOHandler(uint32_t iohandler_id,661const Timeout<std::micro> &timeout) {662// don't sync (potentially context switch) in case where there is no process663// IO664if (!ProcessIOHandlerExists())665return;666667auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);668669Log *log = GetLog(LLDBLog::Process);670if (Result) {671LLDB_LOG(672log,673"waited from m_iohandler_sync to change from {0}. New value is {1}.",674iohandler_id, *Result);675} else {676LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",677iohandler_id);678}679}680681StateType Process::WaitForProcessToStop(682const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,683ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,684SelectMostRelevant select_most_relevant) {685// We can't just wait for a "stopped" event, because the stopped event may686// have restarted the target. We have to actually check each event, and in687// the case of a stopped event check the restarted flag on the event.688if (event_sp_ptr)689event_sp_ptr->reset();690StateType state = GetState();691// If we are exited or detached, we won't ever get back to any other valid692// state...693if (state == eStateDetached || state == eStateExited)694return state;695696Log *log = GetLog(LLDBLog::Process);697LLDB_LOG(log, "timeout = {0}", timeout);698699if (!wait_always && StateIsStoppedState(state, true) &&700StateIsStoppedState(GetPrivateState(), true)) {701LLDB_LOGF(log,702"Process::%s returning without waiting for events; process "703"private and public states are already 'stopped'.",704__FUNCTION__);705// We need to toggle the run lock as this won't get done in706// SetPublicState() if the process is hijacked.707if (hijack_listener_sp && use_run_lock)708m_public_run_lock.SetStopped();709return state;710}711712while (state != eStateInvalid) {713EventSP event_sp;714state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);715if (event_sp_ptr && event_sp)716*event_sp_ptr = event_sp;717718bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);719Process::HandleProcessStateChangedEvent(720event_sp, stream, select_most_relevant, pop_process_io_handler);721722switch (state) {723case eStateCrashed:724case eStateDetached:725case eStateExited:726case eStateUnloaded:727// We need to toggle the run lock as this won't get done in728// SetPublicState() if the process is hijacked.729if (hijack_listener_sp && use_run_lock)730m_public_run_lock.SetStopped();731return state;732case eStateStopped:733if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))734continue;735else {736// We need to toggle the run lock as this won't get done in737// SetPublicState() if the process is hijacked.738if (hijack_listener_sp && use_run_lock)739m_public_run_lock.SetStopped();740return state;741}742default:743continue;744}745}746return state;747}748749bool Process::HandleProcessStateChangedEvent(750const EventSP &event_sp, Stream *stream,751SelectMostRelevant select_most_relevant,752bool &pop_process_io_handler) {753const bool handle_pop = pop_process_io_handler;754755pop_process_io_handler = false;756ProcessSP process_sp =757Process::ProcessEventData::GetProcessFromEvent(event_sp.get());758759if (!process_sp)760return false;761762StateType event_state =763Process::ProcessEventData::GetStateFromEvent(event_sp.get());764if (event_state == eStateInvalid)765return false;766767switch (event_state) {768case eStateInvalid:769case eStateUnloaded:770case eStateAttaching:771case eStateLaunching:772case eStateStepping:773case eStateDetached:774if (stream)775stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),776StateAsCString(event_state));777if (event_state == eStateDetached)778pop_process_io_handler = true;779break;780781case eStateConnected:782case eStateRunning:783// Don't be chatty when we run...784break;785786case eStateExited:787if (stream)788process_sp->GetStatus(*stream);789pop_process_io_handler = true;790break;791792case eStateStopped:793case eStateCrashed:794case eStateSuspended:795// Make sure the program hasn't been auto-restarted:796if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {797if (stream) {798size_t num_reasons =799Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());800if (num_reasons > 0) {801// FIXME: Do we want to report this, or would that just be annoyingly802// chatty?803if (num_reasons == 1) {804const char *reason =805Process::ProcessEventData::GetRestartedReasonAtIndex(806event_sp.get(), 0);807stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",808process_sp->GetID(),809reason ? reason : "<UNKNOWN REASON>");810} else {811stream->Printf("Process %" PRIu64812" stopped and restarted, reasons:\n",813process_sp->GetID());814815for (size_t i = 0; i < num_reasons; i++) {816const char *reason =817Process::ProcessEventData::GetRestartedReasonAtIndex(818event_sp.get(), i);819stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");820}821}822}823}824} else {825StopInfoSP curr_thread_stop_info_sp;826// Lock the thread list so it doesn't change on us, this is the scope for827// the locker:828{829ThreadList &thread_list = process_sp->GetThreadList();830std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());831832ThreadSP curr_thread(thread_list.GetSelectedThread());833ThreadSP thread;834StopReason curr_thread_stop_reason = eStopReasonInvalid;835bool prefer_curr_thread = false;836if (curr_thread && curr_thread->IsValid()) {837curr_thread_stop_reason = curr_thread->GetStopReason();838switch (curr_thread_stop_reason) {839case eStopReasonNone:840case eStopReasonInvalid:841// Don't prefer the current thread if it didn't stop for a reason.842break;843case eStopReasonSignal: {844// We need to do the same computation we do for other threads845// below in case the current thread happens to be the one that846// stopped for the no-stop signal.847uint64_t signo = curr_thread->GetStopInfo()->GetValue();848if (process_sp->GetUnixSignals()->GetShouldStop(signo))849prefer_curr_thread = true;850} break;851default:852prefer_curr_thread = true;853break;854}855curr_thread_stop_info_sp = curr_thread->GetStopInfo();856}857858if (!prefer_curr_thread) {859// Prefer a thread that has just completed its plan over another860// thread as current thread.861ThreadSP plan_thread;862ThreadSP other_thread;863864const size_t num_threads = thread_list.GetSize();865size_t i;866for (i = 0; i < num_threads; ++i) {867thread = thread_list.GetThreadAtIndex(i);868StopReason thread_stop_reason = thread->GetStopReason();869switch (thread_stop_reason) {870case eStopReasonInvalid:871case eStopReasonNone:872break;873874case eStopReasonSignal: {875// Don't select a signal thread if we weren't going to stop at876// that signal. We have to have had another reason for stopping877// here, and the user doesn't want to see this thread.878uint64_t signo = thread->GetStopInfo()->GetValue();879if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {880if (!other_thread)881other_thread = thread;882}883break;884}885case eStopReasonTrace:886case eStopReasonBreakpoint:887case eStopReasonWatchpoint:888case eStopReasonException:889case eStopReasonExec:890case eStopReasonFork:891case eStopReasonVFork:892case eStopReasonVForkDone:893case eStopReasonThreadExiting:894case eStopReasonInstrumentation:895case eStopReasonProcessorTrace:896if (!other_thread)897other_thread = thread;898break;899case eStopReasonPlanComplete:900if (!plan_thread)901plan_thread = thread;902break;903}904}905if (plan_thread)906thread_list.SetSelectedThreadByID(plan_thread->GetID());907else if (other_thread)908thread_list.SetSelectedThreadByID(other_thread->GetID());909else {910if (curr_thread && curr_thread->IsValid())911thread = curr_thread;912else913thread = thread_list.GetThreadAtIndex(0);914915if (thread)916thread_list.SetSelectedThreadByID(thread->GetID());917}918}919}920// Drop the ThreadList mutex by here, since GetThreadStatus below might921// have to run code, e.g. for Data formatters, and if we hold the922// ThreadList mutex, then the process is going to have a hard time923// restarting the process.924if (stream) {925Debugger &debugger = process_sp->GetTarget().GetDebugger();926if (debugger.GetTargetList().GetSelectedTarget().get() ==927&process_sp->GetTarget()) {928ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();929930if (!thread_sp || !thread_sp->IsValid())931return false;932933const bool only_threads_with_stop_reason = true;934const uint32_t start_frame =935thread_sp->GetSelectedFrameIndex(select_most_relevant);936const uint32_t num_frames = 1;937const uint32_t num_frames_with_source = 1;938const bool stop_format = true;939940process_sp->GetStatus(*stream);941process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,942start_frame, num_frames,943num_frames_with_source,944stop_format);945if (curr_thread_stop_info_sp) {946lldb::addr_t crashing_address;947ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(948curr_thread_stop_info_sp, &crashing_address);949if (valobj_sp) {950const ValueObject::GetExpressionPathFormat format =951ValueObject::GetExpressionPathFormat::952eGetExpressionPathFormatHonorPointers;953stream->PutCString("Likely cause: ");954valobj_sp->GetExpressionPath(*stream, format);955stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);956}957}958} else {959uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(960process_sp->GetTarget().shared_from_this());961if (target_idx != UINT32_MAX)962stream->Printf("Target %d: (", target_idx);963else964stream->Printf("Target <unknown index>: (");965process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);966stream->Printf(") stopped.\n");967}968}969970// Pop the process IO handler971pop_process_io_handler = true;972}973break;974}975976if (handle_pop && pop_process_io_handler)977process_sp->PopProcessIOHandler();978979return true;980}981982bool Process::HijackProcessEvents(ListenerSP listener_sp) {983if (listener_sp) {984return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |985eBroadcastBitInterrupt);986} else987return false;988}989990void Process::RestoreProcessEvents() { RestoreBroadcaster(); }991992StateType Process::GetStateChangedEvents(EventSP &event_sp,993const Timeout<std::micro> &timeout,994ListenerSP hijack_listener_sp) {995Log *log = GetLog(LLDBLog::Process);996LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);997998ListenerSP listener_sp = hijack_listener_sp;999if (!listener_sp)1000listener_sp = GetPrimaryListener();10011002StateType state = eStateInvalid;1003if (listener_sp->GetEventForBroadcasterWithType(1004this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,1005timeout)) {1006if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)1007state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());1008else1009LLDB_LOG(log, "got no event or was interrupted.");1010}10111012LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);1013return state;1014}10151016Event *Process::PeekAtStateChangedEvents() {1017Log *log = GetLog(LLDBLog::Process);10181019LLDB_LOGF(log, "Process::%s...", __FUNCTION__);10201021Event *event_ptr;1022event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(1023this, eBroadcastBitStateChanged);1024if (log) {1025if (event_ptr) {1026LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,1027StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));1028} else {1029LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);1030}1031}1032return event_ptr;1033}10341035StateType1036Process::GetStateChangedEventsPrivate(EventSP &event_sp,1037const Timeout<std::micro> &timeout) {1038Log *log = GetLog(LLDBLog::Process);1039LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);10401041StateType state = eStateInvalid;1042if (m_private_state_listener_sp->GetEventForBroadcasterWithType(1043&m_private_state_broadcaster,1044eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,1045timeout))1046if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)1047state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());10481049LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,1050state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));1051return state;1052}10531054bool Process::GetEventsPrivate(EventSP &event_sp,1055const Timeout<std::micro> &timeout,1056bool control_only) {1057Log *log = GetLog(LLDBLog::Process);1058LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);10591060if (control_only)1061return m_private_state_listener_sp->GetEventForBroadcaster(1062&m_private_state_control_broadcaster, event_sp, timeout);1063else1064return m_private_state_listener_sp->GetEvent(event_sp, timeout);1065}10661067bool Process::IsRunning() const {1068return StateIsRunningState(m_public_state.GetValue());1069}10701071int Process::GetExitStatus() {1072std::lock_guard<std::mutex> guard(m_exit_status_mutex);10731074if (m_public_state.GetValue() == eStateExited)1075return m_exit_status;1076return -1;1077}10781079const char *Process::GetExitDescription() {1080std::lock_guard<std::mutex> guard(m_exit_status_mutex);10811082if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())1083return m_exit_string.c_str();1084return nullptr;1085}10861087bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {1088// Use a mutex to protect setting the exit status.1089std::lock_guard<std::mutex> guard(m_exit_status_mutex);10901091Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1092LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",1093GetPluginName(), status, exit_string);10941095// We were already in the exited state1096if (m_private_state.GetValue() == eStateExited) {1097LLDB_LOG(1098log,1099"(plugin = {0}) ignoring exit status because state was already set "1100"to eStateExited",1101GetPluginName());1102return false;1103}11041105m_exit_status = status;1106if (!exit_string.empty())1107m_exit_string = exit_string.str();1108else1109m_exit_string.clear();11101111// Clear the last natural stop ID since it has a strong reference to this1112// process1113m_mod_id.SetStopEventForLastNaturalStopID(EventSP());11141115SetPrivateState(eStateExited);11161117// Allow subclasses to do some cleanup1118DidExit();11191120return true;1121}11221123bool Process::IsAlive() {1124switch (m_private_state.GetValue()) {1125case eStateConnected:1126case eStateAttaching:1127case eStateLaunching:1128case eStateStopped:1129case eStateRunning:1130case eStateStepping:1131case eStateCrashed:1132case eStateSuspended:1133return true;1134default:1135return false;1136}1137}11381139// This static callback can be used to watch for local child processes on the1140// current host. The child process exits, the process will be found in the1141// global target list (we want to be completely sure that the1142// lldb_private::Process doesn't go away before we can deliver the signal.1143bool Process::SetProcessExitStatus(1144lldb::pid_t pid, bool exited,1145int signo, // Zero for no signal1146int exit_status // Exit value of process if signal is zero1147) {1148Log *log = GetLog(LLDBLog::Process);1149LLDB_LOGF(log,1150"Process::SetProcessExitStatus (pid=%" PRIu641151", exited=%i, signal=%i, exit_status=%i)\n",1152pid, exited, signo, exit_status);11531154if (exited) {1155TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));1156if (target_sp) {1157ProcessSP process_sp(target_sp->GetProcessSP());1158if (process_sp) {1159llvm::StringRef signal_str =1160process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);1161process_sp->SetExitStatus(exit_status, signal_str);1162}1163}1164return true;1165}1166return false;1167}11681169bool Process::UpdateThreadList(ThreadList &old_thread_list,1170ThreadList &new_thread_list) {1171m_thread_plans.ClearThreadCache();1172return DoUpdateThreadList(old_thread_list, new_thread_list);1173}11741175void Process::UpdateThreadListIfNeeded() {1176const uint32_t stop_id = GetStopID();1177if (m_thread_list.GetSize(false) == 0 ||1178stop_id != m_thread_list.GetStopID()) {1179bool clear_unused_threads = true;1180const StateType state = GetPrivateState();1181if (StateIsStoppedState(state, true)) {1182std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());1183m_thread_list.SetStopID(stop_id);11841185// m_thread_list does have its own mutex, but we need to hold onto the1186// mutex between the call to UpdateThreadList(...) and the1187// os->UpdateThreadList(...) so it doesn't change on us1188ThreadList &old_thread_list = m_thread_list;1189ThreadList real_thread_list(*this);1190ThreadList new_thread_list(*this);1191// Always update the thread list with the protocol specific thread list,1192// but only update if "true" is returned1193if (UpdateThreadList(m_thread_list_real, real_thread_list)) {1194// Don't call into the OperatingSystem to update the thread list if we1195// are shutting down, since that may call back into the SBAPI's,1196// requiring the API lock which is already held by whoever is shutting1197// us down, causing a deadlock.1198OperatingSystem *os = GetOperatingSystem();1199if (os && !m_destroy_in_process) {1200// Clear any old backing threads where memory threads might have been1201// backed by actual threads from the lldb_private::Process subclass1202size_t num_old_threads = old_thread_list.GetSize(false);1203for (size_t i = 0; i < num_old_threads; ++i)1204old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();1205// See if the OS plugin reports all threads. If it does, then1206// it is safe to clear unseen thread's plans here. Otherwise we1207// should preserve them in case they show up again:1208clear_unused_threads = GetOSPluginReportsAllThreads();12091210// Turn off dynamic types to ensure we don't run any expressions.1211// Objective-C can run an expression to determine if a SBValue is a1212// dynamic type or not and we need to avoid this. OperatingSystem1213// plug-ins can't run expressions that require running code...12141215Target &target = GetTarget();1216const lldb::DynamicValueType saved_prefer_dynamic =1217target.GetPreferDynamicValue();1218if (saved_prefer_dynamic != lldb::eNoDynamicValues)1219target.SetPreferDynamicValue(lldb::eNoDynamicValues);12201221// Now let the OperatingSystem plug-in update the thread list12221223os->UpdateThreadList(1224old_thread_list, // Old list full of threads created by OS plug-in1225real_thread_list, // The actual thread list full of threads1226// created by each lldb_private::Process1227// subclass1228new_thread_list); // The new thread list that we will show to the1229// user that gets filled in12301231if (saved_prefer_dynamic != lldb::eNoDynamicValues)1232target.SetPreferDynamicValue(saved_prefer_dynamic);1233} else {1234// No OS plug-in, the new thread list is the same as the real thread1235// list.1236new_thread_list = real_thread_list;1237}12381239m_thread_list_real.Update(real_thread_list);1240m_thread_list.Update(new_thread_list);1241m_thread_list.SetStopID(stop_id);12421243if (GetLastNaturalStopID() != m_extended_thread_stop_id) {1244// Clear any extended threads that we may have accumulated previously1245m_extended_thread_list.Clear();1246m_extended_thread_stop_id = GetLastNaturalStopID();12471248m_queue_list.Clear();1249m_queue_list_stop_id = GetLastNaturalStopID();1250}1251}1252// Now update the plan stack map.1253// If we do have an OS plugin, any absent real threads in the1254// m_thread_list have already been removed from the ThreadPlanStackMap.1255// So any remaining threads are OS Plugin threads, and those we want to1256// preserve in case they show up again.1257m_thread_plans.Update(m_thread_list, clear_unused_threads);1258}1259}1260}12611262ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {1263return m_thread_plans.Find(tid);1264}12651266bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {1267return m_thread_plans.PrunePlansForTID(tid);1268}12691270void Process::PruneThreadPlans() {1271m_thread_plans.Update(GetThreadList(), true, false);1272}12731274bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,1275lldb::DescriptionLevel desc_level,1276bool internal, bool condense_trivial,1277bool skip_unreported_plans) {1278return m_thread_plans.DumpPlansForTID(1279strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);1280}1281void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,1282bool internal, bool condense_trivial,1283bool skip_unreported_plans) {1284m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,1285skip_unreported_plans);1286}12871288void Process::UpdateQueueListIfNeeded() {1289if (m_system_runtime_up) {1290if (m_queue_list.GetSize() == 0 ||1291m_queue_list_stop_id != GetLastNaturalStopID()) {1292const StateType state = GetPrivateState();1293if (StateIsStoppedState(state, true)) {1294m_system_runtime_up->PopulateQueueList(m_queue_list);1295m_queue_list_stop_id = GetLastNaturalStopID();1296}1297}1298}1299}13001301ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {1302OperatingSystem *os = GetOperatingSystem();1303if (os)1304return os->CreateThread(tid, context);1305return ThreadSP();1306}13071308uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {1309return AssignIndexIDToThread(thread_id);1310}13111312bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {1313return (m_thread_id_to_index_id_map.find(thread_id) !=1314m_thread_id_to_index_id_map.end());1315}13161317uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {1318uint32_t result = 0;1319std::map<uint64_t, uint32_t>::iterator iterator =1320m_thread_id_to_index_id_map.find(thread_id);1321if (iterator == m_thread_id_to_index_id_map.end()) {1322result = ++m_thread_index_id;1323m_thread_id_to_index_id_map[thread_id] = result;1324} else {1325result = iterator->second;1326}13271328return result;1329}13301331StateType Process::GetState() {1332if (CurrentThreadIsPrivateStateThread())1333return m_private_state.GetValue();1334else1335return m_public_state.GetValue();1336}13371338void Process::SetPublicState(StateType new_state, bool restarted) {1339const bool new_state_is_stopped = StateIsStoppedState(new_state, false);1340if (new_state_is_stopped) {1341// This will only set the time if the public stop time has no value, so1342// it is ok to call this multiple times. With a public stop we can't look1343// at the stop ID because many private stops might have happened, so we1344// can't check for a stop ID of zero. This allows the "statistics" command1345// to dump the time it takes to reach somewhere in your code, like a1346// breakpoint you set.1347GetTarget().GetStatistics().SetFirstPublicStopTime();1348}13491350Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1351LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",1352GetPluginName().data(), StateAsCString(new_state), restarted);1353const StateType old_state = m_public_state.GetValue();1354m_public_state.SetValue(new_state);13551356// On the transition from Run to Stopped, we unlock the writer end of the run1357// lock. The lock gets locked in Resume, which is the public API to tell the1358// program to run.1359if (!StateChangedIsExternallyHijacked()) {1360if (new_state == eStateDetached) {1361LLDB_LOGF(log,1362"(plugin = %s, state = %s) -- unlocking run lock for detach",1363GetPluginName().data(), StateAsCString(new_state));1364m_public_run_lock.SetStopped();1365} else {1366const bool old_state_is_stopped = StateIsStoppedState(old_state, false);1367if ((old_state_is_stopped != new_state_is_stopped)) {1368if (new_state_is_stopped && !restarted) {1369LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",1370GetPluginName().data(), StateAsCString(new_state));1371m_public_run_lock.SetStopped();1372}1373}1374}1375}1376}13771378Status Process::Resume() {1379Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1380LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());1381if (!m_public_run_lock.TrySetRunning()) {1382Status error("Resume request failed - process still running.");1383LLDB_LOGF(log, "(plugin = %s) -- TrySetRunning failed, not resuming.",1384GetPluginName().data());1385return error;1386}1387Status error = PrivateResume();1388if (!error.Success()) {1389// Undo running state change1390m_public_run_lock.SetStopped();1391}1392return error;1393}13941395Status Process::ResumeSynchronous(Stream *stream) {1396Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1397LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");1398if (!m_public_run_lock.TrySetRunning()) {1399Status error("Resume request failed - process still running.");1400LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");1401return error;1402}14031404ListenerSP listener_sp(1405Listener::MakeListener(ResumeSynchronousHijackListenerName.data()));1406HijackProcessEvents(listener_sp);14071408Status error = PrivateResume();1409if (error.Success()) {1410StateType state =1411WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,1412true /* use_run_lock */, SelectMostRelevantFrame);1413const bool must_be_alive =1414false; // eStateExited is ok, so this must be false1415if (!StateIsStoppedState(state, must_be_alive))1416error.SetErrorStringWithFormat(1417"process not in stopped state after synchronous resume: %s",1418StateAsCString(state));1419} else {1420// Undo running state change1421m_public_run_lock.SetStopped();1422}14231424// Undo the hijacking of process events...1425RestoreProcessEvents();14261427return error;1428}14291430bool Process::StateChangedIsExternallyHijacked() {1431if (IsHijackedForEvent(eBroadcastBitStateChanged)) {1432llvm::StringRef hijacking_name = GetHijackingListenerName();1433if (!hijacking_name.starts_with("lldb.internal"))1434return true;1435}1436return false;1437}14381439bool Process::StateChangedIsHijackedForSynchronousResume() {1440if (IsHijackedForEvent(eBroadcastBitStateChanged)) {1441llvm::StringRef hijacking_name = GetHijackingListenerName();1442if (hijacking_name == ResumeSynchronousHijackListenerName)1443return true;1444}1445return false;1446}14471448StateType Process::GetPrivateState() { return m_private_state.GetValue(); }14491450void Process::SetPrivateState(StateType new_state) {1451// Use m_destructing not m_finalizing here. If we are finalizing a process1452// that we haven't started tearing down, we'd like to be able to nicely1453// detach if asked, but that requires the event system be live. That will1454// not be true for an in-the-middle-of-being-destructed Process, since the1455// event system relies on Process::shared_from_this, which may have already1456// been destroyed.1457if (m_destructing)1458return;14591460Log *log(GetLog(LLDBLog::State | LLDBLog::Process | LLDBLog::Unwind));1461bool state_changed = false;14621463LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),1464StateAsCString(new_state));14651466std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());1467std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());14681469const StateType old_state = m_private_state.GetValueNoLock();1470state_changed = old_state != new_state;14711472const bool old_state_is_stopped = StateIsStoppedState(old_state, false);1473const bool new_state_is_stopped = StateIsStoppedState(new_state, false);1474if (old_state_is_stopped != new_state_is_stopped) {1475if (new_state_is_stopped)1476m_private_run_lock.SetStopped();1477else1478m_private_run_lock.SetRunning();1479}14801481if (state_changed) {1482m_private_state.SetValueNoLock(new_state);1483EventSP event_sp(1484new Event(eBroadcastBitStateChanged,1485new ProcessEventData(shared_from_this(), new_state)));1486if (StateIsStoppedState(new_state, false)) {1487// Note, this currently assumes that all threads in the list stop when1488// the process stops. In the future we will want to support a debugging1489// model where some threads continue to run while others are stopped.1490// When that happens we will either need a way for the thread list to1491// identify which threads are stopping or create a special thread list1492// containing only threads which actually stopped.1493//1494// The process plugin is responsible for managing the actual behavior of1495// the threads and should have stopped any threads that are going to stop1496// before we get here.1497m_thread_list.DidStop();14981499if (m_mod_id.BumpStopID() == 0)1500GetTarget().GetStatistics().SetFirstPrivateStopTime();15011502if (!m_mod_id.IsLastResumeForUserExpression())1503m_mod_id.SetStopEventForLastNaturalStopID(event_sp);1504m_memory_cache.Clear();1505LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",1506GetPluginName().data(), StateAsCString(new_state),1507m_mod_id.GetStopID());1508}15091510m_private_state_broadcaster.BroadcastEvent(event_sp);1511} else {1512LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",1513GetPluginName().data(), StateAsCString(new_state));1514}1515}15161517void Process::SetRunningUserExpression(bool on) {1518m_mod_id.SetRunningUserExpression(on);1519}15201521void Process::SetRunningUtilityFunction(bool on) {1522m_mod_id.SetRunningUtilityFunction(on);1523}15241525addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }15261527const lldb::ABISP &Process::GetABI() {1528if (!m_abi_sp)1529m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());1530return m_abi_sp;1531}15321533std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {1534std::vector<LanguageRuntime *> language_runtimes;15351536if (m_finalizing)1537return language_runtimes;15381539std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);1540// Before we pass off a copy of the language runtimes, we must make sure that1541// our collection is properly populated. It's possible that some of the1542// language runtimes were not loaded yet, either because nobody requested it1543// yet or the proper condition for loading wasn't yet met (e.g. libc++.so1544// hadn't been loaded).1545for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {1546if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))1547language_runtimes.emplace_back(runtime);1548}15491550return language_runtimes;1551}15521553LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {1554if (m_finalizing)1555return nullptr;15561557LanguageRuntime *runtime = nullptr;15581559std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);1560LanguageRuntimeCollection::iterator pos;1561pos = m_language_runtimes.find(language);1562if (pos == m_language_runtimes.end() || !pos->second) {1563lldb::LanguageRuntimeSP runtime_sp(1564LanguageRuntime::FindPlugin(this, language));15651566m_language_runtimes[language] = runtime_sp;1567runtime = runtime_sp.get();1568} else1569runtime = pos->second.get();15701571if (runtime)1572// It's possible that a language runtime can support multiple LanguageTypes,1573// for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,1574// eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the1575// primary language type and make sure that our runtime supports it.1576assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));15771578return runtime;1579}15801581bool Process::IsPossibleDynamicValue(ValueObject &in_value) {1582if (m_finalizing)1583return false;15841585if (in_value.IsDynamic())1586return false;1587LanguageType known_type = in_value.GetObjectRuntimeLanguage();15881589if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {1590LanguageRuntime *runtime = GetLanguageRuntime(known_type);1591return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;1592}15931594for (LanguageRuntime *runtime : GetLanguageRuntimes()) {1595if (runtime->CouldHaveDynamicValue(in_value))1596return true;1597}15981599return false;1600}16011602void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {1603m_dynamic_checkers_up.reset(dynamic_checkers);1604}16051606StopPointSiteList<BreakpointSite> &Process::GetBreakpointSiteList() {1607return m_breakpoint_site_list;1608}16091610const StopPointSiteList<BreakpointSite> &1611Process::GetBreakpointSiteList() const {1612return m_breakpoint_site_list;1613}16141615void Process::DisableAllBreakpointSites() {1616m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {1617// bp_site->SetEnabled(true);1618DisableBreakpointSite(bp_site);1619});1620}16211622Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {1623Status error(DisableBreakpointSiteByID(break_id));16241625if (error.Success())1626m_breakpoint_site_list.Remove(break_id);16271628return error;1629}16301631Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {1632Status error;1633BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);1634if (bp_site_sp) {1635if (bp_site_sp->IsEnabled())1636error = DisableBreakpointSite(bp_site_sp.get());1637} else {1638error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,1639break_id);1640}16411642return error;1643}16441645Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {1646Status error;1647BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);1648if (bp_site_sp) {1649if (!bp_site_sp->IsEnabled())1650error = EnableBreakpointSite(bp_site_sp.get());1651} else {1652error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,1653break_id);1654}1655return error;1656}16571658lldb::break_id_t1659Process::CreateBreakpointSite(const BreakpointLocationSP &constituent,1660bool use_hardware) {1661addr_t load_addr = LLDB_INVALID_ADDRESS;16621663bool show_error = true;1664switch (GetState()) {1665case eStateInvalid:1666case eStateUnloaded:1667case eStateConnected:1668case eStateAttaching:1669case eStateLaunching:1670case eStateDetached:1671case eStateExited:1672show_error = false;1673break;16741675case eStateStopped:1676case eStateRunning:1677case eStateStepping:1678case eStateCrashed:1679case eStateSuspended:1680show_error = IsAlive();1681break;1682}16831684// Reset the IsIndirect flag here, in case the location changes from pointing1685// to a indirect symbol to a regular symbol.1686constituent->SetIsIndirect(false);16871688if (constituent->ShouldResolveIndirectFunctions()) {1689Symbol *symbol = constituent->GetAddress().CalculateSymbolContextSymbol();1690if (symbol && symbol->IsIndirect()) {1691Status error;1692Address symbol_address = symbol->GetAddress();1693load_addr = ResolveIndirectFunction(&symbol_address, error);1694if (!error.Success() && show_error) {1695GetTarget().GetDebugger().GetErrorStream().Printf(1696"warning: failed to resolve indirect function at 0x%" PRIx641697" for breakpoint %i.%i: %s\n",1698symbol->GetLoadAddress(&GetTarget()),1699constituent->GetBreakpoint().GetID(), constituent->GetID(),1700error.AsCString() ? error.AsCString() : "unknown error");1701return LLDB_INVALID_BREAK_ID;1702}1703Address resolved_address(load_addr);1704load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());1705constituent->SetIsIndirect(true);1706} else1707load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());1708} else1709load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());17101711if (load_addr != LLDB_INVALID_ADDRESS) {1712BreakpointSiteSP bp_site_sp;17131714// Look up this breakpoint site. If it exists, then add this new1715// constituent, otherwise create a new breakpoint site and add it.17161717bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);17181719if (bp_site_sp) {1720bp_site_sp->AddConstituent(constituent);1721constituent->SetBreakpointSite(bp_site_sp);1722return bp_site_sp->GetID();1723} else {1724bp_site_sp.reset(1725new BreakpointSite(constituent, load_addr, use_hardware));1726if (bp_site_sp) {1727Status error = EnableBreakpointSite(bp_site_sp.get());1728if (error.Success()) {1729constituent->SetBreakpointSite(bp_site_sp);1730return m_breakpoint_site_list.Add(bp_site_sp);1731} else {1732if (show_error || use_hardware) {1733// Report error for setting breakpoint...1734GetTarget().GetDebugger().GetErrorStream().Printf(1735"warning: failed to set breakpoint site at 0x%" PRIx641736" for breakpoint %i.%i: %s\n",1737load_addr, constituent->GetBreakpoint().GetID(),1738constituent->GetID(),1739error.AsCString() ? error.AsCString() : "unknown error");1740}1741}1742}1743}1744}1745// We failed to enable the breakpoint1746return LLDB_INVALID_BREAK_ID;1747}17481749void Process::RemoveConstituentFromBreakpointSite(1750lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,1751BreakpointSiteSP &bp_site_sp) {1752uint32_t num_constituents =1753bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);1754if (num_constituents == 0) {1755// Don't try to disable the site if we don't have a live process anymore.1756if (IsAlive())1757DisableBreakpointSite(bp_site_sp.get());1758m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());1759}1760}17611762size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,1763uint8_t *buf) const {1764size_t bytes_removed = 0;1765StopPointSiteList<BreakpointSite> bp_sites_in_range;17661767if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,1768bp_sites_in_range)) {1769bp_sites_in_range.ForEach([bp_addr, size,1770buf](BreakpointSite *bp_site) -> void {1771if (bp_site->GetType() == BreakpointSite::eSoftware) {1772addr_t intersect_addr;1773size_t intersect_size;1774size_t opcode_offset;1775if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,1776&intersect_size, &opcode_offset)) {1777assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);1778assert(bp_addr < intersect_addr + intersect_size &&1779intersect_addr + intersect_size <= bp_addr + size);1780assert(opcode_offset + intersect_size <= bp_site->GetByteSize());1781size_t buf_offset = intersect_addr - bp_addr;1782::memcpy(buf + buf_offset,1783bp_site->GetSavedOpcodeBytes() + opcode_offset,1784intersect_size);1785}1786}1787});1788}1789return bytes_removed;1790}17911792size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {1793PlatformSP platform_sp(GetTarget().GetPlatform());1794if (platform_sp)1795return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);1796return 0;1797}17981799Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {1800Status error;1801assert(bp_site != nullptr);1802Log *log = GetLog(LLDBLog::Breakpoints);1803const addr_t bp_addr = bp_site->GetLoadAddress();1804LLDB_LOGF(1805log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,1806bp_site->GetID(), (uint64_t)bp_addr);1807if (bp_site->IsEnabled()) {1808LLDB_LOGF(1809log,1810"Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641811" -- already enabled",1812bp_site->GetID(), (uint64_t)bp_addr);1813return error;1814}18151816if (bp_addr == LLDB_INVALID_ADDRESS) {1817error.SetErrorString("BreakpointSite contains an invalid load address.");1818return error;1819}1820// Ask the lldb::Process subclass to fill in the correct software breakpoint1821// trap for the breakpoint site1822const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);18231824if (bp_opcode_size == 0) {1825error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "1826"returned zero, unable to get breakpoint "1827"trap for address 0x%" PRIx64,1828bp_addr);1829} else {1830const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();18311832if (bp_opcode_bytes == nullptr) {1833error.SetErrorString(1834"BreakpointSite doesn't contain a valid breakpoint trap opcode.");1835return error;1836}18371838// Save the original opcode by reading it1839if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,1840error) == bp_opcode_size) {1841// Write a software breakpoint in place of the original opcode1842if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==1843bp_opcode_size) {1844uint8_t verify_bp_opcode_bytes[64];1845if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,1846error) == bp_opcode_size) {1847if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,1848bp_opcode_size) == 0) {1849bp_site->SetEnabled(true);1850bp_site->SetType(BreakpointSite::eSoftware);1851LLDB_LOGF(log,1852"Process::EnableSoftwareBreakpoint (site_id = %d) "1853"addr = 0x%" PRIx64 " -- SUCCESS",1854bp_site->GetID(), (uint64_t)bp_addr);1855} else1856error.SetErrorString(1857"failed to verify the breakpoint trap in memory.");1858} else1859error.SetErrorString(1860"Unable to read memory to verify breakpoint trap.");1861} else1862error.SetErrorString("Unable to write breakpoint trap to memory.");1863} else1864error.SetErrorString("Unable to read memory at breakpoint address.");1865}1866if (log && error.Fail())1867LLDB_LOGF(1868log,1869"Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641870" -- FAILED: %s",1871bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());1872return error;1873}18741875Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {1876Status error;1877assert(bp_site != nullptr);1878Log *log = GetLog(LLDBLog::Breakpoints);1879addr_t bp_addr = bp_site->GetLoadAddress();1880lldb::user_id_t breakID = bp_site->GetID();1881LLDB_LOGF(log,1882"Process::DisableSoftwareBreakpoint (breakID = %" PRIu641883") addr = 0x%" PRIx64,1884breakID, (uint64_t)bp_addr);18851886if (bp_site->IsHardware()) {1887error.SetErrorString("Breakpoint site is a hardware breakpoint.");1888} else if (bp_site->IsEnabled()) {1889const size_t break_op_size = bp_site->GetByteSize();1890const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();1891if (break_op_size > 0) {1892// Clear a software breakpoint instruction1893uint8_t curr_break_op[8];1894assert(break_op_size <= sizeof(curr_break_op));1895bool break_op_found = false;18961897// Read the breakpoint opcode1898if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==1899break_op_size) {1900bool verify = false;1901// Make sure the breakpoint opcode exists at this address1902if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {1903break_op_found = true;1904// We found a valid breakpoint opcode at this address, now restore1905// the saved opcode.1906if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),1907break_op_size, error) == break_op_size) {1908verify = true;1909} else1910error.SetErrorString(1911"Memory write failed when restoring original opcode.");1912} else {1913error.SetErrorString(1914"Original breakpoint trap is no longer in memory.");1915// Set verify to true and so we can check if the original opcode has1916// already been restored1917verify = true;1918}19191920if (verify) {1921uint8_t verify_opcode[8];1922assert(break_op_size < sizeof(verify_opcode));1923// Verify that our original opcode made it back to the inferior1924if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==1925break_op_size) {1926// compare the memory we just read with the original opcode1927if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,1928break_op_size) == 0) {1929// SUCCESS1930bp_site->SetEnabled(false);1931LLDB_LOGF(log,1932"Process::DisableSoftwareBreakpoint (site_id = %d) "1933"addr = 0x%" PRIx64 " -- SUCCESS",1934bp_site->GetID(), (uint64_t)bp_addr);1935return error;1936} else {1937if (break_op_found)1938error.SetErrorString("Failed to restore original opcode.");1939}1940} else1941error.SetErrorString("Failed to read memory to verify that "1942"breakpoint trap was restored.");1943}1944} else1945error.SetErrorString(1946"Unable to read memory that should contain the breakpoint trap.");1947}1948} else {1949LLDB_LOGF(1950log,1951"Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641952" -- already disabled",1953bp_site->GetID(), (uint64_t)bp_addr);1954return error;1955}19561957LLDB_LOGF(1958log,1959"Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641960" -- FAILED: %s",1961bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());1962return error;1963}19641965// Uncomment to verify memory caching works after making changes to caching1966// code1967//#define VERIFY_MEMORY_READS19681969size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {1970if (ABISP abi_sp = GetABI())1971addr = abi_sp->FixAnyAddress(addr);19721973error.Clear();1974if (!GetDisableMemoryCache()) {1975#if defined(VERIFY_MEMORY_READS)1976// Memory caching is enabled, with debug verification19771978if (buf && size) {1979// Uncomment the line below to make sure memory caching is working.1980// I ran this through the test suite and got no assertions, so I am1981// pretty confident this is working well. If any changes are made to1982// memory caching, uncomment the line below and test your changes!19831984// Verify all memory reads by using the cache first, then redundantly1985// reading the same memory from the inferior and comparing to make sure1986// everything is exactly the same.1987std::string verify_buf(size, '\0');1988assert(verify_buf.size() == size);1989const size_t cache_bytes_read =1990m_memory_cache.Read(this, addr, buf, size, error);1991Status verify_error;1992const size_t verify_bytes_read =1993ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),1994verify_buf.size(), verify_error);1995assert(cache_bytes_read == verify_bytes_read);1996assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);1997assert(verify_error.Success() == error.Success());1998return cache_bytes_read;1999}2000return 0;2001#else // !defined(VERIFY_MEMORY_READS)2002// Memory caching is enabled, without debug verification20032004return m_memory_cache.Read(addr, buf, size, error);2005#endif // defined (VERIFY_MEMORY_READS)2006} else {2007// Memory caching is disabled20082009return ReadMemoryFromInferior(addr, buf, size, error);2010}2011}20122013void Process::DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr,2014const uint8_t *buf, size_t size,2015AddressRanges &matches, size_t alignment,2016size_t max_matches) {2017// Inputs are already validated in FindInMemory() functions.2018assert(buf != nullptr);2019assert(size > 0);2020assert(alignment > 0);2021assert(max_matches > 0);2022assert(start_addr != LLDB_INVALID_ADDRESS);2023assert(end_addr != LLDB_INVALID_ADDRESS);2024assert(start_addr < end_addr);20252026lldb::addr_t start = llvm::alignTo(start_addr, alignment);2027while (matches.size() < max_matches && (start + size) < end_addr) {2028const lldb::addr_t found_addr = FindInMemory(start, end_addr, buf, size);2029if (found_addr == LLDB_INVALID_ADDRESS)2030break;20312032if (found_addr % alignment) {2033// We need to check the alignment because the FindInMemory uses a special2034// algorithm to efficiently search mememory but doesn't support alignment.2035start = llvm::alignTo(start + 1, alignment);2036continue;2037}20382039matches.emplace_back(found_addr, size);2040start = found_addr + alignment;2041}2042}20432044AddressRanges Process::FindRangesInMemory(const uint8_t *buf, uint64_t size,2045const AddressRanges &ranges,2046size_t alignment, size_t max_matches,2047Status &error) {2048AddressRanges matches;2049if (buf == nullptr) {2050error.SetErrorString("buffer is null");2051return matches;2052}2053if (size == 0) {2054error.SetErrorString("buffer size is zero");2055return matches;2056}2057if (ranges.empty()) {2058error.SetErrorString("empty ranges");2059return matches;2060}2061if (alignment == 0) {2062error.SetErrorString("alignment must be greater than zero");2063return matches;2064}2065if (max_matches == 0) {2066error.SetErrorString("max_matches must be greater than zero");2067return matches;2068}20692070int resolved_ranges = 0;2071Target &target = GetTarget();2072for (size_t i = 0; i < ranges.size(); ++i) {2073if (matches.size() >= max_matches)2074break;2075const AddressRange &range = ranges[i];2076if (range.IsValid() == false)2077continue;20782079const lldb::addr_t start_addr =2080range.GetBaseAddress().GetLoadAddress(&target);2081if (start_addr == LLDB_INVALID_ADDRESS)2082continue;20832084++resolved_ranges;2085const lldb::addr_t end_addr = start_addr + range.GetByteSize();2086DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment,2087max_matches);2088}20892090if (resolved_ranges > 0)2091error.Clear();2092else2093error.SetErrorString("unable to resolve any ranges");20942095return matches;2096}20972098lldb::addr_t Process::FindInMemory(const uint8_t *buf, uint64_t size,2099const AddressRange &range, size_t alignment,2100Status &error) {2101if (buf == nullptr) {2102error.SetErrorString("buffer is null");2103return LLDB_INVALID_ADDRESS;2104}2105if (size == 0) {2106error.SetErrorString("buffer size is zero");2107return LLDB_INVALID_ADDRESS;2108}2109if (!range.IsValid()) {2110error.SetErrorString("range is invalid");2111return LLDB_INVALID_ADDRESS;2112}2113if (alignment == 0) {2114error.SetErrorString("alignment must be greater than zero");2115return LLDB_INVALID_ADDRESS;2116}21172118Target &target = GetTarget();2119const lldb::addr_t start_addr =2120range.GetBaseAddress().GetLoadAddress(&target);2121if (start_addr == LLDB_INVALID_ADDRESS) {2122error.SetErrorString("range load address is invalid");2123return LLDB_INVALID_ADDRESS;2124}2125const lldb::addr_t end_addr = start_addr + range.GetByteSize();21262127AddressRanges matches;2128DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment, 1);2129if (matches.empty())2130return LLDB_INVALID_ADDRESS;21312132error.Clear();2133return matches[0].GetBaseAddress().GetLoadAddress(&target);2134}21352136size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,2137Status &error) {2138char buf[256];2139out_str.clear();2140addr_t curr_addr = addr;2141while (true) {2142size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);2143if (length == 0)2144break;2145out_str.append(buf, length);2146// If we got "length - 1" bytes, we didn't get the whole C string, we need2147// to read some more characters2148if (length == sizeof(buf) - 1)2149curr_addr += length;2150else2151break;2152}2153return out_str.size();2154}21552156// Deprecated in favor of ReadStringFromMemory which has wchar support and2157// correct code to find null terminators.2158size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,2159size_t dst_max_len,2160Status &result_error) {2161size_t total_cstr_len = 0;2162if (dst && dst_max_len) {2163result_error.Clear();2164// NULL out everything just to be safe2165memset(dst, 0, dst_max_len);2166Status error;2167addr_t curr_addr = addr;2168const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();2169size_t bytes_left = dst_max_len - 1;2170char *curr_dst = dst;21712172while (bytes_left > 0) {2173addr_t cache_line_bytes_left =2174cache_line_size - (curr_addr % cache_line_size);2175addr_t bytes_to_read =2176std::min<addr_t>(bytes_left, cache_line_bytes_left);2177size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);21782179if (bytes_read == 0) {2180result_error = error;2181dst[total_cstr_len] = '\0';2182break;2183}2184const size_t len = strlen(curr_dst);21852186total_cstr_len += len;21872188if (len < bytes_to_read)2189break;21902191curr_dst += bytes_read;2192curr_addr += bytes_read;2193bytes_left -= bytes_read;2194}2195} else {2196if (dst == nullptr)2197result_error.SetErrorString("invalid arguments");2198else2199result_error.Clear();2200}2201return total_cstr_len;2202}22032204size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,2205Status &error) {2206LLDB_SCOPED_TIMER();22072208if (ABISP abi_sp = GetABI())2209addr = abi_sp->FixAnyAddress(addr);22102211if (buf == nullptr || size == 0)2212return 0;22132214size_t bytes_read = 0;2215uint8_t *bytes = (uint8_t *)buf;22162217while (bytes_read < size) {2218const size_t curr_size = size - bytes_read;2219const size_t curr_bytes_read =2220DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);2221bytes_read += curr_bytes_read;2222if (curr_bytes_read == curr_size || curr_bytes_read == 0)2223break;2224}22252226// Replace any software breakpoint opcodes that fall into this range back2227// into "buf" before we return2228if (bytes_read > 0)2229RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);2230return bytes_read;2231}22322233uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,2234size_t integer_byte_size,2235uint64_t fail_value,2236Status &error) {2237Scalar scalar;2238if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,2239error))2240return scalar.ULongLong(fail_value);2241return fail_value;2242}22432244int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,2245size_t integer_byte_size,2246int64_t fail_value,2247Status &error) {2248Scalar scalar;2249if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,2250error))2251return scalar.SLongLong(fail_value);2252return fail_value;2253}22542255addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {2256Scalar scalar;2257if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,2258error))2259return scalar.ULongLong(LLDB_INVALID_ADDRESS);2260return LLDB_INVALID_ADDRESS;2261}22622263bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,2264Status &error) {2265Scalar scalar;2266const uint32_t addr_byte_size = GetAddressByteSize();2267if (addr_byte_size <= 4)2268scalar = (uint32_t)ptr_value;2269else2270scalar = ptr_value;2271return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==2272addr_byte_size;2273}22742275size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,2276Status &error) {2277size_t bytes_written = 0;2278const uint8_t *bytes = (const uint8_t *)buf;22792280while (bytes_written < size) {2281const size_t curr_size = size - bytes_written;2282const size_t curr_bytes_written = DoWriteMemory(2283addr + bytes_written, bytes + bytes_written, curr_size, error);2284bytes_written += curr_bytes_written;2285if (curr_bytes_written == curr_size || curr_bytes_written == 0)2286break;2287}2288return bytes_written;2289}22902291size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,2292Status &error) {2293if (ABISP abi_sp = GetABI())2294addr = abi_sp->FixAnyAddress(addr);22952296#if defined(ENABLE_MEMORY_CACHING)2297m_memory_cache.Flush(addr, size);2298#endif22992300if (buf == nullptr || size == 0)2301return 0;23022303m_mod_id.BumpMemoryID();23042305// We need to write any data that would go where any current software traps2306// (enabled software breakpoints) any software traps (breakpoints) that we2307// may have placed in our tasks memory.23082309StopPointSiteList<BreakpointSite> bp_sites_in_range;2310if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))2311return WriteMemoryPrivate(addr, buf, size, error);23122313// No breakpoint sites overlap2314if (bp_sites_in_range.IsEmpty())2315return WriteMemoryPrivate(addr, buf, size, error);23162317const uint8_t *ubuf = (const uint8_t *)buf;2318uint64_t bytes_written = 0;23192320bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,2321&error](BreakpointSite *bp) -> void {2322if (error.Fail())2323return;23242325if (bp->GetType() != BreakpointSite::eSoftware)2326return;23272328addr_t intersect_addr;2329size_t intersect_size;2330size_t opcode_offset;2331const bool intersects = bp->IntersectsRange(2332addr, size, &intersect_addr, &intersect_size, &opcode_offset);2333UNUSED_IF_ASSERT_DISABLED(intersects);2334assert(intersects);2335assert(addr <= intersect_addr && intersect_addr < addr + size);2336assert(addr < intersect_addr + intersect_size &&2337intersect_addr + intersect_size <= addr + size);2338assert(opcode_offset + intersect_size <= bp->GetByteSize());23392340// Check for bytes before this breakpoint2341const addr_t curr_addr = addr + bytes_written;2342if (intersect_addr > curr_addr) {2343// There are some bytes before this breakpoint that we need to just2344// write to memory2345size_t curr_size = intersect_addr - curr_addr;2346size_t curr_bytes_written =2347WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);2348bytes_written += curr_bytes_written;2349if (curr_bytes_written != curr_size) {2350// We weren't able to write all of the requested bytes, we are2351// done looping and will return the number of bytes that we have2352// written so far.2353if (error.Success())2354error.SetErrorToGenericError();2355}2356}2357// Now write any bytes that would cover up any software breakpoints2358// directly into the breakpoint opcode buffer2359::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,2360intersect_size);2361bytes_written += intersect_size;2362});23632364// Write any remaining bytes after the last breakpoint if we have any left2365if (bytes_written < size)2366bytes_written +=2367WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,2368size - bytes_written, error);23692370return bytes_written;2371}23722373size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,2374size_t byte_size, Status &error) {2375if (byte_size == UINT32_MAX)2376byte_size = scalar.GetByteSize();2377if (byte_size > 0) {2378uint8_t buf[32];2379const size_t mem_size =2380scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);2381if (mem_size > 0)2382return WriteMemory(addr, buf, mem_size, error);2383else2384error.SetErrorString("failed to get scalar as memory data");2385} else {2386error.SetErrorString("invalid scalar value");2387}2388return 0;2389}23902391size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,2392bool is_signed, Scalar &scalar,2393Status &error) {2394uint64_t uval = 0;2395if (byte_size == 0) {2396error.SetErrorString("byte size is zero");2397} else if (byte_size & (byte_size - 1)) {2398error.SetErrorStringWithFormat("byte size %u is not a power of 2",2399byte_size);2400} else if (byte_size <= sizeof(uval)) {2401const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);2402if (bytes_read == byte_size) {2403DataExtractor data(&uval, sizeof(uval), GetByteOrder(),2404GetAddressByteSize());2405lldb::offset_t offset = 0;2406if (byte_size <= 4)2407scalar = data.GetMaxU32(&offset, byte_size);2408else2409scalar = data.GetMaxU64(&offset, byte_size);2410if (is_signed)2411scalar.SignExtend(byte_size * 8);2412return bytes_read;2413}2414} else {2415error.SetErrorStringWithFormat(2416"byte size of %u is too large for integer scalar type", byte_size);2417}2418return 0;2419}24202421Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {2422Status error;2423for (const auto &Entry : entries) {2424WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),2425error);2426if (!error.Success())2427break;2428}2429return error;2430}24312432#define USE_ALLOCATE_MEMORY_CACHE 12433addr_t Process::AllocateMemory(size_t size, uint32_t permissions,2434Status &error) {2435if (GetPrivateState() != eStateStopped) {2436error.SetErrorToGenericError();2437return LLDB_INVALID_ADDRESS;2438}24392440#if defined(USE_ALLOCATE_MEMORY_CACHE)2441return m_allocated_memory_cache.AllocateMemory(size, permissions, error);2442#else2443addr_t allocated_addr = DoAllocateMemory(size, permissions, error);2444Log *log = GetLog(LLDBLog::Process);2445LLDB_LOGF(log,2446"Process::AllocateMemory(size=%" PRIu642447", permissions=%s) => 0x%16.16" PRIx642448" (m_stop_id = %u m_memory_id = %u)",2449(uint64_t)size, GetPermissionsAsCString(permissions),2450(uint64_t)allocated_addr, m_mod_id.GetStopID(),2451m_mod_id.GetMemoryID());2452return allocated_addr;2453#endif2454}24552456addr_t Process::CallocateMemory(size_t size, uint32_t permissions,2457Status &error) {2458addr_t return_addr = AllocateMemory(size, permissions, error);2459if (error.Success()) {2460std::string buffer(size, 0);2461WriteMemory(return_addr, buffer.c_str(), size, error);2462}2463return return_addr;2464}24652466bool Process::CanJIT() {2467if (m_can_jit == eCanJITDontKnow) {2468Log *log = GetLog(LLDBLog::Process);2469Status err;24702471uint64_t allocated_memory = AllocateMemory(24728, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,2473err);24742475if (err.Success()) {2476m_can_jit = eCanJITYes;2477LLDB_LOGF(log,2478"Process::%s pid %" PRIu642479" allocation test passed, CanJIT () is true",2480__FUNCTION__, GetID());2481} else {2482m_can_jit = eCanJITNo;2483LLDB_LOGF(log,2484"Process::%s pid %" PRIu642485" allocation test failed, CanJIT () is false: %s",2486__FUNCTION__, GetID(), err.AsCString());2487}24882489DeallocateMemory(allocated_memory);2490}24912492return m_can_jit == eCanJITYes;2493}24942495void Process::SetCanJIT(bool can_jit) {2496m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);2497}24982499void Process::SetCanRunCode(bool can_run_code) {2500SetCanJIT(can_run_code);2501m_can_interpret_function_calls = can_run_code;2502}25032504Status Process::DeallocateMemory(addr_t ptr) {2505Status error;2506#if defined(USE_ALLOCATE_MEMORY_CACHE)2507if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {2508error.SetErrorStringWithFormat(2509"deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);2510}2511#else2512error = DoDeallocateMemory(ptr);25132514Log *log = GetLog(LLDBLog::Process);2515LLDB_LOGF(log,2516"Process::DeallocateMemory(addr=0x%16.16" PRIx642517") => err = %s (m_stop_id = %u, m_memory_id = %u)",2518ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),2519m_mod_id.GetMemoryID());2520#endif2521return error;2522}25232524bool Process::GetWatchpointReportedAfter() {2525if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())2526return *subclass_override;25272528bool reported_after = true;2529const ArchSpec &arch = GetTarget().GetArchitecture();2530if (!arch.IsValid())2531return reported_after;2532llvm::Triple triple = arch.GetTriple();25332534if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||2535triple.isAArch64() || triple.isArmMClass() || triple.isARM())2536reported_after = false;25372538return reported_after;2539}25402541ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,2542lldb::addr_t header_addr,2543size_t size_to_read) {2544Log *log = GetLog(LLDBLog::Host);2545if (log) {2546LLDB_LOGF(log,2547"Process::ReadModuleFromMemory reading %s binary from memory",2548file_spec.GetPath().c_str());2549}2550ModuleSP module_sp(new Module(file_spec, ArchSpec()));2551if (module_sp) {2552Status error;2553std::unique_ptr<Progress> progress_up;2554// Reading an ObjectFile from a local corefile is very fast,2555// only print a progress update if we're reading from a2556// live session which might go over gdb remote serial protocol.2557if (IsLiveDebugSession())2558progress_up = std::make_unique<Progress>(2559"Reading binary from memory", file_spec.GetFilename().GetString());25602561ObjectFile *objfile = module_sp->GetMemoryObjectFile(2562shared_from_this(), header_addr, error, size_to_read);2563if (objfile)2564return module_sp;2565}2566return ModuleSP();2567}25682569bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,2570uint32_t &permissions) {2571MemoryRegionInfo range_info;2572permissions = 0;2573Status error(GetMemoryRegionInfo(load_addr, range_info));2574if (!error.Success())2575return false;2576if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||2577range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||2578range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {2579return false;2580}2581permissions = range_info.GetLLDBPermissions();2582return true;2583}25842585Status Process::EnableWatchpoint(WatchpointSP wp_sp, bool notify) {2586Status error;2587error.SetErrorString("watchpoints are not supported");2588return error;2589}25902591Status Process::DisableWatchpoint(WatchpointSP wp_sp, bool notify) {2592Status error;2593error.SetErrorString("watchpoints are not supported");2594return error;2595}25962597StateType2598Process::WaitForProcessStopPrivate(EventSP &event_sp,2599const Timeout<std::micro> &timeout) {2600StateType state;26012602while (true) {2603event_sp.reset();2604state = GetStateChangedEventsPrivate(event_sp, timeout);26052606if (StateIsStoppedState(state, false))2607break;26082609// If state is invalid, then we timed out2610if (state == eStateInvalid)2611break;26122613if (event_sp)2614HandlePrivateEvent(event_sp);2615}2616return state;2617}26182619void Process::LoadOperatingSystemPlugin(bool flush) {2620std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);2621if (flush)2622m_thread_list.Clear();2623m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));2624if (flush)2625Flush();2626}26272628Status Process::Launch(ProcessLaunchInfo &launch_info) {2629StateType state_after_launch = eStateInvalid;2630EventSP first_stop_event_sp;2631Status status =2632LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);2633if (status.Fail())2634return status;26352636if (state_after_launch != eStateStopped &&2637state_after_launch != eStateCrashed)2638return Status();26392640// Note, the stop event was consumed above, but not handled. This2641// was done to give DidLaunch a chance to run. The target is either2642// stopped or crashed. Directly set the state. This is done to2643// prevent a stop message with a bunch of spurious output on thread2644// status, as well as not pop a ProcessIOHandler.2645SetPublicState(state_after_launch, false);26462647if (PrivateStateThreadIsValid())2648ResumePrivateStateThread();2649else2650StartPrivateStateThread();26512652// Target was stopped at entry as was intended. Need to notify the2653// listeners about it.2654if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))2655HandlePrivateEvent(first_stop_event_sp);26562657return Status();2658}26592660Status Process::LaunchPrivate(ProcessLaunchInfo &launch_info, StateType &state,2661EventSP &event_sp) {2662Status error;2663m_abi_sp.reset();2664m_dyld_up.reset();2665m_jit_loaders_up.reset();2666m_system_runtime_up.reset();2667m_os_up.reset();26682669{2670std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);2671m_process_input_reader.reset();2672}26732674Module *exe_module = GetTarget().GetExecutableModulePointer();26752676// The "remote executable path" is hooked up to the local Executable2677// module. But we should be able to debug a remote process even if the2678// executable module only exists on the remote. However, there needs to2679// be a way to express this path, without actually having a module.2680// The way to do that is to set the ExecutableFile in the LaunchInfo.2681// Figure that out here:26822683FileSpec exe_spec_to_use;2684if (!exe_module) {2685if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {2686error.SetErrorString("executable module does not exist");2687return error;2688}2689exe_spec_to_use = launch_info.GetExecutableFile();2690} else2691exe_spec_to_use = exe_module->GetFileSpec();26922693if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {2694// Install anything that might need to be installed prior to launching.2695// For host systems, this will do nothing, but if we are connected to a2696// remote platform it will install any needed binaries2697error = GetTarget().Install(&launch_info);2698if (error.Fail())2699return error;2700}27012702// Listen and queue events that are broadcasted during the process launch.2703ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));2704HijackProcessEvents(listener_sp);2705auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });27062707if (PrivateStateThreadIsValid())2708PausePrivateStateThread();27092710error = WillLaunch(exe_module);2711if (error.Fail()) {2712std::string local_exec_file_path = exe_spec_to_use.GetPath();2713return Status("file doesn't exist: '%s'", local_exec_file_path.c_str());2714}27152716const bool restarted = false;2717SetPublicState(eStateLaunching, restarted);2718m_should_detach = false;27192720if (m_public_run_lock.TrySetRunning()) {2721// Now launch using these arguments.2722error = DoLaunch(exe_module, launch_info);2723} else {2724// This shouldn't happen2725error.SetErrorString("failed to acquire process run lock");2726}27272728if (error.Fail()) {2729if (GetID() != LLDB_INVALID_PROCESS_ID) {2730SetID(LLDB_INVALID_PROCESS_ID);2731const char *error_string = error.AsCString();2732if (error_string == nullptr)2733error_string = "launch failed";2734SetExitStatus(-1, error_string);2735}2736return error;2737}27382739// Now wait for the process to launch and return control to us, and then2740// call DidLaunch:2741state = WaitForProcessStopPrivate(event_sp, seconds(10));27422743if (state == eStateInvalid || !event_sp) {2744// We were able to launch the process, but we failed to catch the2745// initial stop.2746error.SetErrorString("failed to catch stop after launch");2747SetExitStatus(0, error.AsCString());2748Destroy(false);2749return error;2750}27512752if (state == eStateExited) {2753// We exited while trying to launch somehow. Don't call DidLaunch2754// as that's not likely to work, and return an invalid pid.2755HandlePrivateEvent(event_sp);2756return Status();2757}27582759if (state == eStateStopped || state == eStateCrashed) {2760DidLaunch();27612762// Now that we know the process type, update its signal responses from the2763// ones stored in the Target:2764if (m_unix_signals_sp) {2765StreamSP warning_strm = GetTarget().GetDebugger().GetAsyncErrorStream();2766GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp, warning_strm);2767}27682769DynamicLoader *dyld = GetDynamicLoader();2770if (dyld)2771dyld->DidLaunch();27722773GetJITLoaders().DidLaunch();27742775SystemRuntime *system_runtime = GetSystemRuntime();2776if (system_runtime)2777system_runtime->DidLaunch();27782779if (!m_os_up)2780LoadOperatingSystemPlugin(false);27812782// We successfully launched the process and stopped, now it the2783// right time to set up signal filters before resuming.2784UpdateAutomaticSignalFiltering();2785return Status();2786}27872788return Status("Unexpected process state after the launch: %s, expected %s, "2789"%s, %s or %s",2790StateAsCString(state), StateAsCString(eStateInvalid),2791StateAsCString(eStateExited), StateAsCString(eStateStopped),2792StateAsCString(eStateCrashed));2793}27942795Status Process::LoadCore() {2796Status error = DoLoadCore();2797if (error.Success()) {2798ListenerSP listener_sp(2799Listener::MakeListener("lldb.process.load_core_listener"));2800HijackProcessEvents(listener_sp);28012802if (PrivateStateThreadIsValid())2803ResumePrivateStateThread();2804else2805StartPrivateStateThread();28062807DynamicLoader *dyld = GetDynamicLoader();2808if (dyld)2809dyld->DidAttach();28102811GetJITLoaders().DidAttach();28122813SystemRuntime *system_runtime = GetSystemRuntime();2814if (system_runtime)2815system_runtime->DidAttach();28162817if (!m_os_up)2818LoadOperatingSystemPlugin(false);28192820// We successfully loaded a core file, now pretend we stopped so we can2821// show all of the threads in the core file and explore the crashed state.2822SetPrivateState(eStateStopped);28232824// Wait for a stopped event since we just posted one above...2825lldb::EventSP event_sp;2826StateType state =2827WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,2828nullptr, true, SelectMostRelevantFrame);28292830if (!StateIsStoppedState(state, false)) {2831Log *log = GetLog(LLDBLog::Process);2832LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",2833StateAsCString(state));2834error.SetErrorString(2835"Did not get stopped event after loading the core file.");2836}2837RestoreProcessEvents();2838}2839return error;2840}28412842DynamicLoader *Process::GetDynamicLoader() {2843if (!m_dyld_up)2844m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));2845return m_dyld_up.get();2846}28472848void Process::SetDynamicLoader(DynamicLoaderUP dyld_up) {2849m_dyld_up = std::move(dyld_up);2850}28512852DataExtractor Process::GetAuxvData() { return DataExtractor(); }28532854llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {2855return false;2856}28572858JITLoaderList &Process::GetJITLoaders() {2859if (!m_jit_loaders_up) {2860m_jit_loaders_up = std::make_unique<JITLoaderList>();2861JITLoader::LoadPlugins(this, *m_jit_loaders_up);2862}2863return *m_jit_loaders_up;2864}28652866SystemRuntime *Process::GetSystemRuntime() {2867if (!m_system_runtime_up)2868m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));2869return m_system_runtime_up.get();2870}28712872Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,2873uint32_t exec_count)2874: NextEventAction(process), m_exec_count(exec_count) {2875Log *log = GetLog(LLDBLog::Process);2876LLDB_LOGF(2877log,2878"Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,2879__FUNCTION__, static_cast<void *>(process), exec_count);2880}28812882Process::NextEventAction::EventActionResult2883Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {2884Log *log = GetLog(LLDBLog::Process);28852886StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());2887LLDB_LOGF(log,2888"Process::AttachCompletionHandler::%s called with state %s (%d)",2889__FUNCTION__, StateAsCString(state), static_cast<int>(state));28902891switch (state) {2892case eStateAttaching:2893return eEventActionSuccess;28942895case eStateRunning:2896case eStateConnected:2897return eEventActionRetry;28982899case eStateStopped:2900case eStateCrashed:2901// During attach, prior to sending the eStateStopped event,2902// lldb_private::Process subclasses must set the new process ID.2903assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);2904// We don't want these events to be reported, so go set the2905// ShouldReportStop here:2906m_process->GetThreadList().SetShouldReportStop(eVoteNo);29072908if (m_exec_count > 0) {2909--m_exec_count;29102911LLDB_LOGF(log,2912"Process::AttachCompletionHandler::%s state %s: reduced "2913"remaining exec count to %" PRIu32 ", requesting resume",2914__FUNCTION__, StateAsCString(state), m_exec_count);29152916RequestResume();2917return eEventActionRetry;2918} else {2919LLDB_LOGF(log,2920"Process::AttachCompletionHandler::%s state %s: no more "2921"execs expected to start, continuing with attach",2922__FUNCTION__, StateAsCString(state));29232924m_process->CompleteAttach();2925return eEventActionSuccess;2926}2927break;29282929default:2930case eStateExited:2931case eStateInvalid:2932break;2933}29342935m_exit_string.assign("No valid Process");2936return eEventActionExit;2937}29382939Process::NextEventAction::EventActionResult2940Process::AttachCompletionHandler::HandleBeingInterrupted() {2941return eEventActionSuccess;2942}29432944const char *Process::AttachCompletionHandler::GetExitString() {2945return m_exit_string.c_str();2946}29472948ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {2949if (m_listener_sp)2950return m_listener_sp;2951else2952return debugger.GetListener();2953}29542955Status Process::WillLaunch(Module *module) {2956return DoWillLaunch(module);2957}29582959Status Process::WillAttachToProcessWithID(lldb::pid_t pid) {2960return DoWillAttachToProcessWithID(pid);2961}29622963Status Process::WillAttachToProcessWithName(const char *process_name,2964bool wait_for_launch) {2965return DoWillAttachToProcessWithName(process_name, wait_for_launch);2966}29672968Status Process::Attach(ProcessAttachInfo &attach_info) {2969m_abi_sp.reset();2970{2971std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);2972m_process_input_reader.reset();2973}2974m_dyld_up.reset();2975m_jit_loaders_up.reset();2976m_system_runtime_up.reset();2977m_os_up.reset();29782979lldb::pid_t attach_pid = attach_info.GetProcessID();2980Status error;2981if (attach_pid == LLDB_INVALID_PROCESS_ID) {2982char process_name[PATH_MAX];29832984if (attach_info.GetExecutableFile().GetPath(process_name,2985sizeof(process_name))) {2986const bool wait_for_launch = attach_info.GetWaitForLaunch();29872988if (wait_for_launch) {2989error = WillAttachToProcessWithName(process_name, wait_for_launch);2990if (error.Success()) {2991if (m_public_run_lock.TrySetRunning()) {2992m_should_detach = true;2993const bool restarted = false;2994SetPublicState(eStateAttaching, restarted);2995// Now attach using these arguments.2996error = DoAttachToProcessWithName(process_name, attach_info);2997} else {2998// This shouldn't happen2999error.SetErrorString("failed to acquire process run lock");3000}30013002if (error.Fail()) {3003if (GetID() != LLDB_INVALID_PROCESS_ID) {3004SetID(LLDB_INVALID_PROCESS_ID);3005if (error.AsCString() == nullptr)3006error.SetErrorString("attach failed");30073008SetExitStatus(-1, error.AsCString());3009}3010} else {3011SetNextEventAction(new Process::AttachCompletionHandler(3012this, attach_info.GetResumeCount()));3013StartPrivateStateThread();3014}3015return error;3016}3017} else {3018ProcessInstanceInfoList process_infos;3019PlatformSP platform_sp(GetTarget().GetPlatform());30203021if (platform_sp) {3022ProcessInstanceInfoMatch match_info;3023match_info.GetProcessInfo() = attach_info;3024match_info.SetNameMatchType(NameMatch::Equals);3025platform_sp->FindProcesses(match_info, process_infos);3026const uint32_t num_matches = process_infos.size();3027if (num_matches == 1) {3028attach_pid = process_infos[0].GetProcessID();3029// Fall through and attach using the above process ID3030} else {3031match_info.GetProcessInfo().GetExecutableFile().GetPath(3032process_name, sizeof(process_name));3033if (num_matches > 1) {3034StreamString s;3035ProcessInstanceInfo::DumpTableHeader(s, true, false);3036for (size_t i = 0; i < num_matches; i++) {3037process_infos[i].DumpAsTableRow(3038s, platform_sp->GetUserIDResolver(), true, false);3039}3040error.SetErrorStringWithFormat(3041"more than one process named %s:\n%s", process_name,3042s.GetData());3043} else3044error.SetErrorStringWithFormat(3045"could not find a process named %s", process_name);3046}3047} else {3048error.SetErrorString(3049"invalid platform, can't find processes by name");3050return error;3051}3052}3053} else {3054error.SetErrorString("invalid process name");3055}3056}30573058if (attach_pid != LLDB_INVALID_PROCESS_ID) {3059error = WillAttachToProcessWithID(attach_pid);3060if (error.Success()) {30613062if (m_public_run_lock.TrySetRunning()) {3063// Now attach using these arguments.3064m_should_detach = true;3065const bool restarted = false;3066SetPublicState(eStateAttaching, restarted);3067error = DoAttachToProcessWithID(attach_pid, attach_info);3068} else {3069// This shouldn't happen3070error.SetErrorString("failed to acquire process run lock");3071}30723073if (error.Success()) {3074SetNextEventAction(new Process::AttachCompletionHandler(3075this, attach_info.GetResumeCount()));3076StartPrivateStateThread();3077} else {3078if (GetID() != LLDB_INVALID_PROCESS_ID)3079SetID(LLDB_INVALID_PROCESS_ID);30803081const char *error_string = error.AsCString();3082if (error_string == nullptr)3083error_string = "attach failed";30843085SetExitStatus(-1, error_string);3086}3087}3088}3089return error;3090}30913092void Process::CompleteAttach() {3093Log *log(GetLog(LLDBLog::Process | LLDBLog::Target));3094LLDB_LOGF(log, "Process::%s()", __FUNCTION__);30953096// Let the process subclass figure out at much as it can about the process3097// before we go looking for a dynamic loader plug-in.3098ArchSpec process_arch;3099DidAttach(process_arch);31003101if (process_arch.IsValid()) {3102LLDB_LOG(log,3103"Process::{0} replacing process architecture with DidAttach() "3104"architecture: \"{1}\"",3105__FUNCTION__, process_arch.GetTriple().getTriple());3106GetTarget().SetArchitecture(process_arch);3107}31083109// We just attached. If we have a platform, ask it for the process3110// architecture, and if it isn't the same as the one we've already set,3111// switch architectures.3112PlatformSP platform_sp(GetTarget().GetPlatform());3113assert(platform_sp);3114ArchSpec process_host_arch = GetSystemArchitecture();3115if (platform_sp) {3116const ArchSpec &target_arch = GetTarget().GetArchitecture();3117if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(3118target_arch, process_host_arch,3119ArchSpec::CompatibleMatch, nullptr)) {3120ArchSpec platform_arch;3121platform_sp = GetTarget().GetDebugger().GetPlatformList().GetOrCreate(3122target_arch, process_host_arch, &platform_arch);3123if (platform_sp) {3124GetTarget().SetPlatform(platform_sp);3125GetTarget().SetArchitecture(platform_arch);3126LLDB_LOG(log,3127"switching platform to {0} and architecture to {1} based on "3128"info from attach",3129platform_sp->GetName(), platform_arch.GetTriple().getTriple());3130}3131} else if (!process_arch.IsValid()) {3132ProcessInstanceInfo process_info;3133GetProcessInfo(process_info);3134const ArchSpec &process_arch = process_info.GetArchitecture();3135const ArchSpec &target_arch = GetTarget().GetArchitecture();3136if (process_arch.IsValid() &&3137target_arch.IsCompatibleMatch(process_arch) &&3138!target_arch.IsExactMatch(process_arch)) {3139GetTarget().SetArchitecture(process_arch);3140LLDB_LOGF(log,3141"Process::%s switching architecture to %s based on info "3142"the platform retrieved for pid %" PRIu64,3143__FUNCTION__, process_arch.GetTriple().getTriple().c_str(),3144GetID());3145}3146}3147}3148// Now that we know the process type, update its signal responses from the3149// ones stored in the Target:3150if (m_unix_signals_sp) {3151StreamSP warning_strm = GetTarget().GetDebugger().GetAsyncErrorStream();3152GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp, warning_strm);3153}31543155// We have completed the attach, now it is time to find the dynamic loader3156// plug-in3157DynamicLoader *dyld = GetDynamicLoader();3158if (dyld) {3159dyld->DidAttach();3160if (log) {3161ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3162LLDB_LOG(log,3163"after DynamicLoader::DidAttach(), target "3164"executable is {0} (using {1} plugin)",3165exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),3166dyld->GetPluginName());3167}3168}31693170GetJITLoaders().DidAttach();31713172SystemRuntime *system_runtime = GetSystemRuntime();3173if (system_runtime) {3174system_runtime->DidAttach();3175if (log) {3176ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3177LLDB_LOG(log,3178"after SystemRuntime::DidAttach(), target "3179"executable is {0} (using {1} plugin)",3180exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),3181system_runtime->GetPluginName());3182}3183}31843185if (!m_os_up) {3186LoadOperatingSystemPlugin(false);3187if (m_os_up) {3188// Somebody might have gotten threads before now, but we need to force the3189// update after we've loaded the OperatingSystem plugin or it won't get a3190// chance to process the threads.3191m_thread_list.Clear();3192UpdateThreadListIfNeeded();3193}3194}3195// Figure out which one is the executable, and set that in our target:3196ModuleSP new_executable_module_sp;3197for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {3198if (module_sp && module_sp->IsExecutable()) {3199if (GetTarget().GetExecutableModulePointer() != module_sp.get())3200new_executable_module_sp = module_sp;3201break;3202}3203}3204if (new_executable_module_sp) {3205GetTarget().SetExecutableModule(new_executable_module_sp,3206eLoadDependentsNo);3207if (log) {3208ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3209LLDB_LOGF(3210log,3211"Process::%s after looping through modules, target executable is %s",3212__FUNCTION__,3213exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()3214: "<none>");3215}3216}3217}32183219Status Process::ConnectRemote(llvm::StringRef remote_url) {3220m_abi_sp.reset();3221{3222std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);3223m_process_input_reader.reset();3224}32253226// Find the process and its architecture. Make sure it matches the3227// architecture of the current Target, and if not adjust it.32283229Status error(DoConnectRemote(remote_url));3230if (error.Success()) {3231if (GetID() != LLDB_INVALID_PROCESS_ID) {3232EventSP event_sp;3233StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);32343235if (state == eStateStopped || state == eStateCrashed) {3236// If we attached and actually have a process on the other end, then3237// this ended up being the equivalent of an attach.3238CompleteAttach();32393240// This delays passing the stopped event to listeners till3241// CompleteAttach gets a chance to complete...3242HandlePrivateEvent(event_sp);3243}3244}32453246if (PrivateStateThreadIsValid())3247ResumePrivateStateThread();3248else3249StartPrivateStateThread();3250}3251return error;3252}32533254Status Process::PrivateResume() {3255Log *log(GetLog(LLDBLog::Process | LLDBLog::Step));3256LLDB_LOGF(log,3257"Process::PrivateResume() m_stop_id = %u, public state: %s "3258"private state: %s",3259m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),3260StateAsCString(m_private_state.GetValue()));32613262// If signals handing status changed we might want to update our signal3263// filters before resuming.3264UpdateAutomaticSignalFiltering();32653266Status error(WillResume());3267// Tell the process it is about to resume before the thread list3268if (error.Success()) {3269// Now let the thread list know we are about to resume so it can let all of3270// our threads know that they are about to be resumed. Threads will each be3271// called with Thread::WillResume(StateType) where StateType contains the3272// state that they are supposed to have when the process is resumed3273// (suspended/running/stepping). Threads should also check their resume3274// signal in lldb::Thread::GetResumeSignal() to see if they are supposed to3275// start back up with a signal.3276if (m_thread_list.WillResume()) {3277// Last thing, do the PreResumeActions.3278if (!RunPreResumeActions()) {3279error.SetErrorString(3280"Process::PrivateResume PreResumeActions failed, not resuming.");3281} else {3282m_mod_id.BumpResumeID();3283error = DoResume();3284if (error.Success()) {3285DidResume();3286m_thread_list.DidResume();3287LLDB_LOGF(log, "Process thinks the process has resumed.");3288} else {3289LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");3290return error;3291}3292}3293} else {3294// Somebody wanted to run without running (e.g. we were faking a step3295// from one frame of a set of inlined frames that share the same PC to3296// another.) So generate a continue & a stopped event, and let the world3297// handle them.3298LLDB_LOGF(log,3299"Process::PrivateResume() asked to simulate a start & stop.");33003301SetPrivateState(eStateRunning);3302SetPrivateState(eStateStopped);3303}3304} else3305LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",3306error.AsCString("<unknown error>"));3307return error;3308}33093310Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {3311if (!StateIsRunningState(m_public_state.GetValue()))3312return Status("Process is not running.");33133314// Don't clear the m_clear_thread_plans_on_stop, only set it to true if in3315// case it was already set and some thread plan logic calls halt on its own.3316m_clear_thread_plans_on_stop |= clear_thread_plans;33173318ListenerSP halt_listener_sp(3319Listener::MakeListener("lldb.process.halt_listener"));3320HijackProcessEvents(halt_listener_sp);33213322EventSP event_sp;33233324SendAsyncInterrupt();33253326if (m_public_state.GetValue() == eStateAttaching) {3327// Don't hijack and eat the eStateExited as the code that was doing the3328// attach will be waiting for this event...3329RestoreProcessEvents();3330Destroy(false);3331SetExitStatus(SIGKILL, "Cancelled async attach.");3332return Status();3333}33343335// Wait for the process halt timeout seconds for the process to stop.3336// If we are going to use the run lock, that means we're stopping out to the3337// user, so we should also select the most relevant frame.3338SelectMostRelevant select_most_relevant =3339use_run_lock ? SelectMostRelevantFrame : DoNoSelectMostRelevantFrame;3340StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,3341halt_listener_sp, nullptr,3342use_run_lock, select_most_relevant);3343RestoreProcessEvents();33443345if (state == eStateInvalid || !event_sp) {3346// We timed out and didn't get a stop event...3347return Status("Halt timed out. State = %s", StateAsCString(GetState()));3348}33493350BroadcastEvent(event_sp);33513352return Status();3353}33543355lldb::addr_t Process::FindInMemory(lldb::addr_t low, lldb::addr_t high,3356const uint8_t *buf, size_t size) {3357const size_t region_size = high - low;33583359if (region_size < size)3360return LLDB_INVALID_ADDRESS;33613362std::vector<size_t> bad_char_heuristic(256, size);3363ProcessMemoryIterator iterator(*this, low);33643365for (size_t idx = 0; idx < size - 1; idx++) {3366decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];3367bad_char_heuristic[bcu_idx] = size - idx - 1;3368}3369for (size_t s = 0; s <= (region_size - size);) {3370int64_t j = size - 1;3371while (j >= 0 && buf[j] == iterator[s + j])3372j--;3373if (j < 0)3374return low + s;3375else3376s += bad_char_heuristic[iterator[s + size - 1]];3377}33783379return LLDB_INVALID_ADDRESS;3380}33813382Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {3383Status error;33843385// Check both the public & private states here. If we're hung evaluating an3386// expression, for instance, then the public state will be stopped, but we3387// still need to interrupt.3388if (m_public_state.GetValue() == eStateRunning ||3389m_private_state.GetValue() == eStateRunning) {3390Log *log = GetLog(LLDBLog::Process);3391LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);33923393ListenerSP listener_sp(3394Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));3395HijackProcessEvents(listener_sp);33963397SendAsyncInterrupt();33983399// Consume the interrupt event.3400StateType state = WaitForProcessToStop(GetInterruptTimeout(),3401&exit_event_sp, true, listener_sp);34023403RestoreProcessEvents();34043405// If the process exited while we were waiting for it to stop, put the3406// exited event into the shared pointer passed in and return. Our caller3407// doesn't need to do anything else, since they don't have a process3408// anymore...34093410if (state == eStateExited || m_private_state.GetValue() == eStateExited) {3411LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",3412__FUNCTION__);3413return error;3414} else3415exit_event_sp.reset(); // It is ok to consume any non-exit stop events34163417if (state != eStateStopped) {3418LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,3419StateAsCString(state));3420// If we really couldn't stop the process then we should just error out3421// here, but if the lower levels just bobbled sending the event and we3422// really are stopped, then continue on.3423StateType private_state = m_private_state.GetValue();3424if (private_state != eStateStopped) {3425return Status(3426"Attempt to stop the target in order to detach timed out. "3427"State = %s",3428StateAsCString(GetState()));3429}3430}3431}3432return error;3433}34343435Status Process::Detach(bool keep_stopped) {3436EventSP exit_event_sp;3437Status error;3438m_destroy_in_process = true;34393440error = WillDetach();34413442if (error.Success()) {3443if (DetachRequiresHalt()) {3444error = StopForDestroyOrDetach(exit_event_sp);3445if (!error.Success()) {3446m_destroy_in_process = false;3447return error;3448} else if (exit_event_sp) {3449// We shouldn't need to do anything else here. There's no process left3450// to detach from...3451StopPrivateStateThread();3452m_destroy_in_process = false;3453return error;3454}3455}34563457m_thread_list.DiscardThreadPlans();3458DisableAllBreakpointSites();34593460error = DoDetach(keep_stopped);3461if (error.Success()) {3462DidDetach();3463StopPrivateStateThread();3464} else {3465return error;3466}3467}3468m_destroy_in_process = false;34693470// If we exited when we were waiting for a process to stop, then forward the3471// event here so we don't lose the event3472if (exit_event_sp) {3473// Directly broadcast our exited event because we shut down our private3474// state thread above3475BroadcastEvent(exit_event_sp);3476}34773478// If we have been interrupted (to kill us) in the middle of running, we may3479// not end up propagating the last events through the event system, in which3480// case we might strand the write lock. Unlock it here so when we do to tear3481// down the process we don't get an error destroying the lock.34823483m_public_run_lock.SetStopped();3484return error;3485}34863487Status Process::Destroy(bool force_kill) {3488// If we've already called Process::Finalize then there's nothing useful to3489// be done here. Finalize has actually called Destroy already.3490if (m_finalizing)3491return {};3492return DestroyImpl(force_kill);3493}34943495Status Process::DestroyImpl(bool force_kill) {3496// Tell ourselves we are in the process of destroying the process, so that we3497// don't do any unnecessary work that might hinder the destruction. Remember3498// to set this back to false when we are done. That way if the attempt3499// failed and the process stays around for some reason it won't be in a3500// confused state.35013502if (force_kill)3503m_should_detach = false;35043505if (GetShouldDetach()) {3506// FIXME: This will have to be a process setting:3507bool keep_stopped = false;3508Detach(keep_stopped);3509}35103511m_destroy_in_process = true;35123513Status error(WillDestroy());3514if (error.Success()) {3515EventSP exit_event_sp;3516if (DestroyRequiresHalt()) {3517error = StopForDestroyOrDetach(exit_event_sp);3518}35193520if (m_public_state.GetValue() == eStateStopped) {3521// Ditch all thread plans, and remove all our breakpoints: in case we3522// have to restart the target to kill it, we don't want it hitting a3523// breakpoint... Only do this if we've stopped, however, since if we3524// didn't manage to halt it above, then we're not going to have much luck3525// doing this now.3526m_thread_list.DiscardThreadPlans();3527DisableAllBreakpointSites();3528}35293530error = DoDestroy();3531if (error.Success()) {3532DidDestroy();3533StopPrivateStateThread();3534}3535m_stdio_communication.StopReadThread();3536m_stdio_communication.Disconnect();3537m_stdin_forward = false;35383539{3540std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);3541if (m_process_input_reader) {3542m_process_input_reader->SetIsDone(true);3543m_process_input_reader->Cancel();3544m_process_input_reader.reset();3545}3546}35473548// If we exited when we were waiting for a process to stop, then forward3549// the event here so we don't lose the event3550if (exit_event_sp) {3551// Directly broadcast our exited event because we shut down our private3552// state thread above3553BroadcastEvent(exit_event_sp);3554}35553556// If we have been interrupted (to kill us) in the middle of running, we3557// may not end up propagating the last events through the event system, in3558// which case we might strand the write lock. Unlock it here so when we do3559// to tear down the process we don't get an error destroying the lock.3560m_public_run_lock.SetStopped();3561}35623563m_destroy_in_process = false;35643565return error;3566}35673568Status Process::Signal(int signal) {3569Status error(WillSignal());3570if (error.Success()) {3571error = DoSignal(signal);3572if (error.Success())3573DidSignal();3574}3575return error;3576}35773578void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {3579assert(signals_sp && "null signals_sp");3580m_unix_signals_sp = std::move(signals_sp);3581}35823583const lldb::UnixSignalsSP &Process::GetUnixSignals() {3584assert(m_unix_signals_sp && "null m_unix_signals_sp");3585return m_unix_signals_sp;3586}35873588lldb::ByteOrder Process::GetByteOrder() const {3589return GetTarget().GetArchitecture().GetByteOrder();3590}35913592uint32_t Process::GetAddressByteSize() const {3593return GetTarget().GetArchitecture().GetAddressByteSize();3594}35953596bool Process::ShouldBroadcastEvent(Event *event_ptr) {3597const StateType state =3598Process::ProcessEventData::GetStateFromEvent(event_ptr);3599bool return_value = true;3600Log *log(GetLog(LLDBLog::Events | LLDBLog::Process));36013602switch (state) {3603case eStateDetached:3604case eStateExited:3605case eStateUnloaded:3606m_stdio_communication.SynchronizeWithReadThread();3607m_stdio_communication.StopReadThread();3608m_stdio_communication.Disconnect();3609m_stdin_forward = false;36103611[[fallthrough]];3612case eStateConnected:3613case eStateAttaching:3614case eStateLaunching:3615// These events indicate changes in the state of the debugging session,3616// always report them.3617return_value = true;3618break;3619case eStateInvalid:3620// We stopped for no apparent reason, don't report it.3621return_value = false;3622break;3623case eStateRunning:3624case eStateStepping:3625// If we've started the target running, we handle the cases where we are3626// already running and where there is a transition from stopped to running3627// differently. running -> running: Automatically suppress extra running3628// events stopped -> running: Report except when there is one or more no3629// votes3630// and no yes votes.3631SynchronouslyNotifyStateChanged(state);3632if (m_force_next_event_delivery)3633return_value = true;3634else {3635switch (m_last_broadcast_state) {3636case eStateRunning:3637case eStateStepping:3638// We always suppress multiple runnings with no PUBLIC stop in between.3639return_value = false;3640break;3641default:3642// TODO: make this work correctly. For now always report3643// run if we aren't running so we don't miss any running events. If I3644// run the lldb/test/thread/a.out file and break at main.cpp:58, run3645// and hit the breakpoints on multiple threads, then somehow during the3646// stepping over of all breakpoints no run gets reported.36473648// This is a transition from stop to run.3649switch (m_thread_list.ShouldReportRun(event_ptr)) {3650case eVoteYes:3651case eVoteNoOpinion:3652return_value = true;3653break;3654case eVoteNo:3655return_value = false;3656break;3657}3658break;3659}3660}3661break;3662case eStateStopped:3663case eStateCrashed:3664case eStateSuspended:3665// We've stopped. First see if we're going to restart the target. If we3666// are going to stop, then we always broadcast the event. If we aren't3667// going to stop, let the thread plans decide if we're going to report this3668// event. If no thread has an opinion, we don't report it.36693670m_stdio_communication.SynchronizeWithReadThread();3671RefreshStateAfterStop();3672if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {3673LLDB_LOGF(log,3674"Process::ShouldBroadcastEvent (%p) stopped due to an "3675"interrupt, state: %s",3676static_cast<void *>(event_ptr), StateAsCString(state));3677// Even though we know we are going to stop, we should let the threads3678// have a look at the stop, so they can properly set their state.3679m_thread_list.ShouldStop(event_ptr);3680return_value = true;3681} else {3682bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);3683bool should_resume = false;36843685// It makes no sense to ask "ShouldStop" if we've already been3686// restarted... Asking the thread list is also not likely to go well,3687// since we are running again. So in that case just report the event.36883689if (!was_restarted)3690should_resume = !m_thread_list.ShouldStop(event_ptr);36913692if (was_restarted || should_resume || m_resume_requested) {3693Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);3694LLDB_LOGF(log,3695"Process::ShouldBroadcastEvent: should_resume: %i state: "3696"%s was_restarted: %i report_stop_vote: %d.",3697should_resume, StateAsCString(state), was_restarted,3698report_stop_vote);36993700switch (report_stop_vote) {3701case eVoteYes:3702return_value = true;3703break;3704case eVoteNoOpinion:3705case eVoteNo:3706return_value = false;3707break;3708}37093710if (!was_restarted) {3711LLDB_LOGF(log,3712"Process::ShouldBroadcastEvent (%p) Restarting process "3713"from state: %s",3714static_cast<void *>(event_ptr), StateAsCString(state));3715ProcessEventData::SetRestartedInEvent(event_ptr, true);3716PrivateResume();3717}3718} else {3719return_value = true;3720SynchronouslyNotifyStateChanged(state);3721}3722}3723break;3724}37253726// Forcing the next event delivery is a one shot deal. So reset it here.3727m_force_next_event_delivery = false;37283729// We do some coalescing of events (for instance two consecutive running3730// events get coalesced.) But we only coalesce against events we actually3731// broadcast. So we use m_last_broadcast_state to track that. NB - you3732// can't use "m_public_state.GetValue()" for that purpose, as was originally3733// done, because the PublicState reflects the last event pulled off the3734// queue, and there may be several events stacked up on the queue unserviced.3735// So the PublicState may not reflect the last broadcasted event yet.3736// m_last_broadcast_state gets updated here.37373738if (return_value)3739m_last_broadcast_state = state;37403741LLDB_LOGF(log,3742"Process::ShouldBroadcastEvent (%p) => new state: %s, last "3743"broadcast state: %s - %s",3744static_cast<void *>(event_ptr), StateAsCString(state),3745StateAsCString(m_last_broadcast_state),3746return_value ? "YES" : "NO");3747return return_value;3748}37493750bool Process::StartPrivateStateThread(bool is_secondary_thread) {3751Log *log = GetLog(LLDBLog::Events);37523753bool already_running = PrivateStateThreadIsValid();3754LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,3755already_running ? " already running"3756: " starting private state thread");37573758if (!is_secondary_thread && already_running)3759return true;37603761// Create a thread that watches our internal state and controls which events3762// make it to clients (into the DCProcess event queue).3763char thread_name[1024];3764uint32_t max_len = llvm::get_max_thread_name_length();3765if (max_len > 0 && max_len <= 30) {3766// On platforms with abbreviated thread name lengths, choose thread names3767// that fit within the limit.3768if (already_running)3769snprintf(thread_name, sizeof(thread_name), "intern-state-OV");3770else3771snprintf(thread_name, sizeof(thread_name), "intern-state");3772} else {3773if (already_running)3774snprintf(thread_name, sizeof(thread_name),3775"<lldb.process.internal-state-override(pid=%" PRIu64 ")>",3776GetID());3777else3778snprintf(thread_name, sizeof(thread_name),3779"<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());3780}37813782llvm::Expected<HostThread> private_state_thread =3783ThreadLauncher::LaunchThread(3784thread_name,3785[this, is_secondary_thread] {3786return RunPrivateStateThread(is_secondary_thread);3787},37888 * 1024 * 1024);3789if (!private_state_thread) {3790LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),3791"failed to launch host thread: {0}");3792return false;3793}37943795assert(private_state_thread->IsJoinable());3796m_private_state_thread = *private_state_thread;3797ResumePrivateStateThread();3798return true;3799}38003801void Process::PausePrivateStateThread() {3802ControlPrivateStateThread(eBroadcastInternalStateControlPause);3803}38043805void Process::ResumePrivateStateThread() {3806ControlPrivateStateThread(eBroadcastInternalStateControlResume);3807}38083809void Process::StopPrivateStateThread() {3810if (m_private_state_thread.IsJoinable())3811ControlPrivateStateThread(eBroadcastInternalStateControlStop);3812else {3813Log *log = GetLog(LLDBLog::Process);3814LLDB_LOGF(3815log,3816"Went to stop the private state thread, but it was already invalid.");3817}3818}38193820void Process::ControlPrivateStateThread(uint32_t signal) {3821Log *log = GetLog(LLDBLog::Process);38223823assert(signal == eBroadcastInternalStateControlStop ||3824signal == eBroadcastInternalStateControlPause ||3825signal == eBroadcastInternalStateControlResume);38263827LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);38283829// Signal the private state thread3830if (m_private_state_thread.IsJoinable()) {3831// Broadcast the event.3832// It is important to do this outside of the if below, because it's3833// possible that the thread state is invalid but that the thread is waiting3834// on a control event instead of simply being on its way out (this should3835// not happen, but it apparently can).3836LLDB_LOGF(log, "Sending control event of type: %d.", signal);3837std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());3838m_private_state_control_broadcaster.BroadcastEvent(signal,3839event_receipt_sp);38403841// Wait for the event receipt or for the private state thread to exit3842bool receipt_received = false;3843if (PrivateStateThreadIsValid()) {3844while (!receipt_received) {3845// Check for a receipt for n seconds and then check if the private3846// state thread is still around.3847receipt_received =3848event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());3849if (!receipt_received) {3850// Check if the private state thread is still around. If it isn't3851// then we are done waiting3852if (!PrivateStateThreadIsValid())3853break; // Private state thread exited or is exiting, we are done3854}3855}3856}38573858if (signal == eBroadcastInternalStateControlStop) {3859thread_result_t result = {};3860m_private_state_thread.Join(&result);3861m_private_state_thread.Reset();3862}3863} else {3864LLDB_LOGF(3865log,3866"Private state thread already dead, no need to signal it to stop.");3867}3868}38693870void Process::SendAsyncInterrupt() {3871if (PrivateStateThreadIsValid())3872m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,3873nullptr);3874else3875BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);3876}38773878void Process::HandlePrivateEvent(EventSP &event_sp) {3879Log *log = GetLog(LLDBLog::Process);3880m_resume_requested = false;38813882const StateType new_state =3883Process::ProcessEventData::GetStateFromEvent(event_sp.get());38843885// First check to see if anybody wants a shot at this event:3886if (m_next_event_action_up) {3887NextEventAction::EventActionResult action_result =3888m_next_event_action_up->PerformAction(event_sp);3889LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);38903891switch (action_result) {3892case NextEventAction::eEventActionSuccess:3893SetNextEventAction(nullptr);3894break;38953896case NextEventAction::eEventActionRetry:3897break;38983899case NextEventAction::eEventActionExit:3900// Handle Exiting Here. If we already got an exited event, we should3901// just propagate it. Otherwise, swallow this event, and set our state3902// to exit so the next event will kill us.3903if (new_state != eStateExited) {3904// FIXME: should cons up an exited event, and discard this one.3905SetExitStatus(0, m_next_event_action_up->GetExitString());3906SetNextEventAction(nullptr);3907return;3908}3909SetNextEventAction(nullptr);3910break;3911}3912}39133914// See if we should broadcast this state to external clients?3915const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());39163917if (should_broadcast) {3918const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);3919if (log) {3920LLDB_LOGF(log,3921"Process::%s (pid = %" PRIu643922") broadcasting new state %s (old state %s) to %s",3923__FUNCTION__, GetID(), StateAsCString(new_state),3924StateAsCString(GetState()),3925is_hijacked ? "hijacked" : "public");3926}3927Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());3928if (StateIsRunningState(new_state)) {3929// Only push the input handler if we aren't fowarding events, as this3930// means the curses GUI is in use... Or don't push it if we are launching3931// since it will come up stopped.3932if (!GetTarget().GetDebugger().IsForwardingEvents() &&3933new_state != eStateLaunching && new_state != eStateAttaching) {3934PushProcessIOHandler();3935m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,3936eBroadcastAlways);3937LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",3938__FUNCTION__, m_iohandler_sync.GetValue());3939}3940} else if (StateIsStoppedState(new_state, false)) {3941if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {3942// If the lldb_private::Debugger is handling the events, we don't want3943// to pop the process IOHandler here, we want to do it when we receive3944// the stopped event so we can carefully control when the process3945// IOHandler is popped because when we stop we want to display some3946// text stating how and why we stopped, then maybe some3947// process/thread/frame info, and then we want the "(lldb) " prompt to3948// show up. If we pop the process IOHandler here, then we will cause3949// the command interpreter to become the top IOHandler after the3950// process pops off and it will update its prompt right away... See the3951// Debugger.cpp file where it calls the function as3952// "process_sp->PopProcessIOHandler()" to see where I am talking about.3953// Otherwise we end up getting overlapping "(lldb) " prompts and3954// garbled output.3955//3956// If we aren't handling the events in the debugger (which is indicated3957// by "m_target.GetDebugger().IsHandlingEvents()" returning false) or3958// we are hijacked, then we always pop the process IO handler manually.3959// Hijacking happens when the internal process state thread is running3960// thread plans, or when commands want to run in synchronous mode and3961// they call "process->WaitForProcessToStop()". An example of something3962// that will hijack the events is a simple expression:3963//3964// (lldb) expr (int)puts("hello")3965//3966// This will cause the internal process state thread to resume and halt3967// the process (and _it_ will hijack the eBroadcastBitStateChanged3968// events) and we do need the IO handler to be pushed and popped3969// correctly.39703971if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())3972PopProcessIOHandler();3973}3974}39753976BroadcastEvent(event_sp);3977} else {3978if (log) {3979LLDB_LOGF(3980log,3981"Process::%s (pid = %" PRIu643982") suppressing state %s (old state %s): should_broadcast == false",3983__FUNCTION__, GetID(), StateAsCString(new_state),3984StateAsCString(GetState()));3985}3986}3987}39883989Status Process::HaltPrivate() {3990EventSP event_sp;3991Status error(WillHalt());3992if (error.Fail())3993return error;39943995// Ask the process subclass to actually halt our process3996bool caused_stop;3997error = DoHalt(caused_stop);39983999DidHalt();4000return error;4001}40024003thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {4004bool control_only = true;40054006Log *log = GetLog(LLDBLog::Process);4007LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",4008__FUNCTION__, static_cast<void *>(this), GetID());40094010bool exit_now = false;4011bool interrupt_requested = false;4012while (!exit_now) {4013EventSP event_sp;4014GetEventsPrivate(event_sp, std::nullopt, control_only);4015if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {4016LLDB_LOGF(log,4017"Process::%s (arg = %p, pid = %" PRIu644018") got a control event: %d",4019__FUNCTION__, static_cast<void *>(this), GetID(),4020event_sp->GetType());40214022switch (event_sp->GetType()) {4023case eBroadcastInternalStateControlStop:4024exit_now = true;4025break; // doing any internal state management below40264027case eBroadcastInternalStateControlPause:4028control_only = true;4029break;40304031case eBroadcastInternalStateControlResume:4032control_only = false;4033break;4034}40354036continue;4037} else if (event_sp->GetType() == eBroadcastBitInterrupt) {4038if (m_public_state.GetValue() == eStateAttaching) {4039LLDB_LOGF(log,4040"Process::%s (arg = %p, pid = %" PRIu644041") woke up with an interrupt while attaching - "4042"forwarding interrupt.",4043__FUNCTION__, static_cast<void *>(this), GetID());4044// The server may be spinning waiting for a process to appear, in which4045// case we should tell it to stop doing that. Normally, we don't NEED4046// to do that because we will next close the communication to the stub4047// and that will get it to shut down. But there are remote debugging4048// cases where relying on that side-effect causes the shutdown to be4049// flakey, so we should send a positive signal to interrupt the wait.4050Status error = HaltPrivate();4051BroadcastEvent(eBroadcastBitInterrupt, nullptr);4052} else if (StateIsRunningState(m_last_broadcast_state)) {4053LLDB_LOGF(log,4054"Process::%s (arg = %p, pid = %" PRIu644055") woke up with an interrupt - Halting.",4056__FUNCTION__, static_cast<void *>(this), GetID());4057Status error = HaltPrivate();4058if (error.Fail() && log)4059LLDB_LOGF(log,4060"Process::%s (arg = %p, pid = %" PRIu644061") failed to halt the process: %s",4062__FUNCTION__, static_cast<void *>(this), GetID(),4063error.AsCString());4064// Halt should generate a stopped event. Make a note of the fact that4065// we were doing the interrupt, so we can set the interrupted flag4066// after we receive the event. We deliberately set this to true even if4067// HaltPrivate failed, so that we can interrupt on the next natural4068// stop.4069interrupt_requested = true;4070} else {4071// This can happen when someone (e.g. Process::Halt) sees that we are4072// running and sends an interrupt request, but the process actually4073// stops before we receive it. In that case, we can just ignore the4074// request. We use m_last_broadcast_state, because the Stopped event4075// may not have been popped of the event queue yet, which is when the4076// public state gets updated.4077LLDB_LOGF(log,4078"Process::%s ignoring interrupt as we have already stopped.",4079__FUNCTION__);4080}4081continue;4082}40834084const StateType internal_state =4085Process::ProcessEventData::GetStateFromEvent(event_sp.get());40864087if (internal_state != eStateInvalid) {4088if (m_clear_thread_plans_on_stop &&4089StateIsStoppedState(internal_state, true)) {4090m_clear_thread_plans_on_stop = false;4091m_thread_list.DiscardThreadPlans();4092}40934094if (interrupt_requested) {4095if (StateIsStoppedState(internal_state, true)) {4096// We requested the interrupt, so mark this as such in the stop event4097// so clients can tell an interrupted process from a natural stop4098ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);4099interrupt_requested = false;4100} else if (log) {4101LLDB_LOGF(log,4102"Process::%s interrupt_requested, but a non-stopped "4103"state '%s' received.",4104__FUNCTION__, StateAsCString(internal_state));4105}4106}41074108HandlePrivateEvent(event_sp);4109}41104111if (internal_state == eStateInvalid || internal_state == eStateExited ||4112internal_state == eStateDetached) {4113LLDB_LOGF(log,4114"Process::%s (arg = %p, pid = %" PRIu644115") about to exit with internal state %s...",4116__FUNCTION__, static_cast<void *>(this), GetID(),4117StateAsCString(internal_state));41184119break;4120}4121}41224123// Verify log is still enabled before attempting to write to it...4124LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",4125__FUNCTION__, static_cast<void *>(this), GetID());41264127// If we are a secondary thread, then the primary thread we are working for4128// will have already acquired the public_run_lock, and isn't done with what4129// it was doing yet, so don't try to change it on the way out.4130if (!is_secondary_thread)4131m_public_run_lock.SetStopped();4132return {};4133}41344135// Process Event Data41364137Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp() {}41384139Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,4140StateType state)4141: EventData(), m_process_wp(), m_state(state) {4142if (process_sp)4143m_process_wp = process_sp;4144}41454146Process::ProcessEventData::~ProcessEventData() = default;41474148llvm::StringRef Process::ProcessEventData::GetFlavorString() {4149return "Process::ProcessEventData";4150}41514152llvm::StringRef Process::ProcessEventData::GetFlavor() const {4153return ProcessEventData::GetFlavorString();4154}41554156bool Process::ProcessEventData::ShouldStop(Event *event_ptr,4157bool &found_valid_stopinfo) {4158found_valid_stopinfo = false;41594160ProcessSP process_sp(m_process_wp.lock());4161if (!process_sp)4162return false;41634164ThreadList &curr_thread_list = process_sp->GetThreadList();4165uint32_t num_threads = curr_thread_list.GetSize();41664167// The actions might change one of the thread's stop_info's opinions about4168// whether we should stop the process, so we need to query that as we go.41694170// One other complication here, is that we try to catch any case where the4171// target has run (except for expressions) and immediately exit, but if we4172// get that wrong (which is possible) then the thread list might have4173// changed, and that would cause our iteration here to crash. We could4174// make a copy of the thread list, but we'd really like to also know if it4175// has changed at all, so we store the original thread ID's of all threads and4176// check what we get back against this list & bag out if anything differs.4177std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;4178for (uint32_t idx = 0; idx < num_threads; ++idx) {4179lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);41804181/*4182Filter out all suspended threads, they could not be the reason4183of stop and no need to perform any actions on them.4184*/4185if (thread_sp->GetResumeState() != eStateSuspended)4186not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());4187}41884189// Use this to track whether we should continue from here. We will only4190// continue the target running if no thread says we should stop. Of course4191// if some thread's PerformAction actually sets the target running, then it4192// doesn't matter what the other threads say...41934194bool still_should_stop = false;41954196// Sometimes - for instance if we have a bug in the stub we are talking to,4197// we stop but no thread has a valid stop reason. In that case we should4198// just stop, because we have no way of telling what the right thing to do4199// is, and it's better to let the user decide than continue behind their4200// backs.42014202for (auto [thread_sp, thread_index] : not_suspended_threads) {4203if (curr_thread_list.GetSize() != num_threads) {4204Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));4205LLDB_LOGF(4206log,4207"Number of threads changed from %u to %u while processing event.",4208num_threads, curr_thread_list.GetSize());4209break;4210}42114212if (thread_sp->GetIndexID() != thread_index) {4213Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));4214LLDB_LOG(log,4215"The thread {0} changed from {1} to {2} while processing event.",4216thread_sp.get(), thread_index, thread_sp->GetIndexID());4217break;4218}42194220StopInfoSP stop_info_sp = thread_sp->GetStopInfo();4221if (stop_info_sp && stop_info_sp->IsValid()) {4222found_valid_stopinfo = true;4223bool this_thread_wants_to_stop;4224if (stop_info_sp->GetOverrideShouldStop()) {4225this_thread_wants_to_stop =4226stop_info_sp->GetOverriddenShouldStopValue();4227} else {4228stop_info_sp->PerformAction(event_ptr);4229// The stop action might restart the target. If it does, then we4230// want to mark that in the event so that whoever is receiving it4231// will know to wait for the running event and reflect that state4232// appropriately. We also need to stop processing actions, since they4233// aren't expecting the target to be running.42344235// FIXME: we might have run.4236if (stop_info_sp->HasTargetRunSinceMe()) {4237SetRestarted(true);4238break;4239}42404241this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);4242}42434244if (!still_should_stop)4245still_should_stop = this_thread_wants_to_stop;4246}4247}42484249return still_should_stop;4250}42514252bool Process::ProcessEventData::ForwardEventToPendingListeners(4253Event *event_ptr) {4254// STDIO and the other async event notifications should always be forwarded.4255if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)4256return true;42574258// For state changed events, if the update state is zero, we are handling4259// this on the private state thread. We should wait for the public event.4260return m_update_state == 1;4261}42624263void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {4264// We only have work to do for state changed events:4265if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)4266return;42674268ProcessSP process_sp(m_process_wp.lock());42694270if (!process_sp)4271return;42724273// This function gets called twice for each event, once when the event gets4274// pulled off of the private process event queue, and then any number of4275// times, first when it gets pulled off of the public event queue, then other4276// times when we're pretending that this is where we stopped at the end of4277// expression evaluation. m_update_state is used to distinguish these three4278// cases; it is 0 when we're just pulling it off for private handling, and >4279// 1 for expression evaluation, and we don't want to do the breakpoint4280// command handling then.4281if (m_update_state != 1)4282return;42834284process_sp->SetPublicState(4285m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));42864287if (m_state == eStateStopped && !m_restarted) {4288// Let process subclasses know we are about to do a public stop and do4289// anything they might need to in order to speed up register and memory4290// accesses.4291process_sp->WillPublicStop();4292}42934294// If this is a halt event, even if the halt stopped with some reason other4295// than a plain interrupt (e.g. we had already stopped for a breakpoint when4296// the halt request came through) don't do the StopInfo actions, as they may4297// end up restarting the process.4298if (m_interrupted)4299return;43004301// If we're not stopped or have restarted, then skip the StopInfo actions:4302if (m_state != eStateStopped || m_restarted) {4303return;4304}43054306bool does_anybody_have_an_opinion = false;4307bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);43084309if (GetRestarted()) {4310return;4311}43124313if (!still_should_stop && does_anybody_have_an_opinion) {4314// We've been asked to continue, so do that here.4315SetRestarted(true);4316// Use the private resume method here, since we aren't changing the run4317// lock state.4318process_sp->PrivateResume();4319} else {4320bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&4321!process_sp->StateChangedIsHijackedForSynchronousResume();43224323if (!hijacked) {4324// If we didn't restart, run the Stop Hooks here.4325// Don't do that if state changed events aren't hooked up to the4326// public (or SyncResume) broadcasters. StopHooks are just for4327// real public stops. They might also restart the target,4328// so watch for that.4329if (process_sp->GetTarget().RunStopHooks())4330SetRestarted(true);4331}4332}4333}43344335void Process::ProcessEventData::Dump(Stream *s) const {4336ProcessSP process_sp(m_process_wp.lock());43374338if (process_sp)4339s->Printf(" process = %p (pid = %" PRIu64 "), ",4340static_cast<void *>(process_sp.get()), process_sp->GetID());4341else4342s->PutCString(" process = NULL, ");43434344s->Printf("state = %s", StateAsCString(GetState()));4345}43464347const Process::ProcessEventData *4348Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {4349if (event_ptr) {4350const EventData *event_data = event_ptr->GetData();4351if (event_data &&4352event_data->GetFlavor() == ProcessEventData::GetFlavorString())4353return static_cast<const ProcessEventData *>(event_ptr->GetData());4354}4355return nullptr;4356}43574358ProcessSP4359Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {4360ProcessSP process_sp;4361const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4362if (data)4363process_sp = data->GetProcessSP();4364return process_sp;4365}43664367StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {4368const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4369if (data == nullptr)4370return eStateInvalid;4371else4372return data->GetState();4373}43744375bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {4376const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4377if (data == nullptr)4378return false;4379else4380return data->GetRestarted();4381}43824383void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,4384bool new_value) {4385ProcessEventData *data =4386const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4387if (data != nullptr)4388data->SetRestarted(new_value);4389}43904391size_t4392Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {4393ProcessEventData *data =4394const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4395if (data != nullptr)4396return data->GetNumRestartedReasons();4397else4398return 0;4399}44004401const char *4402Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,4403size_t idx) {4404ProcessEventData *data =4405const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4406if (data != nullptr)4407return data->GetRestartedReasonAtIndex(idx);4408else4409return nullptr;4410}44114412void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,4413const char *reason) {4414ProcessEventData *data =4415const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4416if (data != nullptr)4417data->AddRestartedReason(reason);4418}44194420bool Process::ProcessEventData::GetInterruptedFromEvent(4421const Event *event_ptr) {4422const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4423if (data == nullptr)4424return false;4425else4426return data->GetInterrupted();4427}44284429void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,4430bool new_value) {4431ProcessEventData *data =4432const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4433if (data != nullptr)4434data->SetInterrupted(new_value);4435}44364437bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {4438ProcessEventData *data =4439const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4440if (data) {4441data->SetUpdateStateOnRemoval();4442return true;4443}4444return false;4445}44464447lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }44484449void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {4450exe_ctx.SetTargetPtr(&GetTarget());4451exe_ctx.SetProcessPtr(this);4452exe_ctx.SetThreadPtr(nullptr);4453exe_ctx.SetFramePtr(nullptr);4454}44554456// uint32_t4457// Process::ListProcessesMatchingName (const char *name, StringList &matches,4458// std::vector<lldb::pid_t> &pids)4459//{4460// return 0;4461//}4462//4463// ArchSpec4464// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)4465//{4466// return Host::GetArchSpecForExistingProcess (pid);4467//}4468//4469// ArchSpec4470// Process::GetArchSpecForExistingProcess (const char *process_name)4471//{4472// return Host::GetArchSpecForExistingProcess (process_name);4473//}44744475EventSP Process::CreateEventFromProcessState(uint32_t event_type) {4476auto event_data_sp =4477std::make_shared<ProcessEventData>(shared_from_this(), GetState());4478return std::make_shared<Event>(event_type, event_data_sp);4479}44804481void Process::AppendSTDOUT(const char *s, size_t len) {4482std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4483m_stdout_data.append(s, len);4484auto event_sp = CreateEventFromProcessState(eBroadcastBitSTDOUT);4485BroadcastEventIfUnique(event_sp);4486}44874488void Process::AppendSTDERR(const char *s, size_t len) {4489std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4490m_stderr_data.append(s, len);4491auto event_sp = CreateEventFromProcessState(eBroadcastBitSTDERR);4492BroadcastEventIfUnique(event_sp);4493}44944495void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {4496std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);4497m_profile_data.push_back(one_profile_data);4498auto event_sp = CreateEventFromProcessState(eBroadcastBitProfileData);4499BroadcastEventIfUnique(event_sp);4500}45014502void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,4503const StructuredDataPluginSP &plugin_sp) {4504auto data_sp = std::make_shared<EventDataStructuredData>(4505shared_from_this(), object_sp, plugin_sp);4506BroadcastEvent(eBroadcastBitStructuredData, data_sp);4507}45084509StructuredDataPluginSP4510Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {4511auto find_it = m_structured_data_plugin_map.find(type_name);4512if (find_it != m_structured_data_plugin_map.end())4513return find_it->second;4514else4515return StructuredDataPluginSP();4516}45174518size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {4519std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);4520if (m_profile_data.empty())4521return 0;45224523std::string &one_profile_data = m_profile_data.front();4524size_t bytes_available = one_profile_data.size();4525if (bytes_available > 0) {4526Log *log = GetLog(LLDBLog::Process);4527LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",4528static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4529if (bytes_available > buf_size) {4530memcpy(buf, one_profile_data.c_str(), buf_size);4531one_profile_data.erase(0, buf_size);4532bytes_available = buf_size;4533} else {4534memcpy(buf, one_profile_data.c_str(), bytes_available);4535m_profile_data.erase(m_profile_data.begin());4536}4537}4538return bytes_available;4539}45404541// Process STDIO45424543size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {4544std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4545size_t bytes_available = m_stdout_data.size();4546if (bytes_available > 0) {4547Log *log = GetLog(LLDBLog::Process);4548LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",4549static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4550if (bytes_available > buf_size) {4551memcpy(buf, m_stdout_data.c_str(), buf_size);4552m_stdout_data.erase(0, buf_size);4553bytes_available = buf_size;4554} else {4555memcpy(buf, m_stdout_data.c_str(), bytes_available);4556m_stdout_data.clear();4557}4558}4559return bytes_available;4560}45614562size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {4563std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);4564size_t bytes_available = m_stderr_data.size();4565if (bytes_available > 0) {4566Log *log = GetLog(LLDBLog::Process);4567LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",4568static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4569if (bytes_available > buf_size) {4570memcpy(buf, m_stderr_data.c_str(), buf_size);4571m_stderr_data.erase(0, buf_size);4572bytes_available = buf_size;4573} else {4574memcpy(buf, m_stderr_data.c_str(), bytes_available);4575m_stderr_data.clear();4576}4577}4578return bytes_available;4579}45804581void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,4582size_t src_len) {4583Process *process = (Process *)baton;4584process->AppendSTDOUT(static_cast<const char *>(src), src_len);4585}45864587class IOHandlerProcessSTDIO : public IOHandler {4588public:4589IOHandlerProcessSTDIO(Process *process, int write_fd)4590: IOHandler(process->GetTarget().GetDebugger(),4591IOHandler::Type::ProcessIO),4592m_process(process),4593m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),4594m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {4595m_pipe.CreateNew(false);4596}45974598~IOHandlerProcessSTDIO() override = default;45994600void SetIsRunning(bool running) {4601std::lock_guard<std::mutex> guard(m_mutex);4602SetIsDone(!running);4603m_is_running = running;4604}46054606// Each IOHandler gets to run until it is done. It should read data from the4607// "in" and place output into "out" and "err and return when done.4608void Run() override {4609if (!m_read_file.IsValid() || !m_write_file.IsValid() ||4610!m_pipe.CanRead() || !m_pipe.CanWrite()) {4611SetIsDone(true);4612return;4613}46144615SetIsDone(false);4616const int read_fd = m_read_file.GetDescriptor();4617Terminal terminal(read_fd);4618TerminalState terminal_state(terminal, false);4619// FIXME: error handling?4620llvm::consumeError(terminal.SetCanonical(false));4621llvm::consumeError(terminal.SetEcho(false));4622// FD_ZERO, FD_SET are not supported on windows4623#ifndef _WIN324624const int pipe_read_fd = m_pipe.GetReadFileDescriptor();4625SetIsRunning(true);4626while (true) {4627{4628std::lock_guard<std::mutex> guard(m_mutex);4629if (GetIsDone())4630break;4631}46324633SelectHelper select_helper;4634select_helper.FDSetRead(read_fd);4635select_helper.FDSetRead(pipe_read_fd);4636Status error = select_helper.Select();46374638if (error.Fail())4639break;46404641char ch = 0;4642size_t n;4643if (select_helper.FDIsSetRead(read_fd)) {4644n = 1;4645if (m_read_file.Read(&ch, n).Success() && n == 1) {4646if (m_write_file.Write(&ch, n).Fail() || n != 1)4647break;4648} else4649break;4650}46514652if (select_helper.FDIsSetRead(pipe_read_fd)) {4653size_t bytes_read;4654// Consume the interrupt byte4655Status error = m_pipe.Read(&ch, 1, bytes_read);4656if (error.Success()) {4657if (ch == 'q')4658break;4659if (ch == 'i')4660if (StateIsRunningState(m_process->GetState()))4661m_process->SendAsyncInterrupt();4662}4663}4664}4665SetIsRunning(false);4666#endif4667}46684669void Cancel() override {4670std::lock_guard<std::mutex> guard(m_mutex);4671SetIsDone(true);4672// Only write to our pipe to cancel if we are in4673// IOHandlerProcessSTDIO::Run(). We can end up with a python command that4674// is being run from the command interpreter:4675//4676// (lldb) step_process_thousands_of_times4677//4678// In this case the command interpreter will be in the middle of handling4679// the command and if the process pushes and pops the IOHandler thousands4680// of times, we can end up writing to m_pipe without ever consuming the4681// bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up4682// deadlocking when the pipe gets fed up and blocks until data is consumed.4683if (m_is_running) {4684char ch = 'q'; // Send 'q' for quit4685size_t bytes_written = 0;4686m_pipe.Write(&ch, 1, bytes_written);4687}4688}46894690bool Interrupt() override {4691// Do only things that are safe to do in an interrupt context (like in a4692// SIGINT handler), like write 1 byte to a file descriptor. This will4693// interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte4694// that was written to the pipe and then call4695// m_process->SendAsyncInterrupt() from a much safer location in code.4696if (m_active) {4697char ch = 'i'; // Send 'i' for interrupt4698size_t bytes_written = 0;4699Status result = m_pipe.Write(&ch, 1, bytes_written);4700return result.Success();4701} else {4702// This IOHandler might be pushed on the stack, but not being run4703// currently so do the right thing if we aren't actively watching for4704// STDIN by sending the interrupt to the process. Otherwise the write to4705// the pipe above would do nothing. This can happen when the command4706// interpreter is running and gets a "expression ...". It will be on the4707// IOHandler thread and sending the input is complete to the delegate4708// which will cause the expression to run, which will push the process IO4709// handler, but not run it.47104711if (StateIsRunningState(m_process->GetState())) {4712m_process->SendAsyncInterrupt();4713return true;4714}4715}4716return false;4717}47184719void GotEOF() override {}47204721protected:4722Process *m_process;4723NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB4724NativeFile m_write_file; // Write to this file (usually the primary pty for4725// getting io to debuggee)4726Pipe m_pipe;4727std::mutex m_mutex;4728bool m_is_running = false;4729};47304731void Process::SetSTDIOFileDescriptor(int fd) {4732// First set up the Read Thread for reading/handling process I/O4733m_stdio_communication.SetConnection(4734std::make_unique<ConnectionFileDescriptor>(fd, true));4735if (m_stdio_communication.IsConnected()) {4736m_stdio_communication.SetReadThreadBytesReceivedCallback(4737STDIOReadThreadBytesReceived, this);4738m_stdio_communication.StartReadThread();47394740// Now read thread is set up, set up input reader.4741{4742std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4743if (!m_process_input_reader)4744m_process_input_reader =4745std::make_shared<IOHandlerProcessSTDIO>(this, fd);4746}4747}4748}47494750bool Process::ProcessIOHandlerIsActive() {4751std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4752IOHandlerSP io_handler_sp(m_process_input_reader);4753if (io_handler_sp)4754return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);4755return false;4756}47574758bool Process::PushProcessIOHandler() {4759std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4760IOHandlerSP io_handler_sp(m_process_input_reader);4761if (io_handler_sp) {4762Log *log = GetLog(LLDBLog::Process);4763LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);47644765io_handler_sp->SetIsDone(false);4766// If we evaluate an utility function, then we don't cancel the current4767// IOHandler. Our IOHandler is non-interactive and shouldn't disturb the4768// existing IOHandler that potentially provides the user interface (e.g.4769// the IOHandler for Editline).4770bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();4771GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,4772cancel_top_handler);4773return true;4774}4775return false;4776}47774778bool Process::PopProcessIOHandler() {4779std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4780IOHandlerSP io_handler_sp(m_process_input_reader);4781if (io_handler_sp)4782return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);4783return false;4784}47854786// The process needs to know about installed plug-ins4787void Process::SettingsInitialize() { Thread::SettingsInitialize(); }47884789void Process::SettingsTerminate() { Thread::SettingsTerminate(); }47904791namespace {4792// RestorePlanState is used to record the "is private", "is controlling" and4793// "okay4794// to discard" fields of the plan we are running, and reset it on Clean or on4795// destruction. It will only reset the state once, so you can call Clean and4796// then monkey with the state and it won't get reset on you again.47974798class RestorePlanState {4799public:4800RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)4801: m_thread_plan_sp(thread_plan_sp) {4802if (m_thread_plan_sp) {4803m_private = m_thread_plan_sp->GetPrivate();4804m_is_controlling = m_thread_plan_sp->IsControllingPlan();4805m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();4806}4807}48084809~RestorePlanState() { Clean(); }48104811void Clean() {4812if (!m_already_reset && m_thread_plan_sp) {4813m_already_reset = true;4814m_thread_plan_sp->SetPrivate(m_private);4815m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);4816m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);4817}4818}48194820private:4821lldb::ThreadPlanSP m_thread_plan_sp;4822bool m_already_reset = false;4823bool m_private = false;4824bool m_is_controlling = false;4825bool m_okay_to_discard = false;4826};4827} // anonymous namespace48284829static microseconds4830GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {4831const milliseconds default_one_thread_timeout(250);48324833// If the overall wait is forever, then we don't need to worry about it.4834if (!options.GetTimeout()) {4835return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()4836: default_one_thread_timeout;4837}48384839// If the one thread timeout is set, use it.4840if (options.GetOneThreadTimeout())4841return *options.GetOneThreadTimeout();48424843// Otherwise use half the total timeout, bounded by the4844// default_one_thread_timeout.4845return std::min<microseconds>(default_one_thread_timeout,4846*options.GetTimeout() / 2);4847}48484849static Timeout<std::micro>4850GetExpressionTimeout(const EvaluateExpressionOptions &options,4851bool before_first_timeout) {4852// If we are going to run all threads the whole time, or if we are only going4853// to run one thread, we can just return the overall timeout.4854if (!options.GetStopOthers() || !options.GetTryAllThreads())4855return options.GetTimeout();48564857if (before_first_timeout)4858return GetOneThreadExpressionTimeout(options);48594860if (!options.GetTimeout())4861return std::nullopt;4862else4863return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);4864}48654866static std::optional<ExpressionResults>4867HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,4868RestorePlanState &restorer, const EventSP &event_sp,4869EventSP &event_to_broadcast_sp,4870const EvaluateExpressionOptions &options,4871bool handle_interrupts) {4872Log *log = GetLog(LLDBLog::Step | LLDBLog::Process);48734874ThreadSP thread_sp = thread_plan_sp->GetTarget()4875.GetProcessSP()4876->GetThreadList()4877.FindThreadByID(thread_id);4878if (!thread_sp) {4879LLDB_LOG(log,4880"The thread on which we were running the "4881"expression: tid = {0}, exited while "4882"the expression was running.",4883thread_id);4884return eExpressionThreadVanished;4885}48864887ThreadPlanSP plan = thread_sp->GetCompletedPlan();4888if (plan == thread_plan_sp && plan->PlanSucceeded()) {4889LLDB_LOG(log, "execution completed successfully");48904891// Restore the plan state so it will get reported as intended when we are4892// done.4893restorer.Clean();4894return eExpressionCompleted;4895}48964897StopInfoSP stop_info_sp = thread_sp->GetStopInfo();4898if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&4899stop_info_sp->ShouldNotify(event_sp.get())) {4900LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());4901if (!options.DoesIgnoreBreakpoints()) {4902// Restore the plan state and then force Private to false. We are going4903// to stop because of this plan so we need it to become a public plan or4904// it won't report correctly when we continue to its termination later4905// on.4906restorer.Clean();4907thread_plan_sp->SetPrivate(false);4908event_to_broadcast_sp = event_sp;4909}4910return eExpressionHitBreakpoint;4911}49124913if (!handle_interrupts &&4914Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))4915return std::nullopt;49164917LLDB_LOG(log, "thread plan did not successfully complete");4918if (!options.DoesUnwindOnError())4919event_to_broadcast_sp = event_sp;4920return eExpressionInterrupted;4921}49224923ExpressionResults4924Process::RunThreadPlan(ExecutionContext &exe_ctx,4925lldb::ThreadPlanSP &thread_plan_sp,4926const EvaluateExpressionOptions &options,4927DiagnosticManager &diagnostic_manager) {4928ExpressionResults return_value = eExpressionSetupError;49294930std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);49314932if (!thread_plan_sp) {4933diagnostic_manager.PutString(4934lldb::eSeverityError, "RunThreadPlan called with empty thread plan.");4935return eExpressionSetupError;4936}49374938if (!thread_plan_sp->ValidatePlan(nullptr)) {4939diagnostic_manager.PutString(4940lldb::eSeverityError,4941"RunThreadPlan called with an invalid thread plan.");4942return eExpressionSetupError;4943}49444945if (exe_ctx.GetProcessPtr() != this) {4946diagnostic_manager.PutString(lldb::eSeverityError,4947"RunThreadPlan called on wrong process.");4948return eExpressionSetupError;4949}49504951Thread *thread = exe_ctx.GetThreadPtr();4952if (thread == nullptr) {4953diagnostic_manager.PutString(lldb::eSeverityError,4954"RunThreadPlan called with invalid thread.");4955return eExpressionSetupError;4956}49574958// Record the thread's id so we can tell when a thread we were using4959// to run the expression exits during the expression evaluation.4960lldb::tid_t expr_thread_id = thread->GetID();49614962// We need to change some of the thread plan attributes for the thread plan4963// runner. This will restore them when we are done:49644965RestorePlanState thread_plan_restorer(thread_plan_sp);49664967// We rely on the thread plan we are running returning "PlanCompleted" if4968// when it successfully completes. For that to be true the plan can't be4969// private - since private plans suppress themselves in the GetCompletedPlan4970// call.49714972thread_plan_sp->SetPrivate(false);49734974// The plans run with RunThreadPlan also need to be terminal controlling plans4975// or when they are done we will end up asking the plan above us whether we4976// should stop, which may give the wrong answer.49774978thread_plan_sp->SetIsControllingPlan(true);4979thread_plan_sp->SetOkayToDiscard(false);49804981// If we are running some utility expression for LLDB, we now have to mark4982// this in the ProcesModID of this process. This RAII takes care of marking4983// and reverting the mark it once we are done running the expression.4984UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);49854986if (m_private_state.GetValue() != eStateStopped) {4987diagnostic_manager.PutString(4988lldb::eSeverityError,4989"RunThreadPlan called while the private state was not stopped.");4990return eExpressionSetupError;4991}49924993// Save the thread & frame from the exe_ctx for restoration after we run4994const uint32_t thread_idx_id = thread->GetIndexID();4995StackFrameSP selected_frame_sp =4996thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);4997if (!selected_frame_sp) {4998thread->SetSelectedFrame(nullptr);4999selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);5000if (!selected_frame_sp) {5001diagnostic_manager.Printf(5002lldb::eSeverityError,5003"RunThreadPlan called without a selected frame on thread %d",5004thread_idx_id);5005return eExpressionSetupError;5006}5007}50085009// Make sure the timeout values make sense. The one thread timeout needs to5010// be smaller than the overall timeout.5011if (options.GetOneThreadTimeout() && options.GetTimeout() &&5012*options.GetTimeout() < *options.GetOneThreadTimeout()) {5013diagnostic_manager.PutString(lldb::eSeverityError,5014"RunThreadPlan called with one thread "5015"timeout greater than total timeout");5016return eExpressionSetupError;5017}50185019StackID ctx_frame_id = selected_frame_sp->GetStackID();50205021// N.B. Running the target may unset the currently selected thread and frame.5022// We don't want to do that either, so we should arrange to reset them as5023// well.50245025lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();50265027uint32_t selected_tid;5028StackID selected_stack_id;5029if (selected_thread_sp) {5030selected_tid = selected_thread_sp->GetIndexID();5031selected_stack_id =5032selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)5033->GetStackID();5034} else {5035selected_tid = LLDB_INVALID_THREAD_ID;5036}50375038HostThread backup_private_state_thread;5039lldb::StateType old_state = eStateInvalid;5040lldb::ThreadPlanSP stopper_base_plan_sp;50415042Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));5043if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {5044// Yikes, we are running on the private state thread! So we can't wait for5045// public events on this thread, since we are the thread that is generating5046// public events. The simplest thing to do is to spin up a temporary thread5047// to handle private state thread events while we are fielding public5048// events here.5049LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "5050"another state thread to handle the events.");50515052backup_private_state_thread = m_private_state_thread;50535054// One other bit of business: we want to run just this thread plan and5055// anything it pushes, and then stop, returning control here. But in the5056// normal course of things, the plan above us on the stack would be given a5057// shot at the stop event before deciding to stop, and we don't want that.5058// So we insert a "stopper" base plan on the stack before the plan we want5059// to run. Since base plans always stop and return control to the user,5060// that will do just what we want.5061stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));5062thread->QueueThreadPlan(stopper_base_plan_sp, false);5063// Have to make sure our public state is stopped, since otherwise the5064// reporting logic below doesn't work correctly.5065old_state = m_public_state.GetValue();5066m_public_state.SetValueNoLock(eStateStopped);50675068// Now spin up the private state thread:5069StartPrivateStateThread(true);5070}50715072thread->QueueThreadPlan(5073thread_plan_sp, false); // This used to pass "true" does that make sense?50745075if (options.GetDebug()) {5076// In this case, we aren't actually going to run, we just want to stop5077// right away. Flush this thread so we will refetch the stacks and show the5078// correct backtrace.5079// FIXME: To make this prettier we should invent some stop reason for this,5080// but that5081// is only cosmetic, and this functionality is only of use to lldb5082// developers who can live with not pretty...5083thread->Flush();5084return eExpressionStoppedForDebug;5085}50865087ListenerSP listener_sp(5088Listener::MakeListener("lldb.process.listener.run-thread-plan"));50895090lldb::EventSP event_to_broadcast_sp;50915092{5093// This process event hijacker Hijacks the Public events and its destructor5094// makes sure that the process events get restored on exit to the function.5095//5096// If the event needs to propagate beyond the hijacker (e.g., the process5097// exits during execution), then the event is put into5098// event_to_broadcast_sp for rebroadcasting.50995100ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);51015102if (log) {5103StreamString s;5104thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);5105LLDB_LOGF(log,5106"Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx645107" to run thread plan \"%s\".",5108thread_idx_id, expr_thread_id, s.GetData());5109}51105111bool got_event;5112lldb::EventSP event_sp;5113lldb::StateType stop_state = lldb::eStateInvalid;51145115bool before_first_timeout = true; // This is set to false the first time5116// that we have to halt the target.5117bool do_resume = true;5118bool handle_running_event = true;51195120// This is just for accounting:5121uint32_t num_resumes = 0;51225123// If we are going to run all threads the whole time, or if we are only5124// going to run one thread, then we don't need the first timeout. So we5125// pretend we are after the first timeout already.5126if (!options.GetStopOthers() || !options.GetTryAllThreads())5127before_first_timeout = false;51285129LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",5130options.GetStopOthers(), options.GetTryAllThreads(),5131before_first_timeout);51325133// This isn't going to work if there are unfetched events on the queue. Are5134// there cases where we might want to run the remaining events here, and5135// then try to call the function? That's probably being too tricky for our5136// own good.51375138Event *other_events = listener_sp->PeekAtNextEvent();5139if (other_events != nullptr) {5140diagnostic_manager.PutString(5141lldb::eSeverityError,5142"RunThreadPlan called with pending events on the queue.");5143return eExpressionSetupError;5144}51455146// We also need to make sure that the next event is delivered. We might be5147// calling a function as part of a thread plan, in which case the last5148// delivered event could be the running event, and we don't want event5149// coalescing to cause us to lose OUR running event...5150ForceNextEventDelivery();51515152// This while loop must exit out the bottom, there's cleanup that we need to do5153// when we are done. So don't call return anywhere within it.51545155#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT5156// It's pretty much impossible to write test cases for things like: One5157// thread timeout expires, I go to halt, but the process already stopped on5158// the function call stop breakpoint. Turning on this define will make us5159// not fetch the first event till after the halt. So if you run a quick5160// function, it will have completed, and the completion event will be5161// waiting, when you interrupt for halt. The expression evaluation should5162// still succeed.5163bool miss_first_event = true;5164#endif5165while (true) {5166// We usually want to resume the process if we get to the top of the5167// loop. The only exception is if we get two running events with no5168// intervening stop, which can happen, we will just wait for then next5169// stop event.5170LLDB_LOGF(log,5171"Top of while loop: do_resume: %i handle_running_event: %i "5172"before_first_timeout: %i.",5173do_resume, handle_running_event, before_first_timeout);51745175if (do_resume || handle_running_event) {5176// Do the initial resume and wait for the running event before going5177// further.51785179if (do_resume) {5180num_resumes++;5181Status resume_error = PrivateResume();5182if (!resume_error.Success()) {5183diagnostic_manager.Printf(5184lldb::eSeverityError,5185"couldn't resume inferior the %d time: \"%s\".", num_resumes,5186resume_error.AsCString());5187return_value = eExpressionSetupError;5188break;5189}5190}51915192got_event =5193listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());5194if (!got_event) {5195LLDB_LOGF(log,5196"Process::RunThreadPlan(): didn't get any event after "5197"resume %" PRIu32 ", exiting.",5198num_resumes);51995200diagnostic_manager.Printf(lldb::eSeverityError,5201"didn't get any event after resume %" PRIu325202", exiting.",5203num_resumes);5204return_value = eExpressionSetupError;5205break;5206}52075208stop_state =5209Process::ProcessEventData::GetStateFromEvent(event_sp.get());52105211if (stop_state != eStateRunning) {5212bool restarted = false;52135214if (stop_state == eStateStopped) {5215restarted = Process::ProcessEventData::GetRestartedFromEvent(5216event_sp.get());5217LLDB_LOGF(5218log,5219"Process::RunThreadPlan(): didn't get running event after "5220"resume %d, got %s instead (restarted: %i, do_resume: %i, "5221"handle_running_event: %i).",5222num_resumes, StateAsCString(stop_state), restarted, do_resume,5223handle_running_event);5224}52255226if (restarted) {5227// This is probably an overabundance of caution, I don't think I5228// should ever get a stopped & restarted event here. But if I do,5229// the best thing is to Halt and then get out of here.5230const bool clear_thread_plans = false;5231const bool use_run_lock = false;5232Halt(clear_thread_plans, use_run_lock);5233}52345235diagnostic_manager.Printf(5236lldb::eSeverityError,5237"didn't get running event after initial resume, got %s instead.",5238StateAsCString(stop_state));5239return_value = eExpressionSetupError;5240break;5241}52425243if (log)5244log->PutCString("Process::RunThreadPlan(): resuming succeeded.");5245// We need to call the function synchronously, so spin waiting for it5246// to return. If we get interrupted while executing, we're going to5247// lose our context, and won't be able to gather the result at this5248// point. We set the timeout AFTER the resume, since the resume takes5249// some time and we don't want to charge that to the timeout.5250} else {5251if (log)5252log->PutCString("Process::RunThreadPlan(): waiting for next event.");5253}52545255do_resume = true;5256handle_running_event = true;52575258// Now wait for the process to stop again:5259event_sp.reset();52605261Timeout<std::micro> timeout =5262GetExpressionTimeout(options, before_first_timeout);5263if (log) {5264if (timeout) {5265auto now = system_clock::now();5266LLDB_LOGF(log,5267"Process::RunThreadPlan(): about to wait - now is %s - "5268"endpoint is %s",5269llvm::to_string(now).c_str(),5270llvm::to_string(now + *timeout).c_str());5271} else {5272LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");5273}5274}52755276#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT5277// See comment above...5278if (miss_first_event) {5279std::this_thread::sleep_for(std::chrono::milliseconds(1));5280miss_first_event = false;5281got_event = false;5282} else5283#endif5284got_event = listener_sp->GetEvent(event_sp, timeout);52855286if (got_event) {5287if (event_sp) {5288bool keep_going = false;5289if (event_sp->GetType() == eBroadcastBitInterrupt) {5290const bool clear_thread_plans = false;5291const bool use_run_lock = false;5292Halt(clear_thread_plans, use_run_lock);5293return_value = eExpressionInterrupted;5294diagnostic_manager.PutString(lldb::eSeverityInfo,5295"execution halted by user interrupt.");5296LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "5297"eBroadcastBitInterrupted, exiting.");5298break;5299} else {5300stop_state =5301Process::ProcessEventData::GetStateFromEvent(event_sp.get());5302LLDB_LOGF(log,5303"Process::RunThreadPlan(): in while loop, got event: %s.",5304StateAsCString(stop_state));53055306switch (stop_state) {5307case lldb::eStateStopped: {5308if (Process::ProcessEventData::GetRestartedFromEvent(5309event_sp.get())) {5310// If we were restarted, we just need to go back up to fetch5311// another event.5312LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "5313"restart, so we'll continue waiting.");5314keep_going = true;5315do_resume = false;5316handle_running_event = true;5317} else {5318const bool handle_interrupts = true;5319return_value = *HandleStoppedEvent(5320expr_thread_id, thread_plan_sp, thread_plan_restorer,5321event_sp, event_to_broadcast_sp, options,5322handle_interrupts);5323if (return_value == eExpressionThreadVanished)5324keep_going = false;5325}5326} break;53275328case lldb::eStateRunning:5329// This shouldn't really happen, but sometimes we do get two5330// running events without an intervening stop, and in that case5331// we should just go back to waiting for the stop.5332do_resume = false;5333keep_going = true;5334handle_running_event = false;5335break;53365337default:5338LLDB_LOGF(log,5339"Process::RunThreadPlan(): execution stopped with "5340"unexpected state: %s.",5341StateAsCString(stop_state));53425343if (stop_state == eStateExited)5344event_to_broadcast_sp = event_sp;53455346diagnostic_manager.PutString(5347lldb::eSeverityError,5348"execution stopped with unexpected state.");5349return_value = eExpressionInterrupted;5350break;5351}5352}53535354if (keep_going)5355continue;5356else5357break;5358} else {5359if (log)5360log->PutCString("Process::RunThreadPlan(): got_event was true, but "5361"the event pointer was null. How odd...");5362return_value = eExpressionInterrupted;5363break;5364}5365} else {5366// If we didn't get an event that means we've timed out... We will5367// interrupt the process here. Depending on what we were asked to do5368// we will either exit, or try with all threads running for the same5369// timeout.53705371if (log) {5372if (options.GetTryAllThreads()) {5373if (before_first_timeout) {5374LLDB_LOG(log,5375"Running function with one thread timeout timed out.");5376} else5377LLDB_LOG(log, "Restarting function with all threads enabled and "5378"timeout: {0} timed out, abandoning execution.",5379timeout);5380} else5381LLDB_LOG(log, "Running function with timeout: {0} timed out, "5382"abandoning execution.",5383timeout);5384}53855386// It is possible that between the time we issued the Halt, and we get5387// around to calling Halt the target could have stopped. That's fine,5388// Halt will figure that out and send the appropriate Stopped event.5389// BUT it is also possible that we stopped & restarted (e.g. hit a5390// signal with "stop" set to false.) In5391// that case, we'll get the stopped & restarted event, and we should go5392// back to waiting for the Halt's stopped event. That's what this5393// while loop does.53945395bool back_to_top = true;5396uint32_t try_halt_again = 0;5397bool do_halt = true;5398const uint32_t num_retries = 5;5399while (try_halt_again < num_retries) {5400Status halt_error;5401if (do_halt) {5402LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");5403const bool clear_thread_plans = false;5404const bool use_run_lock = false;5405Halt(clear_thread_plans, use_run_lock);5406}5407if (halt_error.Success()) {5408if (log)5409log->PutCString("Process::RunThreadPlan(): Halt succeeded.");54105411got_event =5412listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());54135414if (got_event) {5415stop_state =5416Process::ProcessEventData::GetStateFromEvent(event_sp.get());5417if (log) {5418LLDB_LOGF(log,5419"Process::RunThreadPlan(): Stopped with event: %s",5420StateAsCString(stop_state));5421if (stop_state == lldb::eStateStopped &&5422Process::ProcessEventData::GetInterruptedFromEvent(5423event_sp.get()))5424log->PutCString(" Event was the Halt interruption event.");5425}54265427if (stop_state == lldb::eStateStopped) {5428if (Process::ProcessEventData::GetRestartedFromEvent(5429event_sp.get())) {5430if (log)5431log->PutCString("Process::RunThreadPlan(): Went to halt "5432"but got a restarted event, there must be "5433"an un-restarted stopped event so try "5434"again... "5435"Exiting wait loop.");5436try_halt_again++;5437do_halt = false;5438continue;5439}54405441// Between the time we initiated the Halt and the time we5442// delivered it, the process could have already finished its5443// job. Check that here:5444const bool handle_interrupts = false;5445if (auto result = HandleStoppedEvent(5446expr_thread_id, thread_plan_sp, thread_plan_restorer,5447event_sp, event_to_broadcast_sp, options,5448handle_interrupts)) {5449return_value = *result;5450back_to_top = false;5451break;5452}54535454if (!options.GetTryAllThreads()) {5455if (log)5456log->PutCString("Process::RunThreadPlan(): try_all_threads "5457"was false, we stopped so now we're "5458"quitting.");5459return_value = eExpressionInterrupted;5460back_to_top = false;5461break;5462}54635464if (before_first_timeout) {5465// Set all the other threads to run, and return to the top of5466// the loop, which will continue;5467before_first_timeout = false;5468thread_plan_sp->SetStopOthers(false);5469if (log)5470log->PutCString(5471"Process::RunThreadPlan(): about to resume.");54725473back_to_top = true;5474break;5475} else {5476// Running all threads failed, so return Interrupted.5477if (log)5478log->PutCString("Process::RunThreadPlan(): running all "5479"threads timed out.");5480return_value = eExpressionInterrupted;5481back_to_top = false;5482break;5483}5484}5485} else {5486if (log)5487log->PutCString("Process::RunThreadPlan(): halt said it "5488"succeeded, but I got no event. "5489"I'm getting out of here passing Interrupted.");5490return_value = eExpressionInterrupted;5491back_to_top = false;5492break;5493}5494} else {5495try_halt_again++;5496continue;5497}5498}54995500if (!back_to_top || try_halt_again > num_retries)5501break;5502else5503continue;5504}5505} // END WAIT LOOP55065507// If we had to start up a temporary private state thread to run this5508// thread plan, shut it down now.5509if (backup_private_state_thread.IsJoinable()) {5510StopPrivateStateThread();5511Status error;5512m_private_state_thread = backup_private_state_thread;5513if (stopper_base_plan_sp) {5514thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);5515}5516if (old_state != eStateInvalid)5517m_public_state.SetValueNoLock(old_state);5518}55195520// If our thread went away on us, we need to get out of here without5521// doing any more work. We don't have to clean up the thread plan, that5522// will have happened when the Thread was destroyed.5523if (return_value == eExpressionThreadVanished) {5524return return_value;5525}55265527if (return_value != eExpressionCompleted && log) {5528// Print a backtrace into the log so we can figure out where we are:5529StreamString s;5530s.PutCString("Thread state after unsuccessful completion: \n");5531thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);5532log->PutString(s.GetString());5533}5534// Restore the thread state if we are going to discard the plan execution.5535// There are three cases where this could happen: 1) The execution5536// successfully completed 2) We hit a breakpoint, and ignore_breakpoints5537// was true 3) We got some other error, and discard_on_error was true5538bool should_unwind = (return_value == eExpressionInterrupted &&5539options.DoesUnwindOnError()) ||5540(return_value == eExpressionHitBreakpoint &&5541options.DoesIgnoreBreakpoints());55425543if (return_value == eExpressionCompleted || should_unwind) {5544thread_plan_sp->RestoreThreadState();5545}55465547// Now do some processing on the results of the run:5548if (return_value == eExpressionInterrupted ||5549return_value == eExpressionHitBreakpoint) {5550if (log) {5551StreamString s;5552if (event_sp)5553event_sp->Dump(&s);5554else {5555log->PutCString("Process::RunThreadPlan(): Stop event that "5556"interrupted us is NULL.");5557}55585559StreamString ts;55605561const char *event_explanation = nullptr;55625563do {5564if (!event_sp) {5565event_explanation = "<no event>";5566break;5567} else if (event_sp->GetType() == eBroadcastBitInterrupt) {5568event_explanation = "<user interrupt>";5569break;5570} else {5571const Process::ProcessEventData *event_data =5572Process::ProcessEventData::GetEventDataFromEvent(5573event_sp.get());55745575if (!event_data) {5576event_explanation = "<no event data>";5577break;5578}55795580Process *process = event_data->GetProcessSP().get();55815582if (!process) {5583event_explanation = "<no process>";5584break;5585}55865587ThreadList &thread_list = process->GetThreadList();55885589uint32_t num_threads = thread_list.GetSize();5590uint32_t thread_index;55915592ts.Printf("<%u threads> ", num_threads);55935594for (thread_index = 0; thread_index < num_threads; ++thread_index) {5595Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();55965597if (!thread) {5598ts.Printf("<?> ");5599continue;5600}56015602ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());5603RegisterContext *register_context =5604thread->GetRegisterContext().get();56055606if (register_context)5607ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());5608else5609ts.Printf("[ip unknown] ");56105611// Show the private stop info here, the public stop info will be5612// from the last natural stop.5613lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();5614if (stop_info_sp) {5615const char *stop_desc = stop_info_sp->GetDescription();5616if (stop_desc)5617ts.PutCString(stop_desc);5618}5619ts.Printf(">");5620}56215622event_explanation = ts.GetData();5623}5624} while (false);56255626if (event_explanation)5627LLDB_LOGF(log,5628"Process::RunThreadPlan(): execution interrupted: %s %s",5629s.GetData(), event_explanation);5630else5631LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",5632s.GetData());5633}56345635if (should_unwind) {5636LLDB_LOGF(log,5637"Process::RunThreadPlan: ExecutionInterrupted - "5638"discarding thread plans up to %p.",5639static_cast<void *>(thread_plan_sp.get()));5640thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5641} else {5642LLDB_LOGF(log,5643"Process::RunThreadPlan: ExecutionInterrupted - for "5644"plan: %p not discarding.",5645static_cast<void *>(thread_plan_sp.get()));5646}5647} else if (return_value == eExpressionSetupError) {5648if (log)5649log->PutCString("Process::RunThreadPlan(): execution set up error.");56505651if (options.DoesUnwindOnError()) {5652thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5653}5654} else {5655if (thread->IsThreadPlanDone(thread_plan_sp.get())) {5656if (log)5657log->PutCString("Process::RunThreadPlan(): thread plan is done");5658return_value = eExpressionCompleted;5659} else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {5660if (log)5661log->PutCString(5662"Process::RunThreadPlan(): thread plan was discarded");5663return_value = eExpressionDiscarded;5664} else {5665if (log)5666log->PutCString(5667"Process::RunThreadPlan(): thread plan stopped in mid course");5668if (options.DoesUnwindOnError() && thread_plan_sp) {5669if (log)5670log->PutCString("Process::RunThreadPlan(): discarding thread plan "5671"'cause unwind_on_error is set.");5672thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5673}5674}5675}56765677// Thread we ran the function in may have gone away because we ran the5678// target Check that it's still there, and if it is put it back in the5679// context. Also restore the frame in the context if it is still present.5680thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();5681if (thread) {5682exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));5683}56845685// Also restore the current process'es selected frame & thread, since this5686// function calling may be done behind the user's back.56875688if (selected_tid != LLDB_INVALID_THREAD_ID) {5689if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&5690selected_stack_id.IsValid()) {5691// We were able to restore the selected thread, now restore the frame:5692std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());5693StackFrameSP old_frame_sp =5694GetThreadList().GetSelectedThread()->GetFrameWithStackID(5695selected_stack_id);5696if (old_frame_sp)5697GetThreadList().GetSelectedThread()->SetSelectedFrame(5698old_frame_sp.get());5699}5700}5701}57025703// If the process exited during the run of the thread plan, notify everyone.57045705if (event_to_broadcast_sp) {5706if (log)5707log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");5708BroadcastEvent(event_to_broadcast_sp);5709}57105711return return_value;5712}57135714const char *Process::ExecutionResultAsCString(ExpressionResults result) {5715const char *result_name = "<unknown>";57165717switch (result) {5718case eExpressionCompleted:5719result_name = "eExpressionCompleted";5720break;5721case eExpressionDiscarded:5722result_name = "eExpressionDiscarded";5723break;5724case eExpressionInterrupted:5725result_name = "eExpressionInterrupted";5726break;5727case eExpressionHitBreakpoint:5728result_name = "eExpressionHitBreakpoint";5729break;5730case eExpressionSetupError:5731result_name = "eExpressionSetupError";5732break;5733case eExpressionParseError:5734result_name = "eExpressionParseError";5735break;5736case eExpressionResultUnavailable:5737result_name = "eExpressionResultUnavailable";5738break;5739case eExpressionTimedOut:5740result_name = "eExpressionTimedOut";5741break;5742case eExpressionStoppedForDebug:5743result_name = "eExpressionStoppedForDebug";5744break;5745case eExpressionThreadVanished:5746result_name = "eExpressionThreadVanished";5747}5748return result_name;5749}57505751void Process::GetStatus(Stream &strm) {5752const StateType state = GetState();5753if (StateIsStoppedState(state, false)) {5754if (state == eStateExited) {5755int exit_status = GetExitStatus();5756const char *exit_description = GetExitDescription();5757strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",5758GetID(), exit_status, exit_status,5759exit_description ? exit_description : "");5760} else {5761if (state == eStateConnected)5762strm.Printf("Connected to remote target.\n");5763else5764strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));5765}5766} else {5767strm.Printf("Process %" PRIu64 " is running.\n", GetID());5768}5769}57705771size_t Process::GetThreadStatus(Stream &strm,5772bool only_threads_with_stop_reason,5773uint32_t start_frame, uint32_t num_frames,5774uint32_t num_frames_with_source,5775bool stop_format) {5776size_t num_thread_infos_dumped = 0;57775778// You can't hold the thread list lock while calling Thread::GetStatus. That5779// very well might run code (e.g. if we need it to get return values or5780// arguments.) For that to work the process has to be able to acquire it.5781// So instead copy the thread ID's, and look them up one by one:57825783uint32_t num_threads;5784std::vector<lldb::tid_t> thread_id_array;5785// Scope for thread list locker;5786{5787std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());5788ThreadList &curr_thread_list = GetThreadList();5789num_threads = curr_thread_list.GetSize();5790uint32_t idx;5791thread_id_array.resize(num_threads);5792for (idx = 0; idx < num_threads; ++idx)5793thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();5794}57955796for (uint32_t i = 0; i < num_threads; i++) {5797ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));5798if (thread_sp) {5799if (only_threads_with_stop_reason) {5800StopInfoSP stop_info_sp = thread_sp->GetStopInfo();5801if (!stop_info_sp || !stop_info_sp->IsValid())5802continue;5803}5804thread_sp->GetStatus(strm, start_frame, num_frames,5805num_frames_with_source,5806stop_format);5807++num_thread_infos_dumped;5808} else {5809Log *log = GetLog(LLDBLog::Process);5810LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu645811" vanished while running Thread::GetStatus.");5812}5813}5814return num_thread_infos_dumped;5815}58165817void Process::AddInvalidMemoryRegion(const LoadRange ®ion) {5818m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());5819}58205821bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) {5822return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),5823region.GetByteSize());5824}58255826void Process::AddPreResumeAction(PreResumeActionCallback callback,5827void *baton) {5828m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));5829}58305831bool Process::RunPreResumeActions() {5832bool result = true;5833while (!m_pre_resume_actions.empty()) {5834struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();5835m_pre_resume_actions.pop_back();5836bool this_result = action.callback(action.baton);5837if (result)5838result = this_result;5839}5840return result;5841}58425843void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }58445845void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)5846{5847PreResumeCallbackAndBaton element(callback, baton);5848auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);5849if (found_iter != m_pre_resume_actions.end())5850{5851m_pre_resume_actions.erase(found_iter);5852}5853}58545855ProcessRunLock &Process::GetRunLock() {5856if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))5857return m_private_run_lock;5858else5859return m_public_run_lock;5860}58615862bool Process::CurrentThreadIsPrivateStateThread()5863{5864return m_private_state_thread.EqualsThread(Host::GetCurrentThread());5865}586658675868void Process::Flush() {5869m_thread_list.Flush();5870m_extended_thread_list.Flush();5871m_extended_thread_stop_id = 0;5872m_queue_list.Clear();5873m_queue_list_stop_id = 0;5874}58755876lldb::addr_t Process::GetCodeAddressMask() {5877if (uint32_t num_bits_setting = GetVirtualAddressableBits())5878return AddressableBits::AddressableBitToMask(num_bits_setting);58795880return m_code_address_mask;5881}58825883lldb::addr_t Process::GetDataAddressMask() {5884if (uint32_t num_bits_setting = GetVirtualAddressableBits())5885return AddressableBits::AddressableBitToMask(num_bits_setting);58865887return m_data_address_mask;5888}58895890lldb::addr_t Process::GetHighmemCodeAddressMask() {5891if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())5892return AddressableBits::AddressableBitToMask(num_bits_setting);58935894if (m_highmem_code_address_mask != LLDB_INVALID_ADDRESS_MASK)5895return m_highmem_code_address_mask;5896return GetCodeAddressMask();5897}58985899lldb::addr_t Process::GetHighmemDataAddressMask() {5900if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())5901return AddressableBits::AddressableBitToMask(num_bits_setting);59025903if (m_highmem_data_address_mask != LLDB_INVALID_ADDRESS_MASK)5904return m_highmem_data_address_mask;5905return GetDataAddressMask();5906}59075908void Process::SetCodeAddressMask(lldb::addr_t code_address_mask) {5909LLDB_LOG(GetLog(LLDBLog::Process),5910"Setting Process code address mask to {0:x}", code_address_mask);5911m_code_address_mask = code_address_mask;5912}59135914void Process::SetDataAddressMask(lldb::addr_t data_address_mask) {5915LLDB_LOG(GetLog(LLDBLog::Process),5916"Setting Process data address mask to {0:x}", data_address_mask);5917m_data_address_mask = data_address_mask;5918}59195920void Process::SetHighmemCodeAddressMask(lldb::addr_t code_address_mask) {5921LLDB_LOG(GetLog(LLDBLog::Process),5922"Setting Process highmem code address mask to {0:x}",5923code_address_mask);5924m_highmem_code_address_mask = code_address_mask;5925}59265927void Process::SetHighmemDataAddressMask(lldb::addr_t data_address_mask) {5928LLDB_LOG(GetLog(LLDBLog::Process),5929"Setting Process highmem data address mask to {0:x}",5930data_address_mask);5931m_highmem_data_address_mask = data_address_mask;5932}59335934addr_t Process::FixCodeAddress(addr_t addr) {5935if (ABISP abi_sp = GetABI())5936addr = abi_sp->FixCodeAddress(addr);5937return addr;5938}59395940addr_t Process::FixDataAddress(addr_t addr) {5941if (ABISP abi_sp = GetABI())5942addr = abi_sp->FixDataAddress(addr);5943return addr;5944}59455946addr_t Process::FixAnyAddress(addr_t addr) {5947if (ABISP abi_sp = GetABI())5948addr = abi_sp->FixAnyAddress(addr);5949return addr;5950}59515952void Process::DidExec() {5953Log *log = GetLog(LLDBLog::Process);5954LLDB_LOGF(log, "Process::%s()", __FUNCTION__);59555956Target &target = GetTarget();5957target.CleanupProcess();5958target.ClearModules(false);5959m_dynamic_checkers_up.reset();5960m_abi_sp.reset();5961m_system_runtime_up.reset();5962m_os_up.reset();5963m_dyld_up.reset();5964m_jit_loaders_up.reset();5965m_image_tokens.clear();5966// After an exec, the inferior is a new process and these memory regions are5967// no longer allocated.5968m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);5969{5970std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);5971m_language_runtimes.clear();5972}5973m_instrumentation_runtimes.clear();5974m_thread_list.DiscardThreadPlans();5975m_memory_cache.Clear(true);5976DoDidExec();5977CompleteAttach();5978// Flush the process (threads and all stack frames) after running5979// CompleteAttach() in case the dynamic loader loaded things in new5980// locations.5981Flush();59825983// After we figure out what was loaded/unloaded in CompleteAttach, we need to5984// let the target know so it can do any cleanup it needs to.5985target.DidExec();5986}59875988addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {5989if (address == nullptr) {5990error.SetErrorString("Invalid address argument");5991return LLDB_INVALID_ADDRESS;5992}59935994addr_t function_addr = LLDB_INVALID_ADDRESS;59955996addr_t addr = address->GetLoadAddress(&GetTarget());5997std::map<addr_t, addr_t>::const_iterator iter =5998m_resolved_indirect_addresses.find(addr);5999if (iter != m_resolved_indirect_addresses.end()) {6000function_addr = (*iter).second;6001} else {6002if (!CallVoidArgVoidPtrReturn(address, function_addr)) {6003Symbol *symbol = address->CalculateSymbolContextSymbol();6004error.SetErrorStringWithFormat(6005"Unable to call resolver for indirect function %s",6006symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");6007function_addr = LLDB_INVALID_ADDRESS;6008} else {6009if (ABISP abi_sp = GetABI())6010function_addr = abi_sp->FixCodeAddress(function_addr);6011m_resolved_indirect_addresses.insert(6012std::pair<addr_t, addr_t>(addr, function_addr));6013}6014}6015return function_addr;6016}60176018void Process::ModulesDidLoad(ModuleList &module_list) {6019// Inform the system runtime of the modified modules.6020SystemRuntime *sys_runtime = GetSystemRuntime();6021if (sys_runtime)6022sys_runtime->ModulesDidLoad(module_list);60236024GetJITLoaders().ModulesDidLoad(module_list);60256026// Give the instrumentation runtimes a chance to be created before informing6027// them of the modified modules.6028InstrumentationRuntime::ModulesDidLoad(module_list, this,6029m_instrumentation_runtimes);6030for (auto &runtime : m_instrumentation_runtimes)6031runtime.second->ModulesDidLoad(module_list);60326033// Give the language runtimes a chance to be created before informing them of6034// the modified modules.6035for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {6036if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))6037runtime->ModulesDidLoad(module_list);6038}60396040// If we don't have an operating system plug-in, try to load one since6041// loading shared libraries might cause a new one to try and load6042if (!m_os_up)6043LoadOperatingSystemPlugin(false);60446045// Inform the structured-data plugins of the modified modules.6046for (auto &pair : m_structured_data_plugin_map) {6047if (pair.second)6048pair.second->ModulesDidLoad(*this, module_list);6049}6050}60516052void Process::PrintWarningOptimization(const SymbolContext &sc) {6053if (!GetWarningsOptimization())6054return;6055if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())6056return;6057sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());6058}60596060void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {6061if (!GetWarningsUnsupportedLanguage())6062return;6063if (!sc.module_sp)6064return;6065LanguageType language = sc.GetLanguage();6066if (language == eLanguageTypeUnknown ||6067language == lldb::eLanguageTypeAssembly ||6068language == lldb::eLanguageTypeMipsAssembler)6069return;6070LanguageSet plugins =6071PluginManager::GetAllTypeSystemSupportedLanguagesForTypes();6072if (plugins[language])6073return;6074sc.module_sp->ReportWarningUnsupportedLanguage(6075language, GetTarget().GetDebugger().GetID());6076}60776078bool Process::GetProcessInfo(ProcessInstanceInfo &info) {6079info.Clear();60806081PlatformSP platform_sp = GetTarget().GetPlatform();6082if (!platform_sp)6083return false;60846085return platform_sp->GetProcessInfo(GetID(), info);6086}60876088ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {6089ThreadCollectionSP threads;60906091const MemoryHistorySP &memory_history =6092MemoryHistory::FindPlugin(shared_from_this());60936094if (!memory_history) {6095return threads;6096}60976098threads = std::make_shared<ThreadCollection>(6099memory_history->GetHistoryThreads(addr));61006101return threads;6102}61036104InstrumentationRuntimeSP6105Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {6106InstrumentationRuntimeCollection::iterator pos;6107pos = m_instrumentation_runtimes.find(type);6108if (pos == m_instrumentation_runtimes.end()) {6109return InstrumentationRuntimeSP();6110} else6111return (*pos).second;6112}61136114bool Process::GetModuleSpec(const FileSpec &module_file_spec,6115const ArchSpec &arch, ModuleSpec &module_spec) {6116module_spec.Clear();6117return false;6118}61196120size_t Process::AddImageToken(lldb::addr_t image_ptr) {6121m_image_tokens.push_back(image_ptr);6122return m_image_tokens.size() - 1;6123}61246125lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {6126if (token < m_image_tokens.size())6127return m_image_tokens[token];6128return LLDB_INVALID_IMAGE_TOKEN;6129}61306131void Process::ResetImageToken(size_t token) {6132if (token < m_image_tokens.size())6133m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;6134}61356136Address6137Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,6138AddressRange range_bounds) {6139Target &target = GetTarget();6140DisassemblerSP disassembler_sp;6141InstructionList *insn_list = nullptr;61426143Address retval = default_stop_addr;61446145if (!target.GetUseFastStepping())6146return retval;6147if (!default_stop_addr.IsValid())6148return retval;61496150const char *plugin_name = nullptr;6151const char *flavor = nullptr;6152disassembler_sp = Disassembler::DisassembleRange(6153target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds);6154if (disassembler_sp)6155insn_list = &disassembler_sp->GetInstructionList();61566157if (insn_list == nullptr) {6158return retval;6159}61606161size_t insn_offset =6162insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);6163if (insn_offset == UINT32_MAX) {6164return retval;6165}61666167uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(6168insn_offset, false /* ignore_calls*/, nullptr);6169if (branch_index == UINT32_MAX) {6170return retval;6171}61726173if (branch_index > insn_offset) {6174Address next_branch_insn_address =6175insn_list->GetInstructionAtIndex(branch_index)->GetAddress();6176if (next_branch_insn_address.IsValid() &&6177range_bounds.ContainsFileAddress(next_branch_insn_address)) {6178retval = next_branch_insn_address;6179}6180}61816182return retval;6183}61846185Status Process::GetMemoryRegionInfo(lldb::addr_t load_addr,6186MemoryRegionInfo &range_info) {6187if (const lldb::ABISP &abi = GetABI())6188load_addr = abi->FixAnyAddress(load_addr);6189return DoGetMemoryRegionInfo(load_addr, range_info);6190}61916192Status Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) {6193Status error;61946195lldb::addr_t range_end = 0;6196const lldb::ABISP &abi = GetABI();61976198region_list.clear();6199do {6200lldb_private::MemoryRegionInfo region_info;6201error = GetMemoryRegionInfo(range_end, region_info);6202// GetMemoryRegionInfo should only return an error if it is unimplemented.6203if (error.Fail()) {6204region_list.clear();6205break;6206}62076208// We only check the end address, not start and end, because we assume that6209// the start will not have non-address bits until the first unmappable6210// region. We will have exited the loop by that point because the previous6211// region, the last mappable region, will have non-address bits in its end6212// address.6213range_end = region_info.GetRange().GetRangeEnd();6214if (region_info.GetMapped() == MemoryRegionInfo::eYes) {6215region_list.push_back(std::move(region_info));6216}6217} while (6218// For a process with no non-address bits, all address bits6219// set means the end of memory.6220range_end != LLDB_INVALID_ADDRESS &&6221// If we have non-address bits and some are set then the end6222// is at or beyond the end of mappable memory.6223!(abi && (abi->FixAnyAddress(range_end) != range_end)));62246225return error;6226}62276228Status6229Process::ConfigureStructuredData(llvm::StringRef type_name,6230const StructuredData::ObjectSP &config_sp) {6231// If you get this, the Process-derived class needs to implement a method to6232// enable an already-reported asynchronous structured data feature. See6233// ProcessGDBRemote for an example implementation over gdb-remote.6234return Status("unimplemented");6235}62366237void Process::MapSupportedStructuredDataPlugins(6238const StructuredData::Array &supported_type_names) {6239Log *log = GetLog(LLDBLog::Process);62406241// Bail out early if there are no type names to map.6242if (supported_type_names.GetSize() == 0) {6243LLDB_LOG(log, "no structured data types supported");6244return;6245}62466247// These StringRefs are backed by the input parameter.6248std::set<llvm::StringRef> type_names;62496250LLDB_LOG(log,6251"the process supports the following async structured data types:");62526253supported_type_names.ForEach(6254[&type_names, &log](StructuredData::Object *object) {6255// There shouldn't be null objects in the array.6256if (!object)6257return false;62586259// All type names should be strings.6260const llvm::StringRef type_name = object->GetStringValue();6261if (type_name.empty())6262return false;62636264type_names.insert(type_name);6265LLDB_LOG(log, "- {0}", type_name);6266return true;6267});62686269// For each StructuredDataPlugin, if the plugin handles any of the types in6270// the supported_type_names, map that type name to that plugin. Stop when6271// we've consumed all the type names.6272// FIXME: should we return an error if there are type names nobody6273// supports?6274for (uint32_t plugin_index = 0; !type_names.empty(); plugin_index++) {6275auto create_instance =6276PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(6277plugin_index);6278if (!create_instance)6279break;62806281// Create the plugin.6282StructuredDataPluginSP plugin_sp = (*create_instance)(*this);6283if (!plugin_sp) {6284// This plugin doesn't think it can work with the process. Move on to the6285// next.6286continue;6287}62886289// For any of the remaining type names, map any that this plugin supports.6290std::vector<llvm::StringRef> names_to_remove;6291for (llvm::StringRef type_name : type_names) {6292if (plugin_sp->SupportsStructuredDataType(type_name)) {6293m_structured_data_plugin_map.insert(6294std::make_pair(type_name, plugin_sp));6295names_to_remove.push_back(type_name);6296LLDB_LOG(log, "using plugin {0} for type name {1}",6297plugin_sp->GetPluginName(), type_name);6298}6299}63006301// Remove the type names that were consumed by this plugin.6302for (llvm::StringRef type_name : names_to_remove)6303type_names.erase(type_name);6304}6305}63066307bool Process::RouteAsyncStructuredData(6308const StructuredData::ObjectSP object_sp) {6309// Nothing to do if there's no data.6310if (!object_sp)6311return false;63126313// The contract is this must be a dictionary, so we can look up the routing6314// key via the top-level 'type' string value within the dictionary.6315StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();6316if (!dictionary)6317return false;63186319// Grab the async structured type name (i.e. the feature/plugin name).6320llvm::StringRef type_name;6321if (!dictionary->GetValueForKeyAsString("type", type_name))6322return false;63236324// Check if there's a plugin registered for this type name.6325auto find_it = m_structured_data_plugin_map.find(type_name);6326if (find_it == m_structured_data_plugin_map.end()) {6327// We don't have a mapping for this structured data type.6328return false;6329}63306331// Route the structured data to the plugin.6332find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);6333return true;6334}63356336Status Process::UpdateAutomaticSignalFiltering() {6337// Default implementation does nothign.6338// No automatic signal filtering to speak of.6339return Status();6340}63416342UtilityFunction *Process::GetLoadImageUtilityFunction(6343Platform *platform,6344llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {6345if (platform != GetTarget().GetPlatform().get())6346return nullptr;6347llvm::call_once(m_dlopen_utility_func_flag_once,6348[&] { m_dlopen_utility_func_up = factory(); });6349return m_dlopen_utility_func_up.get();6350}63516352llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {6353if (!IsLiveDebugSession())6354return llvm::createStringError(llvm::inconvertibleErrorCode(),6355"Can't trace a non-live process.");6356return llvm::make_error<UnimplementedError>();6357}63586359bool Process::CallVoidArgVoidPtrReturn(const Address *address,6360addr_t &returned_func,6361bool trap_exceptions) {6362Thread *thread = GetThreadList().GetExpressionExecutionThread().get();6363if (thread == nullptr || address == nullptr)6364return false;63656366EvaluateExpressionOptions options;6367options.SetStopOthers(true);6368options.SetUnwindOnError(true);6369options.SetIgnoreBreakpoints(true);6370options.SetTryAllThreads(true);6371options.SetDebug(false);6372options.SetTimeout(GetUtilityExpressionTimeout());6373options.SetTrapExceptions(trap_exceptions);63746375auto type_system_or_err =6376GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);6377if (!type_system_or_err) {6378llvm::consumeError(type_system_or_err.takeError());6379return false;6380}6381auto ts = *type_system_or_err;6382if (!ts)6383return false;6384CompilerType void_ptr_type =6385ts->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();6386lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(6387*thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));6388if (call_plan_sp) {6389DiagnosticManager diagnostics;63906391StackFrame *frame = thread->GetStackFrameAtIndex(0).get();6392if (frame) {6393ExecutionContext exe_ctx;6394frame->CalculateExecutionContext(exe_ctx);6395ExpressionResults result =6396RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);6397if (result == eExpressionCompleted) {6398returned_func =6399call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(6400LLDB_INVALID_ADDRESS);64016402if (GetAddressByteSize() == 4) {6403if (returned_func == UINT32_MAX)6404return false;6405} else if (GetAddressByteSize() == 8) {6406if (returned_func == UINT64_MAX)6407return false;6408}6409return true;6410}6411}6412}64136414return false;6415}64166417llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {6418Architecture *arch = GetTarget().GetArchitecturePlugin();6419const MemoryTagManager *tag_manager =6420arch ? arch->GetMemoryTagManager() : nullptr;6421if (!arch || !tag_manager) {6422return llvm::createStringError(6423llvm::inconvertibleErrorCode(),6424"This architecture does not support memory tagging");6425}64266427if (!SupportsMemoryTagging()) {6428return llvm::createStringError(llvm::inconvertibleErrorCode(),6429"Process does not support memory tagging");6430}64316432return tag_manager;6433}64346435llvm::Expected<std::vector<lldb::addr_t>>6436Process::ReadMemoryTags(lldb::addr_t addr, size_t len) {6437llvm::Expected<const MemoryTagManager *> tag_manager_or_err =6438GetMemoryTagManager();6439if (!tag_manager_or_err)6440return tag_manager_or_err.takeError();64416442const MemoryTagManager *tag_manager = *tag_manager_or_err;6443llvm::Expected<std::vector<uint8_t>> tag_data =6444DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());6445if (!tag_data)6446return tag_data.takeError();64476448return tag_manager->UnpackTagsData(*tag_data,6449len / tag_manager->GetGranuleSize());6450}64516452Status Process::WriteMemoryTags(lldb::addr_t addr, size_t len,6453const std::vector<lldb::addr_t> &tags) {6454llvm::Expected<const MemoryTagManager *> tag_manager_or_err =6455GetMemoryTagManager();6456if (!tag_manager_or_err)6457return Status(tag_manager_or_err.takeError());64586459const MemoryTagManager *tag_manager = *tag_manager_or_err;6460llvm::Expected<std::vector<uint8_t>> packed_tags =6461tag_manager->PackTags(tags);6462if (!packed_tags) {6463return Status(packed_tags.takeError());6464}64656466return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),6467*packed_tags);6468}64696470// Create a CoreFileMemoryRange from a MemoryRegionInfo6471static Process::CoreFileMemoryRange6472CreateCoreFileMemoryRange(const MemoryRegionInfo ®ion) {6473const addr_t addr = region.GetRange().GetRangeBase();6474llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());6475return {range, region.GetLLDBPermissions()};6476}64776478// Add dirty pages to the core file ranges and return true if dirty pages6479// were added. Return false if the dirty page information is not valid or in6480// the region.6481static bool AddDirtyPages(const MemoryRegionInfo ®ion,6482Process::CoreFileMemoryRanges &ranges) {6483const auto &dirty_page_list = region.GetDirtyPageList();6484if (!dirty_page_list)6485return false;6486const uint32_t lldb_permissions = region.GetLLDBPermissions();6487const addr_t page_size = region.GetPageSize();6488if (page_size == 0)6489return false;6490llvm::AddressRange range(0, 0);6491for (addr_t page_addr : *dirty_page_list) {6492if (range.empty()) {6493// No range yet, initialize the range with the current dirty page.6494range = llvm::AddressRange(page_addr, page_addr + page_size);6495} else {6496if (range.end() == page_addr) {6497// Combine consective ranges.6498range = llvm::AddressRange(range.start(), page_addr + page_size);6499} else {6500// Add previous contiguous range and init the new range with the6501// current dirty page.6502ranges.push_back({range, lldb_permissions});6503range = llvm::AddressRange(page_addr, page_addr + page_size);6504}6505}6506}6507// The last range6508if (!range.empty())6509ranges.push_back({range, lldb_permissions});6510return true;6511}65126513// Given a region, add the region to \a ranges.6514//6515// Only add the region if it isn't empty and if it has some permissions.6516// If \a try_dirty_pages is true, then try to add only the dirty pages for a6517// given region. If the region has dirty page information, only dirty pages6518// will be added to \a ranges, else the entire range will be added to \a6519// ranges.6520static void AddRegion(const MemoryRegionInfo ®ion, bool try_dirty_pages,6521Process::CoreFileMemoryRanges &ranges) {6522// Don't add empty ranges.6523if (region.GetRange().GetByteSize() == 0)6524return;6525// Don't add ranges with no read permissions.6526if ((region.GetLLDBPermissions() & lldb::ePermissionsReadable) == 0)6527return;6528if (try_dirty_pages && AddDirtyPages(region, ranges))6529return;6530ranges.push_back(CreateCoreFileMemoryRange(region));6531}65326533static void SaveOffRegionsWithStackPointers(6534Process &process, const MemoryRegionInfos ®ions,6535Process::CoreFileMemoryRanges &ranges, std::set<addr_t> &stack_ends) {6536const bool try_dirty_pages = true;65376538// Before we take any dump, we want to save off the used portions of the6539// stacks and mark those memory regions as saved. This prevents us from saving6540// the unused portion of the stack below the stack pointer. Saving space on6541// the dump.6542for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {6543if (!thread_sp)6544continue;6545StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);6546if (!frame_sp)6547continue;6548RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();6549if (!reg_ctx_sp)6550continue;6551const addr_t sp = reg_ctx_sp->GetSP();6552const size_t red_zone = process.GetABI()->GetRedZoneSize();6553lldb_private::MemoryRegionInfo sp_region;6554if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {6555const size_t stack_head = (sp - red_zone);6556const size_t stack_size = sp_region.GetRange().GetRangeEnd() - stack_head;6557sp_region.GetRange().SetRangeBase(stack_head);6558sp_region.GetRange().SetByteSize(stack_size);6559stack_ends.insert(sp_region.GetRange().GetRangeEnd());6560AddRegion(sp_region, try_dirty_pages, ranges);6561}6562}6563}65646565// Save all memory regions that are not empty or have at least some permissions6566// for a full core file style.6567static void GetCoreFileSaveRangesFull(Process &process,6568const MemoryRegionInfos ®ions,6569Process::CoreFileMemoryRanges &ranges,6570std::set<addr_t> &stack_ends) {65716572// Don't add only dirty pages, add full regions.6573const bool try_dirty_pages = false;6574for (const auto ®ion : regions)6575if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)6576AddRegion(region, try_dirty_pages, ranges);6577}65786579// Save only the dirty pages to the core file. Make sure the process has at6580// least some dirty pages, as some OS versions don't support reporting what6581// pages are dirty within an memory region. If no memory regions have dirty6582// page information fall back to saving out all ranges with write permissions.6583static void GetCoreFileSaveRangesDirtyOnly(6584Process &process, const MemoryRegionInfos ®ions,6585Process::CoreFileMemoryRanges &ranges, std::set<addr_t> &stack_ends) {65866587// Iterate over the regions and find all dirty pages.6588bool have_dirty_page_info = false;6589for (const auto ®ion : regions) {6590if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6591AddDirtyPages(region, ranges))6592have_dirty_page_info = true;6593}65946595if (!have_dirty_page_info) {6596// We didn't find support for reporting dirty pages from the process6597// plug-in so fall back to any region with write access permissions.6598const bool try_dirty_pages = false;6599for (const auto ®ion : regions)6600if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6601region.GetWritable() == MemoryRegionInfo::eYes)6602AddRegion(region, try_dirty_pages, ranges);6603}6604}66056606// Save all thread stacks to the core file. Some OS versions support reporting6607// when a memory region is stack related. We check on this information, but we6608// also use the stack pointers of each thread and add those in case the OS6609// doesn't support reporting stack memory. This function also attempts to only6610// emit dirty pages from the stack if the memory regions support reporting6611// dirty regions as this will make the core file smaller. If the process6612// doesn't support dirty regions, then it will fall back to adding the full6613// stack region.6614static void GetCoreFileSaveRangesStackOnly(6615Process &process, const MemoryRegionInfos ®ions,6616Process::CoreFileMemoryRanges &ranges, std::set<addr_t> &stack_ends) {6617const bool try_dirty_pages = true;6618// Some platforms support annotating the region information that tell us that6619// it comes from a thread stack. So look for those regions first.66206621for (const auto ®ion : regions) {6622// Save all the stack memory ranges not associated with a stack pointer.6623if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6624region.IsStackMemory() == MemoryRegionInfo::eYes)6625AddRegion(region, try_dirty_pages, ranges);6626}6627}66286629Status Process::CalculateCoreFileSaveRanges(lldb::SaveCoreStyle core_style,6630CoreFileMemoryRanges &ranges) {6631lldb_private::MemoryRegionInfos regions;6632Status err = GetMemoryRegions(regions);6633if (err.Fail())6634return err;6635if (regions.empty())6636return Status("failed to get any valid memory regions from the process");6637if (core_style == eSaveCoreUnspecified)6638return Status("callers must set the core_style to something other than "6639"eSaveCoreUnspecified");66406641std::set<addr_t> stack_ends;6642SaveOffRegionsWithStackPointers(*this, regions, ranges, stack_ends);66436644switch (core_style) {6645case eSaveCoreUnspecified:6646break;66476648case eSaveCoreFull:6649GetCoreFileSaveRangesFull(*this, regions, ranges, stack_ends);6650break;66516652case eSaveCoreDirtyOnly:6653GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges, stack_ends);6654break;66556656case eSaveCoreStackOnly:6657GetCoreFileSaveRangesStackOnly(*this, regions, ranges, stack_ends);6658break;6659}66606661if (err.Fail())6662return err;66636664if (ranges.empty())6665return Status("no valid address ranges found for core style");66666667return Status(); // Success!6668}66696670void Process::SetAddressableBitMasks(AddressableBits bit_masks) {6671uint32_t low_memory_addr_bits = bit_masks.GetLowmemAddressableBits();6672uint32_t high_memory_addr_bits = bit_masks.GetHighmemAddressableBits();66736674if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)6675return;66766677if (low_memory_addr_bits != 0) {6678addr_t low_addr_mask =6679AddressableBits::AddressableBitToMask(low_memory_addr_bits);6680SetCodeAddressMask(low_addr_mask);6681SetDataAddressMask(low_addr_mask);6682}66836684if (high_memory_addr_bits != 0) {6685addr_t high_addr_mask =6686AddressableBits::AddressableBitToMask(high_memory_addr_bits);6687SetHighmemCodeAddressMask(high_addr_mask);6688SetHighmemDataAddressMask(high_addr_mask);6689}6690}669166926693