6869 lines · cpp
1//===-- Process.cpp -------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include <atomic>10#include <memory>11#include <mutex>12#include <optional>13 14#include "llvm/ADT/ScopeExit.h"15#include "llvm/Support/ScopedPrinter.h"16#include "llvm/Support/Threading.h"17 18#include "lldb/Breakpoint/BreakpointLocation.h"19#include "lldb/Breakpoint/StoppointCallbackContext.h"20#include "lldb/Core/Debugger.h"21#include "lldb/Core/Module.h"22#include "lldb/Core/ModuleSpec.h"23#include "lldb/Core/PluginManager.h"24#include "lldb/Core/Progress.h"25#include "lldb/Core/Telemetry.h"26#include "lldb/Expression/DiagnosticManager.h"27#include "lldb/Expression/DynamicCheckerFunctions.h"28#include "lldb/Expression/UserExpression.h"29#include "lldb/Expression/UtilityFunction.h"30#include "lldb/Host/ConnectionFileDescriptor.h"31#include "lldb/Host/FileSystem.h"32#include "lldb/Host/Host.h"33#include "lldb/Host/HostInfo.h"34#include "lldb/Host/OptionParser.h"35#include "lldb/Host/Pipe.h"36#include "lldb/Host/Terminal.h"37#include "lldb/Host/ThreadLauncher.h"38#include "lldb/Interpreter/CommandInterpreter.h"39#include "lldb/Interpreter/OptionArgParser.h"40#include "lldb/Interpreter/OptionValueProperties.h"41#include "lldb/Symbol/Function.h"42#include "lldb/Symbol/Symbol.h"43#include "lldb/Target/ABI.h"44#include "lldb/Target/AssertFrameRecognizer.h"45#include "lldb/Target/DynamicLoader.h"46#include "lldb/Target/InstrumentationRuntime.h"47#include "lldb/Target/JITLoader.h"48#include "lldb/Target/JITLoaderList.h"49#include "lldb/Target/Language.h"50#include "lldb/Target/LanguageRuntime.h"51#include "lldb/Target/MemoryHistory.h"52#include "lldb/Target/MemoryRegionInfo.h"53#include "lldb/Target/OperatingSystem.h"54#include "lldb/Target/Platform.h"55#include "lldb/Target/Process.h"56#include "lldb/Target/RegisterContext.h"57#include "lldb/Target/StopInfo.h"58#include "lldb/Target/StructuredDataPlugin.h"59#include "lldb/Target/SystemRuntime.h"60#include "lldb/Target/Target.h"61#include "lldb/Target/TargetList.h"62#include "lldb/Target/Thread.h"63#include "lldb/Target/ThreadPlan.h"64#include "lldb/Target/ThreadPlanBase.h"65#include "lldb/Target/ThreadPlanCallFunction.h"66#include "lldb/Target/ThreadPlanStack.h"67#include "lldb/Target/UnixSignals.h"68#include "lldb/Utility/AddressableBits.h"69#include "lldb/Utility/Event.h"70#include "lldb/Utility/LLDBLog.h"71#include "lldb/Utility/Log.h"72#include "lldb/Utility/NameMatches.h"73#include "lldb/Utility/ProcessInfo.h"74#include "lldb/Utility/SelectHelper.h"75#include "lldb/Utility/State.h"76#include "lldb/Utility/Timer.h"77 78using namespace lldb;79using namespace lldb_private;80using namespace std::chrono;81 82class ProcessOptionValueProperties83 : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {84public:85 ProcessOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}86 87 const Property *88 GetPropertyAtIndex(size_t idx,89 const ExecutionContext *exe_ctx) const override {90 // When getting the value for a key from the process options, we will91 // always try and grab the setting from the current process if there is92 // one. Else we just use the one from this instance.93 if (exe_ctx) {94 Process *process = exe_ctx->GetProcessPtr();95 if (process) {96 ProcessOptionValueProperties *instance_properties =97 static_cast<ProcessOptionValueProperties *>(98 process->GetValueProperties().get());99 if (this != instance_properties)100 return instance_properties->ProtectedGetPropertyAtIndex(idx);101 }102 }103 return ProtectedGetPropertyAtIndex(idx);104 }105};106 107static constexpr OptionEnumValueElement g_follow_fork_mode_values[] = {108 {109 eFollowParent,110 "parent",111 "Continue tracing the parent process and detach the child.",112 },113 {114 eFollowChild,115 "child",116 "Trace the child process and detach the parent.",117 },118};119 120#define LLDB_PROPERTIES_process121#include "TargetProperties.inc"122 123enum {124#define LLDB_PROPERTIES_process125#include "TargetPropertiesEnum.inc"126 ePropertyExperimental,127};128 129#define LLDB_PROPERTIES_process_experimental130#include "TargetProperties.inc"131 132enum {133#define LLDB_PROPERTIES_process_experimental134#include "TargetPropertiesEnum.inc"135};136 137class ProcessExperimentalOptionValueProperties138 : public Cloneable<ProcessExperimentalOptionValueProperties,139 OptionValueProperties> {140public:141 ProcessExperimentalOptionValueProperties()142 : Cloneable(Properties::GetExperimentalSettingsName()) {}143};144 145ProcessExperimentalProperties::ProcessExperimentalProperties()146 : Properties(OptionValuePropertiesSP(147 new ProcessExperimentalOptionValueProperties())) {148 m_collection_sp->Initialize(g_process_experimental_properties);149}150 151ProcessProperties::ProcessProperties(lldb_private::Process *process)152 : Properties(),153 m_process(process) // Can be nullptr for global ProcessProperties154{155 if (process == nullptr) {156 // Global process properties, set them up one time157 m_collection_sp = std::make_shared<ProcessOptionValueProperties>("process");158 m_collection_sp->Initialize(g_process_properties);159 m_collection_sp->AppendProperty(160 "thread", "Settings specific to threads.", true,161 Thread::GetGlobalProperties().GetValueProperties());162 } else {163 m_collection_sp =164 OptionValueProperties::CreateLocalCopy(Process::GetGlobalProperties());165 m_collection_sp->SetValueChangedCallback(166 ePropertyPythonOSPluginPath,167 [this] { m_process->LoadOperatingSystemPlugin(true); });168 m_collection_sp->SetValueChangedCallback(169 ePropertyDisableLangRuntimeUnwindPlans,170 [this] { DisableLanguageRuntimeUnwindPlansCallback(); });171 }172 173 m_experimental_properties_up =174 std::make_unique<ProcessExperimentalProperties>();175 m_collection_sp->AppendProperty(176 Properties::GetExperimentalSettingsName(),177 "Experimental settings - setting these won't produce "178 "errors if the setting is not present.",179 true, m_experimental_properties_up->GetValueProperties());180}181 182ProcessProperties::~ProcessProperties() = default;183 184bool ProcessProperties::GetDisableMemoryCache() const {185 const uint32_t idx = ePropertyDisableMemCache;186 return GetPropertyAtIndexAs<bool>(187 idx, g_process_properties[idx].default_uint_value != 0);188}189 190uint64_t ProcessProperties::GetMemoryCacheLineSize() const {191 const uint32_t idx = ePropertyMemCacheLineSize;192 return GetPropertyAtIndexAs<uint64_t>(193 idx, g_process_properties[idx].default_uint_value);194}195 196Args ProcessProperties::GetExtraStartupCommands() const {197 Args args;198 const uint32_t idx = ePropertyExtraStartCommand;199 m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);200 return args;201}202 203void ProcessProperties::SetExtraStartupCommands(const Args &args) {204 const uint32_t idx = ePropertyExtraStartCommand;205 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);206}207 208FileSpec ProcessProperties::GetPythonOSPluginPath() const {209 const uint32_t idx = ePropertyPythonOSPluginPath;210 return GetPropertyAtIndexAs<FileSpec>(idx, {});211}212 213uint32_t ProcessProperties::GetVirtualAddressableBits() const {214 const uint32_t idx = ePropertyVirtualAddressableBits;215 return GetPropertyAtIndexAs<uint64_t>(216 idx, g_process_properties[idx].default_uint_value);217}218 219void ProcessProperties::SetVirtualAddressableBits(uint32_t bits) {220 const uint32_t idx = ePropertyVirtualAddressableBits;221 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));222}223 224uint32_t ProcessProperties::GetHighmemVirtualAddressableBits() const {225 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;226 return GetPropertyAtIndexAs<uint64_t>(227 idx, g_process_properties[idx].default_uint_value);228}229 230void ProcessProperties::SetHighmemVirtualAddressableBits(uint32_t bits) {231 const uint32_t idx = ePropertyHighmemVirtualAddressableBits;232 SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));233}234 235void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {236 const uint32_t idx = ePropertyPythonOSPluginPath;237 SetPropertyAtIndex(idx, file);238}239 240bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {241 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;242 return GetPropertyAtIndexAs<bool>(243 idx, g_process_properties[idx].default_uint_value != 0);244}245 246void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {247 const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;248 SetPropertyAtIndex(idx, ignore);249}250 251bool ProcessProperties::GetUnwindOnErrorInExpressions() const {252 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;253 return GetPropertyAtIndexAs<bool>(254 idx, g_process_properties[idx].default_uint_value != 0);255}256 257void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {258 const uint32_t idx = ePropertyUnwindOnErrorInExpressions;259 SetPropertyAtIndex(idx, ignore);260}261 262bool ProcessProperties::GetStopOnSharedLibraryEvents() const {263 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;264 return GetPropertyAtIndexAs<bool>(265 idx, g_process_properties[idx].default_uint_value != 0);266}267 268void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {269 const uint32_t idx = ePropertyStopOnSharedLibraryEvents;270 SetPropertyAtIndex(idx, stop);271}272 273bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const {274 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;275 return GetPropertyAtIndexAs<bool>(276 idx, g_process_properties[idx].default_uint_value != 0);277}278 279void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable) {280 const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;281 SetPropertyAtIndex(idx, disable);282 m_process->Flush();283}284 285void ProcessProperties::DisableLanguageRuntimeUnwindPlansCallback() {286 if (!m_process)287 return;288 for (auto thread_sp : m_process->Threads()) {289 thread_sp->ClearStackFrames();290 thread_sp->DiscardThreadPlans(/*force*/ true);291 }292}293 294bool ProcessProperties::GetDetachKeepsStopped() const {295 const uint32_t idx = ePropertyDetachKeepsStopped;296 return GetPropertyAtIndexAs<bool>(297 idx, g_process_properties[idx].default_uint_value != 0);298}299 300void ProcessProperties::SetDetachKeepsStopped(bool stop) {301 const uint32_t idx = ePropertyDetachKeepsStopped;302 SetPropertyAtIndex(idx, stop);303}304 305bool ProcessProperties::GetWarningsOptimization() const {306 const uint32_t idx = ePropertyWarningOptimization;307 return GetPropertyAtIndexAs<bool>(308 idx, g_process_properties[idx].default_uint_value != 0);309}310 311bool ProcessProperties::GetWarningsUnsupportedLanguage() const {312 const uint32_t idx = ePropertyWarningUnsupportedLanguage;313 return GetPropertyAtIndexAs<bool>(314 idx, g_process_properties[idx].default_uint_value != 0);315}316 317bool ProcessProperties::GetStopOnExec() const {318 const uint32_t idx = ePropertyStopOnExec;319 return GetPropertyAtIndexAs<bool>(320 idx, g_process_properties[idx].default_uint_value != 0);321}322 323std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {324 const uint32_t idx = ePropertyUtilityExpressionTimeout;325 uint64_t value = GetPropertyAtIndexAs<uint64_t>(326 idx, g_process_properties[idx].default_uint_value);327 return std::chrono::seconds(value);328}329 330std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {331 const uint32_t idx = ePropertyInterruptTimeout;332 uint64_t value = GetPropertyAtIndexAs<uint64_t>(333 idx, g_process_properties[idx].default_uint_value);334 return std::chrono::seconds(value);335}336 337bool ProcessProperties::GetSteppingRunsAllThreads() const {338 const uint32_t idx = ePropertySteppingRunsAllThreads;339 return GetPropertyAtIndexAs<bool>(340 idx, g_process_properties[idx].default_uint_value != 0);341}342 343bool ProcessProperties::GetOSPluginReportsAllThreads() const {344 const bool fail_value = true;345 const Property *exp_property =346 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);347 OptionValueProperties *exp_values =348 exp_property->GetValue()->GetAsProperties();349 if (!exp_values)350 return fail_value;351 352 return exp_values353 ->GetPropertyAtIndexAs<bool>(ePropertyOSPluginReportsAllThreads)354 .value_or(fail_value);355}356 357void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {358 const Property *exp_property =359 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);360 OptionValueProperties *exp_values =361 exp_property->GetValue()->GetAsProperties();362 if (exp_values)363 exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,364 does_report);365}366 367FollowForkMode ProcessProperties::GetFollowForkMode() const {368 const uint32_t idx = ePropertyFollowForkMode;369 return GetPropertyAtIndexAs<FollowForkMode>(370 idx, static_cast<FollowForkMode>(371 g_process_properties[idx].default_uint_value));372}373 374bool ProcessProperties::TrackMemoryCacheChanges() const {375 const uint32_t idx = ePropertyTrackMemoryCacheChanges;376 return GetPropertyAtIndexAs<bool>(377 idx, g_process_properties[idx].default_uint_value != 0);378}379 380ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,381 llvm::StringRef plugin_name,382 ListenerSP listener_sp,383 const FileSpec *crash_file_path,384 bool can_connect) {385 static uint32_t g_process_unique_id = 0;386 387 ProcessSP process_sp;388 ProcessCreateInstance create_callback = nullptr;389 if (!plugin_name.empty()) {390 create_callback =391 PluginManager::GetProcessCreateCallbackForPluginName(plugin_name);392 if (create_callback) {393 process_sp = create_callback(target_sp, listener_sp, crash_file_path,394 can_connect);395 if (process_sp) {396 if (process_sp->CanDebug(target_sp, true)) {397 process_sp->m_process_unique_id = ++g_process_unique_id;398 } else399 process_sp.reset();400 }401 }402 } else {403 for (uint32_t idx = 0;404 (create_callback =405 PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;406 ++idx) {407 process_sp = create_callback(target_sp, listener_sp, crash_file_path,408 can_connect);409 if (process_sp) {410 if (process_sp->CanDebug(target_sp, false)) {411 process_sp->m_process_unique_id = ++g_process_unique_id;412 break;413 } else414 process_sp.reset();415 }416 }417 }418 return process_sp;419}420 421llvm::StringRef Process::GetStaticBroadcasterClass() {422 static constexpr llvm::StringLiteral class_name("lldb.process");423 return class_name;424}425 426Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)427 : Process(target_sp, listener_sp, UnixSignals::CreateForHost()) {428 // This constructor just delegates to the full Process constructor,429 // defaulting to using the Host's UnixSignals.430}431 432Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,433 const UnixSignalsSP &unix_signals_sp)434 : ProcessProperties(this),435 Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),436 Process::GetStaticBroadcasterClass().str()),437 m_target_wp(target_sp), m_public_state(eStateUnloaded),438 m_private_state(eStateUnloaded),439 m_private_state_broadcaster(nullptr,440 "lldb.process.internal_state_broadcaster"),441 m_private_state_control_broadcaster(442 nullptr, "lldb.process.internal_state_control_broadcaster"),443 m_private_state_listener_sp(444 Listener::MakeListener("lldb.process.internal_state_listener")),445 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),446 m_thread_id_to_index_id_map(), m_exit_status(-1),447 m_thread_list_real(*this), m_thread_list(*this), m_thread_plans(*this),448 m_extended_thread_list(*this),449 m_base_direction(RunDirection::eRunForward), m_extended_thread_stop_id(0),450 m_queue_list(this), m_queue_list_stop_id(0),451 m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),452 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),453 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),454 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),455 m_memory_cache(*this), m_allocated_memory_cache(*this),456 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),457 m_private_run_lock(), m_currently_handling_do_on_removals(false),458 m_resume_requested(false), m_interrupt_tid(LLDB_INVALID_THREAD_ID),459 m_finalizing(false), m_destructing(false),460 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),461 m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),462 m_can_interpret_function_calls(false), m_run_thread_plan_lock(),463 m_can_jit(eCanJITDontKnow),464 m_crash_info_dict_sp(new StructuredData::Dictionary()) {465 CheckInWithManager();466 467 Log *log = GetLog(LLDBLog::Object);468 LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));469 470 if (!m_unix_signals_sp)471 m_unix_signals_sp = std::make_shared<UnixSignals>();472 473 SetEventName(eBroadcastBitStateChanged, "state-changed");474 SetEventName(eBroadcastBitInterrupt, "interrupt");475 SetEventName(eBroadcastBitSTDOUT, "stdout-available");476 SetEventName(eBroadcastBitSTDERR, "stderr-available");477 SetEventName(eBroadcastBitProfileData, "profile-data-available");478 SetEventName(eBroadcastBitStructuredData, "structured-data-available");479 480 m_private_state_control_broadcaster.SetEventName(481 eBroadcastInternalStateControlStop, "control-stop");482 m_private_state_control_broadcaster.SetEventName(483 eBroadcastInternalStateControlPause, "control-pause");484 m_private_state_control_broadcaster.SetEventName(485 eBroadcastInternalStateControlResume, "control-resume");486 487 // The listener passed into process creation is the primary listener:488 // It always listens for all the event bits for Process:489 SetPrimaryListener(listener_sp);490 491 m_private_state_listener_sp->StartListeningForEvents(492 &m_private_state_broadcaster,493 eBroadcastBitStateChanged | eBroadcastBitInterrupt);494 495 m_private_state_listener_sp->StartListeningForEvents(496 &m_private_state_control_broadcaster,497 eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |498 eBroadcastInternalStateControlResume);499 // We need something valid here, even if just the default UnixSignalsSP.500 assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");501 502 // Allow the platform to override the default cache line size503 OptionValueSP value_sp =504 m_collection_sp->GetPropertyAtIndex(ePropertyMemCacheLineSize)505 ->GetValue();506 uint64_t platform_cache_line_size =507 target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();508 if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)509 value_sp->SetValueAs(platform_cache_line_size);510 511 // FIXME: Frame recognizer registration should not be done in Target.512 // We should have a plugin do the registration instead, for example, a513 // common C LanguageRuntime plugin.514 RegisterAssertFrameRecognizer(this);515}516 517Process::~Process() {518 Log *log = GetLog(LLDBLog::Object);519 LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));520 StopPrivateStateThread();521 522 // ThreadList::Clear() will try to acquire this process's mutex, so523 // explicitly clear the thread list here to ensure that the mutex is not524 // destroyed before the thread list.525 m_thread_list.Clear();526}527 528ProcessProperties &Process::GetGlobalProperties() {529 // NOTE: intentional leak so we don't crash if global destructor chain gets530 // called as other threads still use the result of this function531 static ProcessProperties *g_settings_ptr =532 new ProcessProperties(nullptr);533 return *g_settings_ptr;534}535 536void Process::Finalize(bool destructing) {537 if (m_finalizing.exchange(true))538 return;539 if (destructing)540 m_destructing.exchange(true);541 542 // Destroy the process. This will call the virtual function DoDestroy under543 // the hood, giving our derived class a chance to do the ncessary tear down.544 DestroyImpl(false);545 546 // Clear our broadcaster before we proceed with destroying547 Broadcaster::Clear();548 549 // Do any cleanup needed prior to being destructed... Subclasses that550 // override this method should call this superclass method as well.551 552 // We need to destroy the loader before the derived Process class gets553 // destroyed since it is very likely that undoing the loader will require554 // access to the real process.555 m_dynamic_checkers_up.reset();556 m_abi_sp.reset();557 m_os_up.reset();558 m_system_runtime_up.reset();559 m_dyld_up.reset();560 m_jit_loaders_up.reset();561 m_thread_plans.Clear();562 m_thread_list_real.Destroy();563 m_thread_list.Destroy();564 m_extended_thread_list.Destroy();565 m_queue_list.Clear();566 m_queue_list_stop_id = 0;567 m_watchpoint_resource_list.Clear();568 std::vector<Notifications> empty_notifications;569 m_notifications.swap(empty_notifications);570 m_image_tokens.clear();571 m_memory_cache.Clear();572 m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);573 {574 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);575 m_language_runtimes.clear();576 }577 m_instrumentation_runtimes.clear();578 m_next_event_action_up.reset();579 // Clear the last natural stop ID since it has a strong reference to this580 // process581 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());582 // We have to be very careful here as the m_private_state_listener might583 // contain events that have ProcessSP values in them which can keep this584 // process around forever. These events need to be cleared out.585 m_private_state_listener_sp->Clear();586 m_public_run_lock.SetStopped();587 m_private_run_lock.SetStopped();588 m_structured_data_plugin_map.clear();589}590 591void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {592 m_notifications.push_back(callbacks);593 if (callbacks.initialize != nullptr)594 callbacks.initialize(callbacks.baton, this);595}596 597bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {598 std::vector<Notifications>::iterator pos, end = m_notifications.end();599 for (pos = m_notifications.begin(); pos != end; ++pos) {600 if (pos->baton == callbacks.baton &&601 pos->initialize == callbacks.initialize &&602 pos->process_state_changed == callbacks.process_state_changed) {603 m_notifications.erase(pos);604 return true;605 }606 }607 return false;608}609 610void Process::SynchronouslyNotifyStateChanged(StateType state) {611 std::vector<Notifications>::iterator notification_pos,612 notification_end = m_notifications.end();613 for (notification_pos = m_notifications.begin();614 notification_pos != notification_end; ++notification_pos) {615 if (notification_pos->process_state_changed)616 notification_pos->process_state_changed(notification_pos->baton, this,617 state);618 }619}620 621// FIXME: We need to do some work on events before the general Listener sees622// them.623// For instance if we are continuing from a breakpoint, we need to ensure that624// we do the little "insert real insn, step & stop" trick. But we can't do625// that when the event is delivered by the broadcaster - since that is done on626// the thread that is waiting for new events, so if we needed more than one627// event for our handling, we would stall. So instead we do it when we fetch628// the event off of the queue.629//630 631StateType Process::GetNextEvent(EventSP &event_sp) {632 StateType state = eStateInvalid;633 634 if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,635 std::chrono::seconds(0)) &&636 event_sp)637 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());638 639 return state;640}641 642void Process::SyncIOHandler(uint32_t iohandler_id,643 const Timeout<std::micro> &timeout) {644 // don't sync (potentially context switch) in case where there is no process645 // IO646 if (!ProcessIOHandlerExists())647 return;648 649 auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);650 651 Log *log = GetLog(LLDBLog::Process);652 if (Result) {653 LLDB_LOG(654 log,655 "waited from m_iohandler_sync to change from {0}. New value is {1}.",656 iohandler_id, *Result);657 } else {658 LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",659 iohandler_id);660 }661}662 663StateType Process::WaitForProcessToStop(664 const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,665 ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,666 SelectMostRelevant select_most_relevant) {667 // We can't just wait for a "stopped" event, because the stopped event may668 // have restarted the target. We have to actually check each event, and in669 // the case of a stopped event check the restarted flag on the event.670 if (event_sp_ptr)671 event_sp_ptr->reset();672 StateType state = GetState();673 // If we are exited or detached, we won't ever get back to any other valid674 // state...675 if (state == eStateDetached || state == eStateExited)676 return state;677 678 Log *log = GetLog(LLDBLog::Process);679 LLDB_LOG(log, "timeout = {0}", timeout);680 681 if (!wait_always && StateIsStoppedState(state, true) &&682 StateIsStoppedState(GetPrivateState(), true)) {683 LLDB_LOGF(log,684 "Process::%s returning without waiting for events; process "685 "private and public states are already 'stopped'.",686 __FUNCTION__);687 // We need to toggle the run lock as this won't get done in688 // SetPublicState() if the process is hijacked.689 if (hijack_listener_sp && use_run_lock)690 m_public_run_lock.SetStopped();691 return state;692 }693 694 while (state != eStateInvalid) {695 EventSP event_sp;696 state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);697 if (event_sp_ptr && event_sp)698 *event_sp_ptr = event_sp;699 700 bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);701 Process::HandleProcessStateChangedEvent(702 event_sp, stream, select_most_relevant, pop_process_io_handler);703 704 switch (state) {705 case eStateCrashed:706 case eStateDetached:707 case eStateExited:708 case eStateUnloaded:709 // We need to toggle the run lock as this won't get done in710 // SetPublicState() if the process is hijacked.711 if (hijack_listener_sp && use_run_lock)712 m_public_run_lock.SetStopped();713 return state;714 case eStateStopped:715 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))716 continue;717 else {718 // We need to toggle the run lock as this won't get done in719 // SetPublicState() if the process is hijacked.720 if (hijack_listener_sp && use_run_lock)721 m_public_run_lock.SetStopped();722 return state;723 }724 default:725 continue;726 }727 }728 return state;729}730 731bool Process::HandleProcessStateChangedEvent(732 const EventSP &event_sp, Stream *stream,733 SelectMostRelevant select_most_relevant,734 bool &pop_process_io_handler) {735 const bool handle_pop = pop_process_io_handler;736 737 pop_process_io_handler = false;738 ProcessSP process_sp =739 Process::ProcessEventData::GetProcessFromEvent(event_sp.get());740 741 if (!process_sp)742 return false;743 744 StateType event_state =745 Process::ProcessEventData::GetStateFromEvent(event_sp.get());746 if (event_state == eStateInvalid)747 return false;748 749 switch (event_state) {750 case eStateInvalid:751 case eStateUnloaded:752 case eStateAttaching:753 case eStateLaunching:754 case eStateStepping:755 case eStateDetached:756 if (stream)757 stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),758 StateAsCString(event_state));759 if (event_state == eStateDetached)760 pop_process_io_handler = true;761 break;762 763 case eStateConnected:764 case eStateRunning:765 // Don't be chatty when we run...766 break;767 768 case eStateExited:769 if (stream)770 process_sp->GetStatus(*stream);771 pop_process_io_handler = true;772 break;773 774 case eStateStopped:775 case eStateCrashed:776 case eStateSuspended:777 // Make sure the program hasn't been auto-restarted:778 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {779 if (stream) {780 size_t num_reasons =781 Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());782 if (num_reasons > 0) {783 // FIXME: Do we want to report this, or would that just be annoyingly784 // chatty?785 if (num_reasons == 1) {786 const char *reason =787 Process::ProcessEventData::GetRestartedReasonAtIndex(788 event_sp.get(), 0);789 stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",790 process_sp->GetID(),791 reason ? reason : "<UNKNOWN REASON>");792 } else {793 stream->Printf("Process %" PRIu64794 " stopped and restarted, reasons:\n",795 process_sp->GetID());796 797 for (size_t i = 0; i < num_reasons; i++) {798 const char *reason =799 Process::ProcessEventData::GetRestartedReasonAtIndex(800 event_sp.get(), i);801 stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");802 }803 }804 }805 }806 } else {807 StopInfoSP curr_thread_stop_info_sp;808 // Lock the thread list so it doesn't change on us, this is the scope for809 // the locker:810 {811 ThreadList &thread_list = process_sp->GetThreadList();812 std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());813 814 ThreadSP curr_thread(thread_list.GetSelectedThread());815 816 if (curr_thread && curr_thread->IsValid())817 curr_thread_stop_info_sp = curr_thread->GetStopInfo();818 bool prefer_curr_thread = curr_thread_stop_info_sp &&819 curr_thread_stop_info_sp->ShouldSelect();820 821 if (!prefer_curr_thread) {822 // Prefer a thread that has just completed its plan over another823 // thread as current thread.824 ThreadSP plan_thread;825 ThreadSP other_thread;826 827 for (ThreadSP thread : thread_list.Threads()) {828 StopInfoSP stop_info = thread->GetStopInfo();829 if (!stop_info || !stop_info->ShouldSelect())830 continue;831 StopReason thread_stop_reason = stop_info->GetStopReason();832 if (thread_stop_reason == eStopReasonPlanComplete) {833 if (!plan_thread)834 plan_thread = thread;835 } else if (!other_thread) {836 other_thread = thread;837 }838 }839 if (plan_thread)840 thread_list.SetSelectedThreadByID(plan_thread->GetID());841 else if (other_thread)842 thread_list.SetSelectedThreadByID(other_thread->GetID());843 else {844 ThreadSP thread;845 if (curr_thread && curr_thread->IsValid())846 thread = curr_thread;847 else848 thread = thread_list.GetThreadAtIndex(0);849 850 if (thread)851 thread_list.SetSelectedThreadByID(thread->GetID());852 }853 }854 }855 // Drop the ThreadList mutex by here, since GetThreadStatus below might856 // have to run code, e.g. for Data formatters, and if we hold the857 // ThreadList mutex, then the process is going to have a hard time858 // restarting the process.859 if (stream) {860 Debugger &debugger = process_sp->GetTarget().GetDebugger();861 if (debugger.GetTargetList().GetSelectedTarget().get() ==862 &process_sp->GetTarget()) {863 ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();864 865 if (!thread_sp || !thread_sp->IsValid())866 return false;867 868 const bool only_threads_with_stop_reason = true;869 const uint32_t start_frame =870 thread_sp->GetSelectedFrameIndex(select_most_relevant);871 const uint32_t num_frames = 1;872 const uint32_t num_frames_with_source = 1;873 const bool stop_format = true;874 875 process_sp->GetStatus(*stream);876 process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,877 start_frame, num_frames,878 num_frames_with_source,879 stop_format);880 if (curr_thread_stop_info_sp) {881 lldb::addr_t crashing_address;882 ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(883 curr_thread_stop_info_sp, &crashing_address);884 if (valobj_sp) {885 const ValueObject::GetExpressionPathFormat format =886 ValueObject::GetExpressionPathFormat::887 eGetExpressionPathFormatHonorPointers;888 stream->PutCString("Likely cause: ");889 valobj_sp->GetExpressionPath(*stream, format);890 stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);891 }892 }893 } else {894 uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(895 process_sp->GetTarget().shared_from_this());896 if (target_idx != UINT32_MAX)897 stream->Printf("Target %d: (", target_idx);898 else899 stream->Printf("Target <unknown index>: (");900 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);901 stream->Printf(") stopped.\n");902 }903 }904 905 // Pop the process IO handler906 pop_process_io_handler = true;907 }908 break;909 }910 911 if (handle_pop && pop_process_io_handler)912 process_sp->PopProcessIOHandler();913 914 return true;915}916 917bool Process::HijackProcessEvents(ListenerSP listener_sp) {918 if (listener_sp) {919 return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |920 eBroadcastBitInterrupt);921 } else922 return false;923}924 925void Process::RestoreProcessEvents() { RestoreBroadcaster(); }926 927StateType Process::GetStateChangedEvents(EventSP &event_sp,928 const Timeout<std::micro> &timeout,929 ListenerSP hijack_listener_sp) {930 Log *log = GetLog(LLDBLog::Process);931 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);932 933 ListenerSP listener_sp = hijack_listener_sp;934 if (!listener_sp)935 listener_sp = GetPrimaryListener();936 937 StateType state = eStateInvalid;938 if (listener_sp->GetEventForBroadcasterWithType(939 this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,940 timeout)) {941 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)942 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());943 else944 LLDB_LOG(log, "got no event or was interrupted.");945 }946 947 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);948 return state;949}950 951Event *Process::PeekAtStateChangedEvents() {952 Log *log = GetLog(LLDBLog::Process);953 954 LLDB_LOGF(log, "Process::%s...", __FUNCTION__);955 956 Event *event_ptr;957 event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(958 this, eBroadcastBitStateChanged);959 if (log) {960 if (event_ptr) {961 LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,962 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));963 } else {964 LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);965 }966 }967 return event_ptr;968}969 970StateType971Process::GetStateChangedEventsPrivate(EventSP &event_sp,972 const Timeout<std::micro> &timeout) {973 Log *log = GetLog(LLDBLog::Process);974 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);975 976 StateType state = eStateInvalid;977 if (m_private_state_listener_sp->GetEventForBroadcasterWithType(978 &m_private_state_broadcaster,979 eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,980 timeout))981 if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)982 state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());983 984 LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,985 state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));986 return state;987}988 989bool Process::GetEventsPrivate(EventSP &event_sp,990 const Timeout<std::micro> &timeout,991 bool control_only) {992 Log *log = GetLog(LLDBLog::Process);993 LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);994 995 if (control_only)996 return m_private_state_listener_sp->GetEventForBroadcaster(997 &m_private_state_control_broadcaster, event_sp, timeout);998 else999 return m_private_state_listener_sp->GetEvent(event_sp, timeout);1000}1001 1002bool Process::IsRunning() const {1003 return StateIsRunningState(m_public_state.GetValue());1004}1005 1006int Process::GetExitStatus() {1007 std::lock_guard<std::mutex> guard(m_exit_status_mutex);1008 1009 if (m_public_state.GetValue() == eStateExited)1010 return m_exit_status;1011 return -1;1012}1013 1014const char *Process::GetExitDescription() {1015 std::lock_guard<std::mutex> guard(m_exit_status_mutex);1016 1017 if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())1018 return m_exit_string.c_str();1019 return nullptr;1020}1021 1022bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {1023 // Use a mutex to protect setting the exit status.1024 std::lock_guard<std::mutex> guard(m_exit_status_mutex);1025 Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1026 LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",1027 GetPluginName(), status, exit_string);1028 1029 // We were already in the exited state1030 if (m_private_state.GetValue() == eStateExited) {1031 LLDB_LOG(1032 log,1033 "(plugin = {0}) ignoring exit status because state was already set "1034 "to eStateExited",1035 GetPluginName());1036 return false;1037 }1038 1039 telemetry::ScopedDispatcher<telemetry::ProcessExitInfo> helper;1040 1041 UUID module_uuid;1042 // Need this check because the pointer may not be valid at this point.1043 if (TargetSP target_sp = m_target_wp.lock()) {1044 helper.SetDebugger(&target_sp->GetDebugger());1045 if (ModuleSP mod = target_sp->GetExecutableModule())1046 module_uuid = mod->GetUUID();1047 }1048 1049 helper.DispatchNow([&](telemetry::ProcessExitInfo *info) {1050 info->module_uuid = module_uuid;1051 info->pid = m_pid;1052 info->is_start_entry = true;1053 info->exit_desc = {status, exit_string.str()};1054 });1055 1056 helper.DispatchOnExit(1057 [module_uuid, pid = m_pid](telemetry::ProcessExitInfo *info) {1058 info->module_uuid = module_uuid;1059 info->pid = pid;1060 });1061 1062 m_exit_status = status;1063 if (!exit_string.empty())1064 m_exit_string = exit_string.str();1065 else1066 m_exit_string.clear();1067 1068 // Clear the last natural stop ID since it has a strong reference to this1069 // process1070 m_mod_id.SetStopEventForLastNaturalStopID(EventSP());1071 1072 SetPrivateState(eStateExited);1073 1074 // Allow subclasses to do some cleanup1075 DidExit();1076 1077 return true;1078}1079 1080bool Process::IsAlive() {1081 switch (m_private_state.GetValue()) {1082 case eStateConnected:1083 case eStateAttaching:1084 case eStateLaunching:1085 case eStateStopped:1086 case eStateRunning:1087 case eStateStepping:1088 case eStateCrashed:1089 case eStateSuspended:1090 return true;1091 default:1092 return false;1093 }1094}1095 1096// This static callback can be used to watch for local child processes on the1097// current host. The child process exits, the process will be found in the1098// global target list (we want to be completely sure that the1099// lldb_private::Process doesn't go away before we can deliver the signal.1100bool Process::SetProcessExitStatus(1101 lldb::pid_t pid, bool exited,1102 int signo, // Zero for no signal1103 int exit_status // Exit value of process if signal is zero1104 ) {1105 Log *log = GetLog(LLDBLog::Process);1106 LLDB_LOGF(log,1107 "Process::SetProcessExitStatus (pid=%" PRIu641108 ", exited=%i, signal=%i, exit_status=%i)\n",1109 pid, exited, signo, exit_status);1110 1111 if (exited) {1112 TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));1113 if (target_sp) {1114 ProcessSP process_sp(target_sp->GetProcessSP());1115 if (process_sp) {1116 llvm::StringRef signal_str =1117 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);1118 process_sp->SetExitStatus(exit_status, signal_str);1119 }1120 }1121 return true;1122 }1123 return false;1124}1125 1126bool Process::UpdateThreadList(ThreadList &old_thread_list,1127 ThreadList &new_thread_list) {1128 m_thread_plans.ClearThreadCache();1129 return DoUpdateThreadList(old_thread_list, new_thread_list);1130}1131 1132void Process::UpdateThreadListIfNeeded() {1133 const uint32_t stop_id = GetStopID();1134 if (m_thread_list.GetSize(false) == 0 ||1135 stop_id != m_thread_list.GetStopID()) {1136 bool clear_unused_threads = true;1137 const StateType state = GetPrivateState();1138 if (StateIsStoppedState(state, true)) {1139 std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());1140 m_thread_list.SetStopID(stop_id);1141 1142 // m_thread_list does have its own mutex, but we need to hold onto the1143 // mutex between the call to UpdateThreadList(...) and the1144 // os->UpdateThreadList(...) so it doesn't change on us1145 ThreadList &old_thread_list = m_thread_list;1146 ThreadList real_thread_list(*this);1147 ThreadList new_thread_list(*this);1148 // Always update the thread list with the protocol specific thread list,1149 // but only update if "true" is returned1150 if (UpdateThreadList(m_thread_list_real, real_thread_list)) {1151 // Don't call into the OperatingSystem to update the thread list if we1152 // are shutting down, since that may call back into the SBAPI's,1153 // requiring the API lock which is already held by whoever is shutting1154 // us down, causing a deadlock.1155 OperatingSystem *os = GetOperatingSystem();1156 if (os && !m_destroy_in_process) {1157 // Clear any old backing threads where memory threads might have been1158 // backed by actual threads from the lldb_private::Process subclass1159 size_t num_old_threads = old_thread_list.GetSize(false);1160 for (size_t i = 0; i < num_old_threads; ++i)1161 old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();1162 // See if the OS plugin reports all threads. If it does, then1163 // it is safe to clear unseen thread's plans here. Otherwise we1164 // should preserve them in case they show up again:1165 clear_unused_threads = os->DoesPluginReportAllThreads();1166 1167 // Turn off dynamic types to ensure we don't run any expressions.1168 // Objective-C can run an expression to determine if a SBValue is a1169 // dynamic type or not and we need to avoid this. OperatingSystem1170 // plug-ins can't run expressions that require running code...1171 1172 Target &target = GetTarget();1173 const lldb::DynamicValueType saved_prefer_dynamic =1174 target.GetPreferDynamicValue();1175 if (saved_prefer_dynamic != lldb::eNoDynamicValues)1176 target.SetPreferDynamicValue(lldb::eNoDynamicValues);1177 1178 // Now let the OperatingSystem plug-in update the thread list1179 1180 os->UpdateThreadList(1181 old_thread_list, // Old list full of threads created by OS plug-in1182 real_thread_list, // The actual thread list full of threads1183 // created by each lldb_private::Process1184 // subclass1185 new_thread_list); // The new thread list that we will show to the1186 // user that gets filled in1187 1188 if (saved_prefer_dynamic != lldb::eNoDynamicValues)1189 target.SetPreferDynamicValue(saved_prefer_dynamic);1190 } else {1191 // No OS plug-in, the new thread list is the same as the real thread1192 // list.1193 new_thread_list = real_thread_list;1194 }1195 1196 m_thread_list_real.Update(real_thread_list);1197 m_thread_list.Update(new_thread_list);1198 m_thread_list.SetStopID(stop_id);1199 1200 if (GetLastNaturalStopID() != m_extended_thread_stop_id) {1201 // Clear any extended threads that we may have accumulated previously1202 m_extended_thread_list.Clear();1203 m_extended_thread_stop_id = GetLastNaturalStopID();1204 1205 m_queue_list.Clear();1206 m_queue_list_stop_id = GetLastNaturalStopID();1207 }1208 }1209 // Now update the plan stack map.1210 // If we do have an OS plugin, any absent real threads in the1211 // m_thread_list have already been removed from the ThreadPlanStackMap.1212 // So any remaining threads are OS Plugin threads, and those we want to1213 // preserve in case they show up again.1214 m_thread_plans.Update(m_thread_list, clear_unused_threads);1215 }1216 }1217}1218 1219ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {1220 return m_thread_plans.Find(tid);1221}1222 1223bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {1224 return m_thread_plans.PrunePlansForTID(tid);1225}1226 1227void Process::PruneThreadPlans() {1228 m_thread_plans.Update(GetThreadList(), true, false);1229}1230 1231bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,1232 lldb::DescriptionLevel desc_level,1233 bool internal, bool condense_trivial,1234 bool skip_unreported_plans) {1235 return m_thread_plans.DumpPlansForTID(1236 strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);1237}1238void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,1239 bool internal, bool condense_trivial,1240 bool skip_unreported_plans) {1241 m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,1242 skip_unreported_plans);1243}1244 1245void Process::UpdateQueueListIfNeeded() {1246 if (m_system_runtime_up) {1247 if (m_queue_list.GetSize() == 0 ||1248 m_queue_list_stop_id != GetLastNaturalStopID()) {1249 const StateType state = GetPrivateState();1250 if (StateIsStoppedState(state, true)) {1251 m_system_runtime_up->PopulateQueueList(m_queue_list);1252 m_queue_list_stop_id = GetLastNaturalStopID();1253 }1254 }1255 }1256}1257 1258ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {1259 OperatingSystem *os = GetOperatingSystem();1260 if (os)1261 return os->CreateThread(tid, context);1262 return ThreadSP();1263}1264 1265uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {1266 return AssignIndexIDToThread(thread_id);1267}1268 1269bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {1270 return (m_thread_id_to_index_id_map.find(thread_id) !=1271 m_thread_id_to_index_id_map.end());1272}1273 1274uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {1275 auto [iterator, inserted] =1276 m_thread_id_to_index_id_map.try_emplace(thread_id, m_thread_index_id + 1);1277 if (inserted)1278 ++m_thread_index_id;1279 1280 return iterator->second;1281}1282 1283StateType Process::GetState() {1284 if (CurrentThreadPosesAsPrivateStateThread())1285 return m_private_state.GetValue();1286 else1287 return m_public_state.GetValue();1288}1289 1290void Process::SetPublicState(StateType new_state, bool restarted) {1291 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);1292 if (new_state_is_stopped) {1293 // This will only set the time if the public stop time has no value, so1294 // it is ok to call this multiple times. With a public stop we can't look1295 // at the stop ID because many private stops might have happened, so we1296 // can't check for a stop ID of zero. This allows the "statistics" command1297 // to dump the time it takes to reach somewhere in your code, like a1298 // breakpoint you set.1299 GetTarget().GetStatistics().SetFirstPublicStopTime();1300 }1301 1302 Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1303 LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",1304 GetPluginName().data(), StateAsCString(new_state), restarted);1305 const StateType old_state = m_public_state.GetValue();1306 m_public_state.SetValue(new_state);1307 1308 // On the transition from Run to Stopped, we unlock the writer end of the run1309 // lock. The lock gets locked in Resume, which is the public API to tell the1310 // program to run.1311 if (!StateChangedIsExternallyHijacked()) {1312 if (new_state == eStateDetached) {1313 LLDB_LOGF(log,1314 "(plugin = %s, state = %s) -- unlocking run lock for detach",1315 GetPluginName().data(), StateAsCString(new_state));1316 m_public_run_lock.SetStopped();1317 } else {1318 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);1319 if ((old_state_is_stopped != new_state_is_stopped)) {1320 if (new_state_is_stopped && !restarted) {1321 LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",1322 GetPluginName().data(), StateAsCString(new_state));1323 m_public_run_lock.SetStopped();1324 }1325 }1326 }1327 }1328}1329 1330Status Process::Resume() {1331 Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1332 LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());1333 if (!m_public_run_lock.SetRunning()) {1334 LLDB_LOGF(log, "(plugin = %s) -- SetRunning failed, not resuming.",1335 GetPluginName().data());1336 return Status::FromErrorString(1337 "resume request failed - process already running");1338 }1339 Status error = PrivateResume();1340 if (!error.Success()) {1341 // Undo running state change1342 m_public_run_lock.SetStopped();1343 }1344 return error;1345}1346 1347Status Process::ResumeSynchronous(Stream *stream) {1348 Log *log(GetLog(LLDBLog::State | LLDBLog::Process));1349 LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");1350 if (!m_public_run_lock.SetRunning()) {1351 LLDB_LOGF(log, "Process::Resume: -- SetRunning failed, not resuming.");1352 return Status::FromErrorString(1353 "resume request failed: process already running");1354 }1355 1356 ListenerSP listener_sp(1357 Listener::MakeListener(ResumeSynchronousHijackListenerName.data()));1358 HijackProcessEvents(listener_sp);1359 1360 Status error = PrivateResume();1361 if (error.Success()) {1362 StateType state =1363 WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,1364 true /* use_run_lock */, SelectMostRelevantFrame);1365 const bool must_be_alive =1366 false; // eStateExited is ok, so this must be false1367 if (!StateIsStoppedState(state, must_be_alive))1368 error = Status::FromErrorStringWithFormat(1369 "process not in stopped state after synchronous resume: %s",1370 StateAsCString(state));1371 } else {1372 // Undo running state change1373 m_public_run_lock.SetStopped();1374 }1375 1376 // Undo the hijacking of process events...1377 RestoreProcessEvents();1378 1379 return error;1380}1381 1382bool Process::StateChangedIsExternallyHijacked() {1383 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {1384 llvm::StringRef hijacking_name = GetHijackingListenerName();1385 if (!hijacking_name.starts_with("lldb.internal"))1386 return true;1387 }1388 return false;1389}1390 1391bool Process::StateChangedIsHijackedForSynchronousResume() {1392 if (IsHijackedForEvent(eBroadcastBitStateChanged)) {1393 llvm::StringRef hijacking_name = GetHijackingListenerName();1394 if (hijacking_name == ResumeSynchronousHijackListenerName)1395 return true;1396 }1397 return false;1398}1399 1400StateType Process::GetPrivateState() { return m_private_state.GetValue(); }1401 1402void Process::SetPrivateState(StateType new_state) {1403 // Use m_destructing not m_finalizing here. If we are finalizing a process1404 // that we haven't started tearing down, we'd like to be able to nicely1405 // detach if asked, but that requires the event system be live. That will1406 // not be true for an in-the-middle-of-being-destructed Process, since the1407 // event system relies on Process::shared_from_this, which may have already1408 // been destroyed.1409 if (m_destructing)1410 return;1411 1412 Log *log(GetLog(LLDBLog::State | LLDBLog::Process | LLDBLog::Unwind));1413 bool state_changed = false;1414 1415 LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),1416 StateAsCString(new_state));1417 1418 std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());1419 std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());1420 1421 const StateType old_state = m_private_state.GetValueNoLock();1422 state_changed = old_state != new_state;1423 1424 const bool old_state_is_stopped = StateIsStoppedState(old_state, false);1425 const bool new_state_is_stopped = StateIsStoppedState(new_state, false);1426 if (old_state_is_stopped != new_state_is_stopped) {1427 if (new_state_is_stopped)1428 m_private_run_lock.SetStopped();1429 else1430 m_private_run_lock.SetRunning();1431 }1432 1433 if (state_changed) {1434 m_private_state.SetValueNoLock(new_state);1435 EventSP event_sp(1436 new Event(eBroadcastBitStateChanged,1437 new ProcessEventData(shared_from_this(), new_state)));1438 if (StateIsStoppedState(new_state, false)) {1439 // Note, this currently assumes that all threads in the list stop when1440 // the process stops. In the future we will want to support a debugging1441 // model where some threads continue to run while others are stopped.1442 // When that happens we will either need a way for the thread list to1443 // identify which threads are stopping or create a special thread list1444 // containing only threads which actually stopped.1445 //1446 // The process plugin is responsible for managing the actual behavior of1447 // the threads and should have stopped any threads that are going to stop1448 // before we get here.1449 m_thread_list.DidStop();1450 1451 if (m_mod_id.BumpStopID() == 0)1452 GetTarget().GetStatistics().SetFirstPrivateStopTime();1453 1454 if (!m_mod_id.IsLastResumeForUserExpression())1455 m_mod_id.SetStopEventForLastNaturalStopID(event_sp);1456 m_memory_cache.Clear();1457 LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",1458 GetPluginName().data(), StateAsCString(new_state),1459 m_mod_id.GetStopID());1460 }1461 1462 m_private_state_broadcaster.BroadcastEvent(event_sp);1463 } else {1464 LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",1465 GetPluginName().data(), StateAsCString(new_state));1466 }1467}1468 1469void Process::SetRunningUserExpression(bool on) {1470 m_mod_id.SetRunningUserExpression(on);1471}1472 1473void Process::SetRunningUtilityFunction(bool on) {1474 m_mod_id.SetRunningUtilityFunction(on);1475}1476 1477addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }1478 1479const lldb::ABISP &Process::GetABI() {1480 if (!m_abi_sp)1481 m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());1482 return m_abi_sp;1483}1484 1485std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {1486 std::vector<LanguageRuntime *> language_runtimes;1487 1488 if (m_finalizing)1489 return language_runtimes;1490 1491 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);1492 // Before we pass off a copy of the language runtimes, we must make sure that1493 // our collection is properly populated. It's possible that some of the1494 // language runtimes were not loaded yet, either because nobody requested it1495 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so1496 // hadn't been loaded).1497 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {1498 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))1499 language_runtimes.emplace_back(runtime);1500 }1501 1502 return language_runtimes;1503}1504 1505LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {1506 if (m_finalizing)1507 return nullptr;1508 1509 LanguageRuntime *runtime = nullptr;1510 1511 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);1512 LanguageRuntimeCollection::iterator pos;1513 pos = m_language_runtimes.find(language);1514 if (pos == m_language_runtimes.end() || !pos->second) {1515 lldb::LanguageRuntimeSP runtime_sp(1516 LanguageRuntime::FindPlugin(this, language));1517 1518 m_language_runtimes[language] = runtime_sp;1519 runtime = runtime_sp.get();1520 } else1521 runtime = pos->second.get();1522 1523 if (runtime)1524 // It's possible that a language runtime can support multiple LanguageTypes,1525 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,1526 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the1527 // primary language type and make sure that our runtime supports it.1528 assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));1529 1530 return runtime;1531}1532 1533bool Process::IsPossibleDynamicValue(ValueObject &in_value) {1534 if (m_finalizing)1535 return false;1536 1537 if (in_value.IsDynamic())1538 return false;1539 LanguageType known_type = in_value.GetObjectRuntimeLanguage();1540 1541 if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {1542 LanguageRuntime *runtime = GetLanguageRuntime(known_type);1543 return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;1544 }1545 1546 for (LanguageRuntime *runtime : GetLanguageRuntimes()) {1547 if (runtime->CouldHaveDynamicValue(in_value))1548 return true;1549 }1550 1551 return false;1552}1553 1554void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {1555 m_dynamic_checkers_up.reset(dynamic_checkers);1556}1557 1558StopPointSiteList<BreakpointSite> &Process::GetBreakpointSiteList() {1559 return m_breakpoint_site_list;1560}1561 1562const StopPointSiteList<BreakpointSite> &1563Process::GetBreakpointSiteList() const {1564 return m_breakpoint_site_list;1565}1566 1567void Process::DisableAllBreakpointSites() {1568 m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {1569 // bp_site->SetEnabled(true);1570 DisableBreakpointSite(bp_site);1571 });1572}1573 1574Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {1575 Status error(DisableBreakpointSiteByID(break_id));1576 1577 if (error.Success())1578 m_breakpoint_site_list.Remove(break_id);1579 1580 return error;1581}1582 1583Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {1584 Status error;1585 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);1586 if (bp_site_sp) {1587 if (bp_site_sp->IsEnabled())1588 error = DisableBreakpointSite(bp_site_sp.get());1589 } else {1590 error = Status::FromErrorStringWithFormat(1591 "invalid breakpoint site ID: %" PRIu64, break_id);1592 }1593 1594 return error;1595}1596 1597Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {1598 Status error;1599 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);1600 if (bp_site_sp) {1601 if (!bp_site_sp->IsEnabled())1602 error = EnableBreakpointSite(bp_site_sp.get());1603 } else {1604 error = Status::FromErrorStringWithFormat(1605 "invalid breakpoint site ID: %" PRIu64, break_id);1606 }1607 return error;1608}1609 1610lldb::break_id_t1611Process::CreateBreakpointSite(const BreakpointLocationSP &constituent,1612 bool use_hardware) {1613 addr_t load_addr = LLDB_INVALID_ADDRESS;1614 1615 bool show_error = true;1616 switch (GetState()) {1617 case eStateInvalid:1618 case eStateUnloaded:1619 case eStateConnected:1620 case eStateAttaching:1621 case eStateLaunching:1622 case eStateDetached:1623 case eStateExited:1624 show_error = false;1625 break;1626 1627 case eStateStopped:1628 case eStateRunning:1629 case eStateStepping:1630 case eStateCrashed:1631 case eStateSuspended:1632 show_error = IsAlive();1633 break;1634 }1635 1636 // Reset the IsIndirect flag here, in case the location changes from pointing1637 // to a indirect symbol to a regular symbol.1638 constituent->SetIsIndirect(false);1639 1640 if (constituent->ShouldResolveIndirectFunctions()) {1641 Symbol *symbol = constituent->GetAddress().CalculateSymbolContextSymbol();1642 if (symbol && symbol->IsIndirect()) {1643 Status error;1644 Address symbol_address = symbol->GetAddress();1645 load_addr = ResolveIndirectFunction(&symbol_address, error);1646 if (!error.Success() && show_error) {1647 GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(1648 "warning: failed to resolve indirect function at 0x%" PRIx641649 " for breakpoint %i.%i: %s\n",1650 symbol->GetLoadAddress(&GetTarget()),1651 constituent->GetBreakpoint().GetID(), constituent->GetID(),1652 error.AsCString() ? error.AsCString() : "unknown error");1653 return LLDB_INVALID_BREAK_ID;1654 }1655 Address resolved_address(load_addr);1656 load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());1657 constituent->SetIsIndirect(true);1658 } else1659 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());1660 } else1661 load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());1662 1663 if (load_addr != LLDB_INVALID_ADDRESS) {1664 BreakpointSiteSP bp_site_sp;1665 1666 // Look up this breakpoint site. If it exists, then add this new1667 // constituent, otherwise create a new breakpoint site and add it.1668 1669 bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);1670 1671 if (bp_site_sp) {1672 bp_site_sp->AddConstituent(constituent);1673 constituent->SetBreakpointSite(bp_site_sp);1674 return bp_site_sp->GetID();1675 } else {1676 bp_site_sp.reset(1677 new BreakpointSite(constituent, load_addr, use_hardware));1678 if (bp_site_sp) {1679 Status error = EnableBreakpointSite(bp_site_sp.get());1680 if (error.Success()) {1681 constituent->SetBreakpointSite(bp_site_sp);1682 return m_breakpoint_site_list.Add(bp_site_sp);1683 } else {1684 if (show_error || use_hardware) {1685 // Report error for setting breakpoint...1686 GetTarget().GetDebugger().GetAsyncErrorStream()->Printf(1687 "warning: failed to set breakpoint site at 0x%" PRIx641688 " for breakpoint %i.%i: %s\n",1689 load_addr, constituent->GetBreakpoint().GetID(),1690 constituent->GetID(),1691 error.AsCString() ? error.AsCString() : "unknown error");1692 }1693 }1694 }1695 }1696 }1697 // We failed to enable the breakpoint1698 return LLDB_INVALID_BREAK_ID;1699}1700 1701void Process::RemoveConstituentFromBreakpointSite(1702 lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,1703 BreakpointSiteSP &bp_site_sp) {1704 uint32_t num_constituents =1705 bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);1706 if (num_constituents == 0) {1707 // Don't try to disable the site if we don't have a live process anymore.1708 if (IsAlive())1709 DisableBreakpointSite(bp_site_sp.get());1710 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());1711 }1712}1713 1714size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,1715 uint8_t *buf) const {1716 size_t bytes_removed = 0;1717 StopPointSiteList<BreakpointSite> bp_sites_in_range;1718 1719 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,1720 bp_sites_in_range)) {1721 bp_sites_in_range.ForEach([bp_addr, size,1722 buf](BreakpointSite *bp_site) -> void {1723 if (bp_site->GetType() == BreakpointSite::eSoftware) {1724 addr_t intersect_addr;1725 size_t intersect_size;1726 size_t opcode_offset;1727 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,1728 &intersect_size, &opcode_offset)) {1729 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);1730 assert(bp_addr < intersect_addr + intersect_size &&1731 intersect_addr + intersect_size <= bp_addr + size);1732 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());1733 size_t buf_offset = intersect_addr - bp_addr;1734 ::memcpy(buf + buf_offset,1735 bp_site->GetSavedOpcodeBytes() + opcode_offset,1736 intersect_size);1737 }1738 }1739 });1740 }1741 return bytes_removed;1742}1743 1744size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {1745 PlatformSP platform_sp(GetTarget().GetPlatform());1746 if (platform_sp)1747 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);1748 return 0;1749}1750 1751Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {1752 Status error;1753 assert(bp_site != nullptr);1754 Log *log = GetLog(LLDBLog::Breakpoints);1755 const addr_t bp_addr = bp_site->GetLoadAddress();1756 LLDB_LOGF(1757 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,1758 bp_site->GetID(), (uint64_t)bp_addr);1759 if (bp_site->IsEnabled()) {1760 LLDB_LOGF(1761 log,1762 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641763 " -- already enabled",1764 bp_site->GetID(), (uint64_t)bp_addr);1765 return error;1766 }1767 1768 if (bp_addr == LLDB_INVALID_ADDRESS) {1769 error = Status::FromErrorString(1770 "BreakpointSite contains an invalid load address.");1771 return error;1772 }1773 // Ask the lldb::Process subclass to fill in the correct software breakpoint1774 // trap for the breakpoint site1775 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);1776 1777 if (bp_opcode_size == 0) {1778 error = Status::FromErrorStringWithFormat(1779 "Process::GetSoftwareBreakpointTrapOpcode() "1780 "returned zero, unable to get breakpoint "1781 "trap for address 0x%" PRIx64,1782 bp_addr);1783 } else {1784 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();1785 1786 if (bp_opcode_bytes == nullptr) {1787 error = Status::FromErrorString(1788 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");1789 return error;1790 }1791 1792 // Save the original opcode by reading it1793 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,1794 error) == bp_opcode_size) {1795 // Write a software breakpoint in place of the original opcode1796 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==1797 bp_opcode_size) {1798 uint8_t verify_bp_opcode_bytes[64];1799 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,1800 error) == bp_opcode_size) {1801 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,1802 bp_opcode_size) == 0) {1803 bp_site->SetEnabled(true);1804 bp_site->SetType(BreakpointSite::eSoftware);1805 LLDB_LOGF(log,1806 "Process::EnableSoftwareBreakpoint (site_id = %d) "1807 "addr = 0x%" PRIx64 " -- SUCCESS",1808 bp_site->GetID(), (uint64_t)bp_addr);1809 } else1810 error = Status::FromErrorString(1811 "failed to verify the breakpoint trap in memory.");1812 } else1813 error = Status::FromErrorString(1814 "Unable to read memory to verify breakpoint trap.");1815 } else1816 error = Status::FromErrorString(1817 "Unable to write breakpoint trap to memory.");1818 } else1819 error = Status::FromErrorString(1820 "Unable to read memory at breakpoint address.");1821 }1822 if (log && error.Fail())1823 LLDB_LOGF(1824 log,1825 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641826 " -- FAILED: %s",1827 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());1828 return error;1829}1830 1831Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {1832 Status error;1833 assert(bp_site != nullptr);1834 Log *log = GetLog(LLDBLog::Breakpoints);1835 addr_t bp_addr = bp_site->GetLoadAddress();1836 lldb::user_id_t breakID = bp_site->GetID();1837 LLDB_LOGF(log,1838 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu641839 ") addr = 0x%" PRIx64,1840 breakID, (uint64_t)bp_addr);1841 1842 if (bp_site->IsHardware()) {1843 error =1844 Status::FromErrorString("Breakpoint site is a hardware breakpoint.");1845 } else if (bp_site->IsEnabled()) {1846 const size_t break_op_size = bp_site->GetByteSize();1847 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();1848 if (break_op_size > 0) {1849 // Clear a software breakpoint instruction1850 uint8_t curr_break_op[8];1851 assert(break_op_size <= sizeof(curr_break_op));1852 bool break_op_found = false;1853 1854 // Read the breakpoint opcode1855 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==1856 break_op_size) {1857 bool verify = false;1858 // Make sure the breakpoint opcode exists at this address1859 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {1860 break_op_found = true;1861 // We found a valid breakpoint opcode at this address, now restore1862 // the saved opcode.1863 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),1864 break_op_size, error) == break_op_size) {1865 verify = true;1866 } else1867 error = Status::FromErrorString(1868 "Memory write failed when restoring original opcode.");1869 } else {1870 error = Status::FromErrorString(1871 "Original breakpoint trap is no longer in memory.");1872 // Set verify to true and so we can check if the original opcode has1873 // already been restored1874 verify = true;1875 }1876 1877 if (verify) {1878 uint8_t verify_opcode[8];1879 assert(break_op_size < sizeof(verify_opcode));1880 // Verify that our original opcode made it back to the inferior1881 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==1882 break_op_size) {1883 // compare the memory we just read with the original opcode1884 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,1885 break_op_size) == 0) {1886 // SUCCESS1887 bp_site->SetEnabled(false);1888 LLDB_LOGF(log,1889 "Process::DisableSoftwareBreakpoint (site_id = %d) "1890 "addr = 0x%" PRIx64 " -- SUCCESS",1891 bp_site->GetID(), (uint64_t)bp_addr);1892 return error;1893 } else {1894 if (break_op_found)1895 error = Status::FromErrorString(1896 "Failed to restore original opcode.");1897 }1898 } else1899 error =1900 Status::FromErrorString("Failed to read memory to verify that "1901 "breakpoint trap was restored.");1902 }1903 } else1904 error = Status::FromErrorString(1905 "Unable to read memory that should contain the breakpoint trap.");1906 }1907 } else {1908 LLDB_LOGF(1909 log,1910 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641911 " -- already disabled",1912 bp_site->GetID(), (uint64_t)bp_addr);1913 return error;1914 }1915 1916 LLDB_LOGF(1917 log,1918 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx641919 " -- FAILED: %s",1920 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());1921 return error;1922}1923 1924// Uncomment to verify memory caching works after making changes to caching1925// code1926//#define VERIFY_MEMORY_READS1927 1928size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {1929 if (ABISP abi_sp = GetABI())1930 addr = abi_sp->FixAnyAddress(addr);1931 1932 error.Clear();1933 if (!GetDisableMemoryCache()) {1934#if defined(VERIFY_MEMORY_READS)1935 // Memory caching is enabled, with debug verification1936 1937 if (buf && size) {1938 // Uncomment the line below to make sure memory caching is working.1939 // I ran this through the test suite and got no assertions, so I am1940 // pretty confident this is working well. If any changes are made to1941 // memory caching, uncomment the line below and test your changes!1942 1943 // Verify all memory reads by using the cache first, then redundantly1944 // reading the same memory from the inferior and comparing to make sure1945 // everything is exactly the same.1946 std::string verify_buf(size, '\0');1947 assert(verify_buf.size() == size);1948 const size_t cache_bytes_read =1949 m_memory_cache.Read(this, addr, buf, size, error);1950 Status verify_error;1951 const size_t verify_bytes_read =1952 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),1953 verify_buf.size(), verify_error);1954 assert(cache_bytes_read == verify_bytes_read);1955 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);1956 assert(verify_error.Success() == error.Success());1957 return cache_bytes_read;1958 }1959 return 0;1960#else // !defined(VERIFY_MEMORY_READS)1961 // Memory caching is enabled, without debug verification1962 1963 return m_memory_cache.Read(addr, buf, size, error);1964#endif // defined (VERIFY_MEMORY_READS)1965 } else {1966 // Memory caching is disabled1967 1968 return ReadMemoryFromInferior(addr, buf, size, error);1969 }1970}1971 1972llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>1973Process::ReadMemoryRanges(llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,1974 llvm::MutableArrayRef<uint8_t> buffer) {1975 auto total_ranges_len = llvm::sum_of(1976 llvm::map_range(ranges, [](auto range) { return range.size; }));1977 // If the buffer is not large enough, this is a programmer error.1978 // In production builds, gracefully fail by returning a length of 0 for all1979 // ranges.1980 assert(buffer.size() >= total_ranges_len && "provided buffer is too short");1981 if (buffer.size() < total_ranges_len) {1982 llvm::MutableArrayRef<uint8_t> empty;1983 return {ranges.size(), empty};1984 }1985 1986 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;1987 1988 // While `buffer` has space, take the next requested range and read1989 // memory into a `buffer` piece, then slice it to remove the used memory.1990 for (auto [addr, range_len] : ranges) {1991 Status status;1992 size_t num_bytes_read =1993 ReadMemoryFromInferior(addr, buffer.data(), range_len, status);1994 // FIXME: ReadMemoryFromInferior promises to return 0 in case of errors, but1995 // it doesn't; it never checks for errors.1996 if (status.Fail())1997 num_bytes_read = 0;1998 1999 assert(num_bytes_read <= range_len && "read more than requested bytes");2000 if (num_bytes_read > range_len) {2001 // In production builds, gracefully fail by returning length zero for this2002 // range.2003 results.emplace_back();2004 continue;2005 }2006 2007 results.push_back(buffer.take_front(num_bytes_read));2008 // Slice buffer to remove the used memory.2009 buffer = buffer.drop_front(num_bytes_read);2010 }2011 2012 return results;2013}2014 2015void Process::DoFindInMemory(lldb::addr_t start_addr, lldb::addr_t end_addr,2016 const uint8_t *buf, size_t size,2017 AddressRanges &matches, size_t alignment,2018 size_t max_matches) {2019 // Inputs are already validated in FindInMemory() functions.2020 assert(buf != nullptr);2021 assert(size > 0);2022 assert(alignment > 0);2023 assert(max_matches > 0);2024 assert(start_addr != LLDB_INVALID_ADDRESS);2025 assert(end_addr != LLDB_INVALID_ADDRESS);2026 assert(start_addr < end_addr);2027 2028 lldb::addr_t start = llvm::alignTo(start_addr, alignment);2029 while (matches.size() < max_matches && (start + size) < end_addr) {2030 const lldb::addr_t found_addr = FindInMemory(start, end_addr, buf, size);2031 if (found_addr == LLDB_INVALID_ADDRESS)2032 break;2033 2034 if (found_addr % alignment) {2035 // We need to check the alignment because the FindInMemory uses a special2036 // algorithm to efficiently search mememory but doesn't support alignment.2037 start = llvm::alignTo(start + 1, alignment);2038 continue;2039 }2040 2041 matches.emplace_back(found_addr, size);2042 start = found_addr + alignment;2043 }2044}2045 2046AddressRanges Process::FindRangesInMemory(const uint8_t *buf, uint64_t size,2047 const AddressRanges &ranges,2048 size_t alignment, size_t max_matches,2049 Status &error) {2050 AddressRanges matches;2051 if (buf == nullptr) {2052 error = Status::FromErrorString("buffer is null");2053 return matches;2054 }2055 if (size == 0) {2056 error = Status::FromErrorString("buffer size is zero");2057 return matches;2058 }2059 if (ranges.empty()) {2060 error = Status::FromErrorString("empty ranges");2061 return matches;2062 }2063 if (alignment == 0) {2064 error = Status::FromErrorString("alignment must be greater than zero");2065 return matches;2066 }2067 if (max_matches == 0) {2068 error = Status::FromErrorString("max_matches must be greater than zero");2069 return matches;2070 }2071 2072 int resolved_ranges = 0;2073 Target &target = GetTarget();2074 for (size_t i = 0; i < ranges.size(); ++i) {2075 if (matches.size() >= max_matches)2076 break;2077 const AddressRange &range = ranges[i];2078 if (range.IsValid() == false)2079 continue;2080 2081 const lldb::addr_t start_addr =2082 range.GetBaseAddress().GetLoadAddress(&target);2083 if (start_addr == LLDB_INVALID_ADDRESS)2084 continue;2085 2086 ++resolved_ranges;2087 const lldb::addr_t end_addr = start_addr + range.GetByteSize();2088 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment,2089 max_matches);2090 }2091 2092 if (resolved_ranges > 0)2093 error.Clear();2094 else2095 error = Status::FromErrorString("unable to resolve any ranges");2096 2097 return matches;2098}2099 2100lldb::addr_t Process::FindInMemory(const uint8_t *buf, uint64_t size,2101 const AddressRange &range, size_t alignment,2102 Status &error) {2103 if (buf == nullptr) {2104 error = Status::FromErrorString("buffer is null");2105 return LLDB_INVALID_ADDRESS;2106 }2107 if (size == 0) {2108 error = Status::FromErrorString("buffer size is zero");2109 return LLDB_INVALID_ADDRESS;2110 }2111 if (!range.IsValid()) {2112 error = Status::FromErrorString("range is invalid");2113 return LLDB_INVALID_ADDRESS;2114 }2115 if (alignment == 0) {2116 error = Status::FromErrorString("alignment must be greater than zero");2117 return LLDB_INVALID_ADDRESS;2118 }2119 2120 Target &target = GetTarget();2121 const lldb::addr_t start_addr =2122 range.GetBaseAddress().GetLoadAddress(&target);2123 if (start_addr == LLDB_INVALID_ADDRESS) {2124 error = Status::FromErrorString("range load address is invalid");2125 return LLDB_INVALID_ADDRESS;2126 }2127 const lldb::addr_t end_addr = start_addr + range.GetByteSize();2128 2129 AddressRanges matches;2130 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment, 1);2131 if (matches.empty())2132 return LLDB_INVALID_ADDRESS;2133 2134 error.Clear();2135 return matches[0].GetBaseAddress().GetLoadAddress(&target);2136}2137 2138size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,2139 Status &error) {2140 char buf[256];2141 out_str.clear();2142 addr_t curr_addr = addr;2143 while (true) {2144 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);2145 if (length == 0)2146 break;2147 out_str.append(buf, length);2148 // If we got "length - 1" bytes, we didn't get the whole C string, we need2149 // to read some more characters2150 if (length == sizeof(buf) - 1)2151 curr_addr += length;2152 else2153 break;2154 }2155 return out_str.size();2156}2157 2158// Deprecated in favor of ReadStringFromMemory which has wchar support and2159// correct code to find null terminators.2160size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,2161 size_t dst_max_len,2162 Status &result_error) {2163 size_t total_cstr_len = 0;2164 if (dst && dst_max_len) {2165 result_error.Clear();2166 // NULL out everything just to be safe2167 memset(dst, 0, dst_max_len);2168 addr_t curr_addr = addr;2169 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();2170 size_t bytes_left = dst_max_len - 1;2171 char *curr_dst = dst;2172 2173 while (bytes_left > 0) {2174 addr_t cache_line_bytes_left =2175 cache_line_size - (curr_addr % cache_line_size);2176 addr_t bytes_to_read =2177 std::min<addr_t>(bytes_left, cache_line_bytes_left);2178 Status error;2179 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);2180 2181 if (bytes_read == 0) {2182 result_error = std::move(error);2183 dst[total_cstr_len] = '\0';2184 break;2185 }2186 const size_t len = strlen(curr_dst);2187 2188 total_cstr_len += len;2189 2190 if (len < bytes_to_read)2191 break;2192 2193 curr_dst += bytes_read;2194 curr_addr += bytes_read;2195 bytes_left -= bytes_read;2196 }2197 } else {2198 if (dst == nullptr)2199 result_error = Status::FromErrorString("invalid arguments");2200 else2201 result_error.Clear();2202 }2203 return total_cstr_len;2204}2205 2206size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,2207 Status &error) {2208 LLDB_SCOPED_TIMER();2209 2210 if (ABISP abi_sp = GetABI())2211 addr = abi_sp->FixAnyAddress(addr);2212 2213 if (buf == nullptr || size == 0)2214 return 0;2215 2216 size_t bytes_read = 0;2217 uint8_t *bytes = (uint8_t *)buf;2218 2219 while (bytes_read < size) {2220 const size_t curr_size = size - bytes_read;2221 const size_t curr_bytes_read =2222 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);2223 bytes_read += curr_bytes_read;2224 if (curr_bytes_read == curr_size || curr_bytes_read == 0)2225 break;2226 }2227 2228 // Replace any software breakpoint opcodes that fall into this range back2229 // into "buf" before we return2230 if (bytes_read > 0)2231 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);2232 return bytes_read;2233}2234 2235lldb::offset_t Process::ReadMemoryInChunks(lldb::addr_t vm_addr, void *buf,2236 lldb::addr_t chunk_size,2237 lldb::offset_t size,2238 ReadMemoryChunkCallback callback) {2239 // Safety check to prevent an infinite loop.2240 if (chunk_size == 0)2241 return 0;2242 2243 // Buffer for when a NULL buf is provided, initialized2244 // to 0 bytes, we set it to chunk_size and then replace buf2245 // with the new buffer.2246 DataBufferHeap data_buffer;2247 if (!buf) {2248 data_buffer.SetByteSize(chunk_size);2249 buf = data_buffer.GetBytes();2250 }2251 2252 uint64_t bytes_remaining = size;2253 uint64_t bytes_read = 0;2254 Status error;2255 while (bytes_remaining > 0) {2256 // Get the next read chunk size as the minimum of the remaining bytes and2257 // the write chunk max size.2258 const lldb::addr_t bytes_to_read = std::min(bytes_remaining, chunk_size);2259 const lldb::addr_t current_addr = vm_addr + bytes_read;2260 const lldb::addr_t bytes_read_for_chunk =2261 ReadMemoryFromInferior(current_addr, buf, bytes_to_read, error);2262 2263 bytes_read += bytes_read_for_chunk;2264 // If the bytes read in this chunk would cause us to overflow, something2265 // went wrong and we should fail fast.2266 if (bytes_read_for_chunk > bytes_remaining)2267 return 0;2268 else2269 bytes_remaining -= bytes_read_for_chunk;2270 2271 if (callback(error, current_addr, buf, bytes_read_for_chunk) ==2272 IterationAction::Stop)2273 break;2274 }2275 2276 return bytes_read;2277}2278 2279uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,2280 size_t integer_byte_size,2281 uint64_t fail_value,2282 Status &error) {2283 Scalar scalar;2284 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,2285 error))2286 return scalar.ULongLong(fail_value);2287 return fail_value;2288}2289 2290int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,2291 size_t integer_byte_size,2292 int64_t fail_value,2293 Status &error) {2294 Scalar scalar;2295 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,2296 error))2297 return scalar.SLongLong(fail_value);2298 return fail_value;2299}2300 2301addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {2302 Scalar scalar;2303 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,2304 error))2305 return scalar.ULongLong(LLDB_INVALID_ADDRESS);2306 return LLDB_INVALID_ADDRESS;2307}2308 2309bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,2310 Status &error) {2311 Scalar scalar;2312 const uint32_t addr_byte_size = GetAddressByteSize();2313 if (addr_byte_size <= 4)2314 scalar = (uint32_t)ptr_value;2315 else2316 scalar = ptr_value;2317 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==2318 addr_byte_size;2319}2320 2321size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,2322 Status &error) {2323 size_t bytes_written = 0;2324 const uint8_t *bytes = (const uint8_t *)buf;2325 2326 while (bytes_written < size) {2327 const size_t curr_size = size - bytes_written;2328 const size_t curr_bytes_written = DoWriteMemory(2329 addr + bytes_written, bytes + bytes_written, curr_size, error);2330 bytes_written += curr_bytes_written;2331 if (curr_bytes_written == curr_size || curr_bytes_written == 0)2332 break;2333 }2334 return bytes_written;2335}2336 2337size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,2338 Status &error) {2339 if (ABISP abi_sp = GetABI())2340 addr = abi_sp->FixAnyAddress(addr);2341 2342 m_memory_cache.Flush(addr, size);2343 2344 if (buf == nullptr || size == 0)2345 return 0;2346 2347 if (TrackMemoryCacheChanges() || !m_allocated_memory_cache.IsInCache(addr))2348 m_mod_id.BumpMemoryID();2349 2350 // We need to write any data that would go where any current software traps2351 // (enabled software breakpoints) any software traps (breakpoints) that we2352 // may have placed in our tasks memory.2353 2354 StopPointSiteList<BreakpointSite> bp_sites_in_range;2355 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))2356 return WriteMemoryPrivate(addr, buf, size, error);2357 2358 // No breakpoint sites overlap2359 if (bp_sites_in_range.IsEmpty())2360 return WriteMemoryPrivate(addr, buf, size, error);2361 2362 const uint8_t *ubuf = (const uint8_t *)buf;2363 uint64_t bytes_written = 0;2364 2365 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,2366 &error](BreakpointSite *bp) -> void {2367 if (error.Fail())2368 return;2369 2370 if (bp->GetType() != BreakpointSite::eSoftware)2371 return;2372 2373 addr_t intersect_addr;2374 size_t intersect_size;2375 size_t opcode_offset;2376 const bool intersects = bp->IntersectsRange(2377 addr, size, &intersect_addr, &intersect_size, &opcode_offset);2378 UNUSED_IF_ASSERT_DISABLED(intersects);2379 assert(intersects);2380 assert(addr <= intersect_addr && intersect_addr < addr + size);2381 assert(addr < intersect_addr + intersect_size &&2382 intersect_addr + intersect_size <= addr + size);2383 assert(opcode_offset + intersect_size <= bp->GetByteSize());2384 2385 // Check for bytes before this breakpoint2386 const addr_t curr_addr = addr + bytes_written;2387 if (intersect_addr > curr_addr) {2388 // There are some bytes before this breakpoint that we need to just2389 // write to memory2390 size_t curr_size = intersect_addr - curr_addr;2391 size_t curr_bytes_written =2392 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);2393 bytes_written += curr_bytes_written;2394 if (curr_bytes_written != curr_size) {2395 // We weren't able to write all of the requested bytes, we are2396 // done looping and will return the number of bytes that we have2397 // written so far.2398 if (error.Success())2399 error = Status::FromErrorString("could not write all bytes");2400 }2401 }2402 // Now write any bytes that would cover up any software breakpoints2403 // directly into the breakpoint opcode buffer2404 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,2405 intersect_size);2406 bytes_written += intersect_size;2407 });2408 2409 // Write any remaining bytes after the last breakpoint if we have any left2410 if (bytes_written < size)2411 bytes_written +=2412 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,2413 size - bytes_written, error);2414 2415 return bytes_written;2416}2417 2418size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,2419 size_t byte_size, Status &error) {2420 if (byte_size == UINT32_MAX)2421 byte_size = scalar.GetByteSize();2422 if (byte_size > 0) {2423 uint8_t buf[32];2424 const size_t mem_size =2425 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);2426 if (mem_size > 0)2427 return WriteMemory(addr, buf, mem_size, error);2428 else2429 error = Status::FromErrorString("failed to get scalar as memory data");2430 } else {2431 error = Status::FromErrorString("invalid scalar value");2432 }2433 return 0;2434}2435 2436size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,2437 bool is_signed, Scalar &scalar,2438 Status &error) {2439 uint64_t uval = 0;2440 if (byte_size == 0) {2441 error = Status::FromErrorString("byte size is zero");2442 } else if (byte_size & (byte_size - 1)) {2443 error = Status::FromErrorStringWithFormat(2444 "byte size %u is not a power of 2", byte_size);2445 } else if (byte_size <= sizeof(uval)) {2446 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);2447 if (bytes_read == byte_size) {2448 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),2449 GetAddressByteSize());2450 lldb::offset_t offset = 0;2451 if (byte_size <= 4)2452 scalar = data.GetMaxU32(&offset, byte_size);2453 else2454 scalar = data.GetMaxU64(&offset, byte_size);2455 if (is_signed) {2456 scalar.MakeSigned();2457 scalar.SignExtend(byte_size * 8);2458 }2459 return bytes_read;2460 }2461 } else {2462 error = Status::FromErrorStringWithFormat(2463 "byte size of %u is too large for integer scalar type", byte_size);2464 }2465 return 0;2466}2467 2468Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {2469 Status error;2470 for (const auto &Entry : entries) {2471 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),2472 error);2473 if (!error.Success())2474 break;2475 }2476 return error;2477}2478 2479addr_t Process::AllocateMemory(size_t size, uint32_t permissions,2480 Status &error) {2481 if (GetPrivateState() != eStateStopped) {2482 error = Status::FromErrorString(2483 "cannot allocate memory while process is running");2484 return LLDB_INVALID_ADDRESS;2485 }2486 2487 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);2488}2489 2490addr_t Process::CallocateMemory(size_t size, uint32_t permissions,2491 Status &error) {2492 addr_t return_addr = AllocateMemory(size, permissions, error);2493 if (error.Success()) {2494 std::string buffer(size, 0);2495 WriteMemory(return_addr, buffer.c_str(), size, error);2496 }2497 return return_addr;2498}2499 2500bool Process::CanJIT() {2501 if (m_can_jit == eCanJITDontKnow) {2502 Log *log = GetLog(LLDBLog::Process);2503 Status err;2504 2505 uint64_t allocated_memory = AllocateMemory(2506 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,2507 err);2508 2509 if (err.Success()) {2510 m_can_jit = eCanJITYes;2511 LLDB_LOGF(log,2512 "Process::%s pid %" PRIu642513 " allocation test passed, CanJIT () is true",2514 __FUNCTION__, GetID());2515 } else {2516 m_can_jit = eCanJITNo;2517 LLDB_LOGF(log,2518 "Process::%s pid %" PRIu642519 " allocation test failed, CanJIT () is false: %s",2520 __FUNCTION__, GetID(), err.AsCString());2521 }2522 2523 DeallocateMemory(allocated_memory);2524 }2525 2526 return m_can_jit == eCanJITYes;2527}2528 2529void Process::SetCanJIT(bool can_jit) {2530 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);2531}2532 2533void Process::SetCanRunCode(bool can_run_code) {2534 SetCanJIT(can_run_code);2535 m_can_interpret_function_calls = can_run_code;2536}2537 2538Status Process::DeallocateMemory(addr_t ptr) {2539 Status error;2540 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {2541 error = Status::FromErrorStringWithFormat(2542 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);2543 }2544 return error;2545}2546 2547bool Process::GetWatchpointReportedAfter() {2548 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())2549 return *subclass_override;2550 2551 bool reported_after = true;2552 const ArchSpec &arch = GetTarget().GetArchitecture();2553 if (!arch.IsValid())2554 return reported_after;2555 llvm::Triple triple = arch.GetTriple();2556 2557 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||2558 triple.isAArch64() || triple.isArmMClass() || triple.isARM() ||2559 triple.isLoongArch())2560 reported_after = false;2561 2562 return reported_after;2563}2564 2565ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,2566 lldb::addr_t header_addr,2567 size_t size_to_read) {2568 Log *log = GetLog(LLDBLog::Host);2569 if (log) {2570 LLDB_LOGF(log,2571 "Process::ReadModuleFromMemory reading %s binary from memory",2572 file_spec.GetPath().c_str());2573 }2574 ModuleSP module_sp(new Module(file_spec, ArchSpec()));2575 if (module_sp) {2576 Status error;2577 std::unique_ptr<Progress> progress_up;2578 // Reading an ObjectFile from a local corefile is very fast,2579 // only print a progress update if we're reading from a2580 // live session which might go over gdb remote serial protocol.2581 if (IsLiveDebugSession())2582 progress_up = std::make_unique<Progress>(2583 "Reading binary from memory", file_spec.GetFilename().GetString());2584 2585 ObjectFile *objfile = module_sp->GetMemoryObjectFile(2586 shared_from_this(), header_addr, error, size_to_read);2587 if (objfile)2588 return module_sp;2589 }2590 return ModuleSP();2591}2592 2593bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,2594 uint32_t &permissions) {2595 MemoryRegionInfo range_info;2596 permissions = 0;2597 Status error(GetMemoryRegionInfo(load_addr, range_info));2598 if (!error.Success())2599 return false;2600 if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||2601 range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||2602 range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {2603 return false;2604 }2605 permissions = range_info.GetLLDBPermissions();2606 return true;2607}2608 2609Status Process::EnableWatchpoint(WatchpointSP wp_sp, bool notify) {2610 Status error;2611 error = Status::FromErrorString("watchpoints are not supported");2612 return error;2613}2614 2615Status Process::DisableWatchpoint(WatchpointSP wp_sp, bool notify) {2616 Status error;2617 error = Status::FromErrorString("watchpoints are not supported");2618 return error;2619}2620 2621StateType2622Process::WaitForProcessStopPrivate(EventSP &event_sp,2623 const Timeout<std::micro> &timeout) {2624 StateType state;2625 2626 while (true) {2627 event_sp.reset();2628 state = GetStateChangedEventsPrivate(event_sp, timeout);2629 2630 if (StateIsStoppedState(state, false))2631 break;2632 2633 // If state is invalid, then we timed out2634 if (state == eStateInvalid)2635 break;2636 2637 if (event_sp)2638 HandlePrivateEvent(event_sp);2639 }2640 return state;2641}2642 2643void Process::LoadOperatingSystemPlugin(bool flush) {2644 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);2645 if (flush)2646 m_thread_list.Clear();2647 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));2648 if (flush)2649 Flush();2650}2651 2652Status Process::Launch(ProcessLaunchInfo &launch_info) {2653 StateType state_after_launch = eStateInvalid;2654 EventSP first_stop_event_sp;2655 Status status =2656 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);2657 if (status.Fail())2658 return status;2659 2660 if (state_after_launch != eStateStopped &&2661 state_after_launch != eStateCrashed)2662 return Status();2663 2664 // Note, the stop event was consumed above, but not handled. This2665 // was done to give DidLaunch a chance to run. The target is either2666 // stopped or crashed. Directly set the state. This is done to2667 // prevent a stop message with a bunch of spurious output on thread2668 // status, as well as not pop a ProcessIOHandler.2669 SetPublicState(state_after_launch, false);2670 2671 if (PrivateStateThreadIsValid())2672 ResumePrivateStateThread();2673 else2674 StartPrivateStateThread();2675 2676 // Target was stopped at entry as was intended. Need to notify the2677 // listeners about it.2678 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))2679 HandlePrivateEvent(first_stop_event_sp);2680 2681 return Status();2682}2683 2684Status Process::LaunchPrivate(ProcessLaunchInfo &launch_info, StateType &state,2685 EventSP &event_sp) {2686 Status error;2687 m_abi_sp.reset();2688 m_dyld_up.reset();2689 m_jit_loaders_up.reset();2690 m_system_runtime_up.reset();2691 m_os_up.reset();2692 GetTarget().ClearAllLoadedSections();2693 2694 {2695 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);2696 m_process_input_reader.reset();2697 }2698 2699 Module *exe_module = GetTarget().GetExecutableModulePointer();2700 2701 // The "remote executable path" is hooked up to the local Executable2702 // module. But we should be able to debug a remote process even if the2703 // executable module only exists on the remote. However, there needs to2704 // be a way to express this path, without actually having a module.2705 // The way to do that is to set the ExecutableFile in the LaunchInfo.2706 // Figure that out here:2707 2708 FileSpec exe_spec_to_use;2709 if (!exe_module) {2710 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {2711 error = Status::FromErrorString("executable module does not exist");2712 return error;2713 }2714 exe_spec_to_use = launch_info.GetExecutableFile();2715 } else2716 exe_spec_to_use = exe_module->GetFileSpec();2717 2718 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {2719 // Install anything that might need to be installed prior to launching.2720 // For host systems, this will do nothing, but if we are connected to a2721 // remote platform it will install any needed binaries2722 error = GetTarget().Install(&launch_info);2723 if (error.Fail())2724 return error;2725 }2726 2727 // Listen and queue events that are broadcasted during the process launch.2728 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));2729 HijackProcessEvents(listener_sp);2730 auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });2731 2732 if (PrivateStateThreadIsValid())2733 PausePrivateStateThread();2734 2735 error = WillLaunch(exe_module);2736 if (error.Fail()) {2737 std::string local_exec_file_path = exe_spec_to_use.GetPath();2738 return Status::FromErrorStringWithFormat("file doesn't exist: '%s'",2739 local_exec_file_path.c_str());2740 }2741 2742 const bool restarted = false;2743 SetPublicState(eStateLaunching, restarted);2744 m_should_detach = false;2745 2746 m_public_run_lock.SetRunning();2747 error = DoLaunch(exe_module, launch_info);2748 2749 if (error.Fail()) {2750 if (GetID() != LLDB_INVALID_PROCESS_ID) {2751 SetID(LLDB_INVALID_PROCESS_ID);2752 const char *error_string = error.AsCString();2753 if (error_string == nullptr)2754 error_string = "launch failed";2755 SetExitStatus(-1, error_string);2756 }2757 return error;2758 }2759 2760 // Now wait for the process to launch and return control to us, and then2761 // call DidLaunch:2762 state = WaitForProcessStopPrivate(event_sp, seconds(10));2763 2764 if (state == eStateInvalid || !event_sp) {2765 // We were able to launch the process, but we failed to catch the2766 // initial stop.2767 error = Status::FromErrorString("failed to catch stop after launch");2768 SetExitStatus(0, error.AsCString());2769 Destroy(false);2770 return error;2771 }2772 2773 if (state == eStateExited) {2774 // We exited while trying to launch somehow. Don't call DidLaunch2775 // as that's not likely to work, and return an invalid pid.2776 HandlePrivateEvent(event_sp);2777 return Status();2778 }2779 2780 if (state == eStateStopped || state == eStateCrashed) {2781 DidLaunch();2782 2783 // Now that we know the process type, update its signal responses from the2784 // ones stored in the Target:2785 if (m_unix_signals_sp)2786 GetTarget().UpdateSignalsFromDummy(2787 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());2788 2789 DynamicLoader *dyld = GetDynamicLoader();2790 if (dyld)2791 dyld->DidLaunch();2792 2793 GetJITLoaders().DidLaunch();2794 2795 SystemRuntime *system_runtime = GetSystemRuntime();2796 if (system_runtime)2797 system_runtime->DidLaunch();2798 2799 if (!m_os_up)2800 LoadOperatingSystemPlugin(false);2801 2802 // We successfully launched the process and stopped, now it the2803 // right time to set up signal filters before resuming.2804 UpdateAutomaticSignalFiltering();2805 return Status();2806 }2807 2808 return Status::FromErrorStringWithFormat(2809 "Unexpected process state after the launch: %s, expected %s, "2810 "%s, %s or %s",2811 StateAsCString(state), StateAsCString(eStateInvalid),2812 StateAsCString(eStateExited), StateAsCString(eStateStopped),2813 StateAsCString(eStateCrashed));2814}2815 2816Status Process::LoadCore() {2817 GetTarget().ClearAllLoadedSections();2818 Status error = DoLoadCore();2819 if (error.Success()) {2820 ListenerSP listener_sp(2821 Listener::MakeListener("lldb.process.load_core_listener"));2822 HijackProcessEvents(listener_sp);2823 2824 if (PrivateStateThreadIsValid())2825 ResumePrivateStateThread();2826 else2827 StartPrivateStateThread();2828 2829 DynamicLoader *dyld = GetDynamicLoader();2830 if (dyld)2831 dyld->DidAttach();2832 2833 GetJITLoaders().DidAttach();2834 2835 SystemRuntime *system_runtime = GetSystemRuntime();2836 if (system_runtime)2837 system_runtime->DidAttach();2838 2839 if (!m_os_up)2840 LoadOperatingSystemPlugin(false);2841 2842 // We successfully loaded a core file, now pretend we stopped so we can2843 // show all of the threads in the core file and explore the crashed state.2844 SetPrivateState(eStateStopped);2845 2846 // Wait for a stopped event since we just posted one above...2847 lldb::EventSP event_sp;2848 StateType state =2849 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,2850 nullptr, true, SelectMostRelevantFrame);2851 2852 if (!StateIsStoppedState(state, false)) {2853 Log *log = GetLog(LLDBLog::Process);2854 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",2855 StateAsCString(state));2856 error = Status::FromErrorString(2857 "Did not get stopped event after loading the core file.");2858 }2859 RestoreProcessEvents();2860 // Since we hijacked the event stream, we will have we won't have run the2861 // stop hooks. Make sure we do that here:2862 GetTarget().RunStopHooks(/* at_initial_stop= */ true);2863 }2864 return error;2865}2866 2867DynamicLoader *Process::GetDynamicLoader() {2868 if (!m_dyld_up)2869 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));2870 return m_dyld_up.get();2871}2872 2873void Process::SetDynamicLoader(DynamicLoaderUP dyld_up) {2874 m_dyld_up = std::move(dyld_up);2875}2876 2877DataExtractor Process::GetAuxvData() { return DataExtractor(); }2878 2879llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {2880 return false;2881}2882 2883JITLoaderList &Process::GetJITLoaders() {2884 if (!m_jit_loaders_up) {2885 m_jit_loaders_up = std::make_unique<JITLoaderList>();2886 JITLoader::LoadPlugins(this, *m_jit_loaders_up);2887 }2888 return *m_jit_loaders_up;2889}2890 2891SystemRuntime *Process::GetSystemRuntime() {2892 if (!m_system_runtime_up)2893 m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));2894 return m_system_runtime_up.get();2895}2896 2897Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,2898 uint32_t exec_count)2899 : NextEventAction(process), m_exec_count(exec_count) {2900 Log *log = GetLog(LLDBLog::Process);2901 LLDB_LOGF(2902 log,2903 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,2904 __FUNCTION__, static_cast<void *>(process), exec_count);2905}2906 2907Process::NextEventAction::EventActionResult2908Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {2909 Log *log = GetLog(LLDBLog::Process);2910 2911 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());2912 LLDB_LOGF(log,2913 "Process::AttachCompletionHandler::%s called with state %s (%d)",2914 __FUNCTION__, StateAsCString(state), static_cast<int>(state));2915 2916 switch (state) {2917 case eStateAttaching:2918 return eEventActionSuccess;2919 2920 case eStateRunning:2921 case eStateConnected:2922 return eEventActionRetry;2923 2924 case eStateStopped:2925 case eStateCrashed:2926 // During attach, prior to sending the eStateStopped event,2927 // lldb_private::Process subclasses must set the new process ID.2928 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);2929 // We don't want these events to be reported, so go set the2930 // ShouldReportStop here:2931 m_process->GetThreadList().SetShouldReportStop(eVoteNo);2932 2933 if (m_exec_count > 0) {2934 --m_exec_count;2935 2936 LLDB_LOGF(log,2937 "Process::AttachCompletionHandler::%s state %s: reduced "2938 "remaining exec count to %" PRIu32 ", requesting resume",2939 __FUNCTION__, StateAsCString(state), m_exec_count);2940 2941 RequestResume();2942 return eEventActionRetry;2943 } else {2944 LLDB_LOGF(log,2945 "Process::AttachCompletionHandler::%s state %s: no more "2946 "execs expected to start, continuing with attach",2947 __FUNCTION__, StateAsCString(state));2948 2949 m_process->CompleteAttach();2950 return eEventActionSuccess;2951 }2952 break;2953 2954 default:2955 case eStateExited:2956 case eStateInvalid:2957 break;2958 }2959 2960 m_exit_string.assign("No valid Process");2961 return eEventActionExit;2962}2963 2964Process::NextEventAction::EventActionResult2965Process::AttachCompletionHandler::HandleBeingInterrupted() {2966 return eEventActionSuccess;2967}2968 2969const char *Process::AttachCompletionHandler::GetExitString() {2970 return m_exit_string.c_str();2971}2972 2973ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {2974 if (m_listener_sp)2975 return m_listener_sp;2976 else2977 return debugger.GetListener();2978}2979 2980Status Process::WillLaunch(Module *module) {2981 return DoWillLaunch(module);2982}2983 2984Status Process::WillAttachToProcessWithID(lldb::pid_t pid) {2985 return DoWillAttachToProcessWithID(pid);2986}2987 2988Status Process::WillAttachToProcessWithName(const char *process_name,2989 bool wait_for_launch) {2990 return DoWillAttachToProcessWithName(process_name, wait_for_launch);2991}2992 2993Status Process::Attach(ProcessAttachInfo &attach_info) {2994 m_abi_sp.reset();2995 {2996 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);2997 m_process_input_reader.reset();2998 }2999 m_dyld_up.reset();3000 m_jit_loaders_up.reset();3001 m_system_runtime_up.reset();3002 m_os_up.reset();3003 GetTarget().ClearAllLoadedSections();3004 3005 lldb::pid_t attach_pid = attach_info.GetProcessID();3006 Status error;3007 if (attach_pid == LLDB_INVALID_PROCESS_ID) {3008 char process_name[PATH_MAX];3009 3010 if (attach_info.GetExecutableFile().GetPath(process_name,3011 sizeof(process_name))) {3012 const bool wait_for_launch = attach_info.GetWaitForLaunch();3013 3014 if (wait_for_launch) {3015 error = WillAttachToProcessWithName(process_name, wait_for_launch);3016 if (error.Success()) {3017 m_public_run_lock.SetRunning();3018 m_should_detach = true;3019 const bool restarted = false;3020 SetPublicState(eStateAttaching, restarted);3021 // Now attach using these arguments.3022 error = DoAttachToProcessWithName(process_name, attach_info);3023 3024 if (error.Fail()) {3025 if (GetID() != LLDB_INVALID_PROCESS_ID) {3026 SetID(LLDB_INVALID_PROCESS_ID);3027 if (error.AsCString() == nullptr)3028 error = Status::FromErrorString("attach failed");3029 3030 SetExitStatus(-1, error.AsCString());3031 }3032 } else {3033 SetNextEventAction(new Process::AttachCompletionHandler(3034 this, attach_info.GetResumeCount()));3035 StartPrivateStateThread();3036 }3037 return error;3038 }3039 } else {3040 ProcessInstanceInfoList process_infos;3041 PlatformSP platform_sp(GetTarget().GetPlatform());3042 3043 if (platform_sp) {3044 ProcessInstanceInfoMatch match_info;3045 match_info.GetProcessInfo() = attach_info;3046 match_info.SetNameMatchType(NameMatch::Equals);3047 platform_sp->FindProcesses(match_info, process_infos);3048 const uint32_t num_matches = process_infos.size();3049 if (num_matches == 1) {3050 attach_pid = process_infos[0].GetProcessID();3051 // Fall through and attach using the above process ID3052 } else {3053 match_info.GetProcessInfo().GetExecutableFile().GetPath(3054 process_name, sizeof(process_name));3055 if (num_matches > 1) {3056 StreamString s;3057 ProcessInstanceInfo::DumpTableHeader(s, true, false);3058 for (size_t i = 0; i < num_matches; i++) {3059 process_infos[i].DumpAsTableRow(3060 s, platform_sp->GetUserIDResolver(), true, false);3061 }3062 error = Status::FromErrorStringWithFormat(3063 "more than one process named %s:\n%s", process_name,3064 s.GetData());3065 } else3066 error = Status::FromErrorStringWithFormat(3067 "could not find a process named %s", process_name);3068 }3069 } else {3070 error = Status::FromErrorString(3071 "invalid platform, can't find processes by name");3072 return error;3073 }3074 }3075 } else {3076 error = Status::FromErrorString("invalid process name");3077 }3078 }3079 3080 if (attach_pid != LLDB_INVALID_PROCESS_ID) {3081 error = WillAttachToProcessWithID(attach_pid);3082 if (error.Success()) {3083 m_public_run_lock.SetRunning();3084 3085 // Now attach using these arguments.3086 m_should_detach = true;3087 const bool restarted = false;3088 SetPublicState(eStateAttaching, restarted);3089 error = DoAttachToProcessWithID(attach_pid, attach_info);3090 3091 if (error.Success()) {3092 SetNextEventAction(new Process::AttachCompletionHandler(3093 this, attach_info.GetResumeCount()));3094 StartPrivateStateThread();3095 } else {3096 if (GetID() != LLDB_INVALID_PROCESS_ID)3097 SetID(LLDB_INVALID_PROCESS_ID);3098 3099 const char *error_string = error.AsCString();3100 if (error_string == nullptr)3101 error_string = "attach failed";3102 3103 SetExitStatus(-1, error_string);3104 }3105 }3106 }3107 return error;3108}3109 3110void Process::CompleteAttach() {3111 Log *log(GetLog(LLDBLog::Process | LLDBLog::Target));3112 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);3113 3114 // Let the process subclass figure out at much as it can about the process3115 // before we go looking for a dynamic loader plug-in.3116 ArchSpec process_arch;3117 DidAttach(process_arch);3118 3119 if (process_arch.IsValid()) {3120 LLDB_LOG(log,3121 "Process::{0} replacing process architecture with DidAttach() "3122 "architecture: \"{1}\"",3123 __FUNCTION__, process_arch.GetTriple().getTriple());3124 GetTarget().SetArchitecture(process_arch);3125 }3126 3127 // We just attached. If we have a platform, ask it for the process3128 // architecture, and if it isn't the same as the one we've already set,3129 // switch architectures.3130 PlatformSP platform_sp(GetTarget().GetPlatform());3131 assert(platform_sp);3132 ArchSpec process_host_arch = GetSystemArchitecture();3133 if (platform_sp) {3134 const ArchSpec &target_arch = GetTarget().GetArchitecture();3135 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(3136 target_arch, process_host_arch,3137 ArchSpec::CompatibleMatch, nullptr)) {3138 ArchSpec platform_arch;3139 platform_sp = GetTarget().GetDebugger().GetPlatformList().GetOrCreate(3140 target_arch, process_host_arch, &platform_arch);3141 if (platform_sp) {3142 GetTarget().SetPlatform(platform_sp);3143 GetTarget().SetArchitecture(platform_arch);3144 LLDB_LOG(log,3145 "switching platform to {0} and architecture to {1} based on "3146 "info from attach",3147 platform_sp->GetName(), platform_arch.GetTriple().getTriple());3148 }3149 } else if (!process_arch.IsValid()) {3150 ProcessInstanceInfo process_info;3151 GetProcessInfo(process_info);3152 const ArchSpec &process_arch = process_info.GetArchitecture();3153 const ArchSpec &target_arch = GetTarget().GetArchitecture();3154 if (process_arch.IsValid() &&3155 target_arch.IsCompatibleMatch(process_arch) &&3156 !target_arch.IsExactMatch(process_arch)) {3157 GetTarget().SetArchitecture(process_arch);3158 LLDB_LOGF(log,3159 "Process::%s switching architecture to %s based on info "3160 "the platform retrieved for pid %" PRIu64,3161 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),3162 GetID());3163 }3164 }3165 }3166 // Now that we know the process type, update its signal responses from the3167 // ones stored in the Target:3168 if (m_unix_signals_sp)3169 GetTarget().UpdateSignalsFromDummy(3170 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());3171 3172 // We have completed the attach, now it is time to find the dynamic loader3173 // plug-in3174 DynamicLoader *dyld = GetDynamicLoader();3175 if (dyld) {3176 dyld->DidAttach();3177 if (log) {3178 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3179 LLDB_LOG(log,3180 "after DynamicLoader::DidAttach(), target "3181 "executable is {0} (using {1} plugin)",3182 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),3183 dyld->GetPluginName());3184 }3185 }3186 3187 GetJITLoaders().DidAttach();3188 3189 SystemRuntime *system_runtime = GetSystemRuntime();3190 if (system_runtime) {3191 system_runtime->DidAttach();3192 if (log) {3193 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3194 LLDB_LOG(log,3195 "after SystemRuntime::DidAttach(), target "3196 "executable is {0} (using {1} plugin)",3197 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),3198 system_runtime->GetPluginName());3199 }3200 }3201 3202 // If we don't have an operating system plugin loaded yet, see if3203 // LoadOperatingSystemPlugin can find one (and stuff it in m_os_up).3204 if (!m_os_up)3205 LoadOperatingSystemPlugin(false);3206 3207 if (m_os_up) {3208 // Somebody might have gotten threads before we loaded the OS Plugin above,3209 // so we need to force the update now or the newly loaded plugin won't get3210 // a chance to process the threads.3211 m_thread_list.Clear();3212 UpdateThreadListIfNeeded();3213 }3214 3215 // Figure out which one is the executable, and set that in our target:3216 ModuleSP new_executable_module_sp;3217 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {3218 if (module_sp && module_sp->IsExecutable()) {3219 if (GetTarget().GetExecutableModulePointer() != module_sp.get())3220 new_executable_module_sp = module_sp;3221 break;3222 }3223 }3224 if (new_executable_module_sp) {3225 GetTarget().SetExecutableModule(new_executable_module_sp,3226 eLoadDependentsNo);3227 if (log) {3228 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();3229 LLDB_LOGF(3230 log,3231 "Process::%s after looping through modules, target executable is %s",3232 __FUNCTION__,3233 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()3234 : "<none>");3235 }3236 }3237 // Since we hijacked the event stream, we will have we won't have run the3238 // stop hooks. Make sure we do that here:3239 GetTarget().RunStopHooks(/* at_initial_stop= */ true);3240}3241 3242Status Process::ConnectRemote(llvm::StringRef remote_url) {3243 m_abi_sp.reset();3244 {3245 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);3246 m_process_input_reader.reset();3247 }3248 3249 // Find the process and its architecture. Make sure it matches the3250 // architecture of the current Target, and if not adjust it.3251 3252 Status error(DoConnectRemote(remote_url));3253 if (error.Success()) {3254 if (GetID() != LLDB_INVALID_PROCESS_ID) {3255 EventSP event_sp;3256 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);3257 3258 if (state == eStateStopped || state == eStateCrashed) {3259 // If we attached and actually have a process on the other end, then3260 // this ended up being the equivalent of an attach.3261 SetShouldDetach(true);3262 CompleteAttach();3263 3264 // This delays passing the stopped event to listeners till3265 // CompleteAttach gets a chance to complete...3266 HandlePrivateEvent(event_sp);3267 }3268 }3269 3270 if (PrivateStateThreadIsValid())3271 ResumePrivateStateThread();3272 else3273 StartPrivateStateThread();3274 }3275 return error;3276}3277 3278void Process::SetBaseDirection(RunDirection direction) {3279 if (m_base_direction == direction)3280 return;3281 m_thread_list.DiscardThreadPlans();3282 m_base_direction = direction;3283}3284 3285Status Process::PrivateResume() {3286 Log *log(GetLog(LLDBLog::Process | LLDBLog::Step));3287 LLDB_LOGF(log,3288 "Process::PrivateResume() m_stop_id = %u, public state: %s "3289 "private state: %s",3290 m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),3291 StateAsCString(m_private_state.GetValue()));3292 3293 // If signals handing status changed we might want to update our signal3294 // filters before resuming.3295 UpdateAutomaticSignalFiltering();3296 // Clear any crash info we accumulated for this stop, but don't do so if we3297 // are running functions; we don't want to wipe out the real stop's info.3298 if (!GetModID().IsLastResumeForUserExpression())3299 ResetExtendedCrashInfoDict();3300 3301 Status error(WillResume());3302 // Tell the process it is about to resume before the thread list3303 if (error.Success()) {3304 // Now let the thread list know we are about to resume so it can let all of3305 // our threads know that they are about to be resumed. Threads will each be3306 // called with Thread::WillResume(StateType) where StateType contains the3307 // state that they are supposed to have when the process is resumed3308 // (suspended/running/stepping). Threads should also check their resume3309 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to3310 // start back up with a signal.3311 RunDirection direction;3312 if (m_thread_list.WillResume(direction)) {3313 LLDB_LOGF(log, "Process::PrivateResume WillResume direction=%d",3314 direction);3315 // Last thing, do the PreResumeActions.3316 if (!RunPreResumeActions()) {3317 error = Status::FromErrorString(3318 "Process::PrivateResume PreResumeActions failed, not resuming.");3319 LLDB_LOGF(3320 log,3321 "Process::PrivateResume PreResumeActions failed, not resuming.");3322 } else {3323 m_mod_id.BumpResumeID();3324 error = DoResume(direction);3325 if (error.Success()) {3326 DidResume();3327 m_thread_list.DidResume();3328 LLDB_LOGF(log,3329 "Process::PrivateResume thinks the process has resumed.");3330 } else {3331 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");3332 return error;3333 }3334 }3335 } else {3336 // Somebody wanted to run without running (e.g. we were faking a step3337 // from one frame of a set of inlined frames that share the same PC to3338 // another.) So generate a continue & a stopped event, and let the world3339 // handle them.3340 LLDB_LOGF(log,3341 "Process::PrivateResume() asked to simulate a start & stop.");3342 3343 SetPrivateState(eStateRunning);3344 SetPrivateState(eStateStopped);3345 }3346 } else3347 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",3348 error.AsCString("<unknown error>"));3349 return error;3350}3351 3352Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {3353 if (!StateIsRunningState(m_public_state.GetValue()))3354 return Status::FromErrorString("Process is not running.");3355 3356 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in3357 // case it was already set and some thread plan logic calls halt on its own.3358 m_clear_thread_plans_on_stop |= clear_thread_plans;3359 3360 ListenerSP halt_listener_sp(3361 Listener::MakeListener("lldb.process.halt_listener"));3362 HijackProcessEvents(halt_listener_sp);3363 3364 EventSP event_sp;3365 3366 SendAsyncInterrupt();3367 3368 if (m_public_state.GetValue() == eStateAttaching) {3369 // Don't hijack and eat the eStateExited as the code that was doing the3370 // attach will be waiting for this event...3371 RestoreProcessEvents();3372 Destroy(false);3373 SetExitStatus(SIGKILL, "Cancelled async attach.");3374 return Status();3375 }3376 3377 // Wait for the process halt timeout seconds for the process to stop.3378 // If we are going to use the run lock, that means we're stopping out to the3379 // user, so we should also select the most relevant frame.3380 SelectMostRelevant select_most_relevant =3381 use_run_lock ? SelectMostRelevantFrame : DoNoSelectMostRelevantFrame;3382 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,3383 halt_listener_sp, nullptr,3384 use_run_lock, select_most_relevant);3385 RestoreProcessEvents();3386 3387 if (state == eStateInvalid || !event_sp) {3388 // We timed out and didn't get a stop event...3389 return Status::FromErrorStringWithFormat("Halt timed out. State = %s",3390 StateAsCString(GetState()));3391 }3392 3393 BroadcastEvent(event_sp);3394 3395 return Status();3396}3397 3398lldb::addr_t Process::FindInMemory(lldb::addr_t low, lldb::addr_t high,3399 const uint8_t *buf, size_t size) {3400 const size_t region_size = high - low;3401 3402 if (region_size < size)3403 return LLDB_INVALID_ADDRESS;3404 3405 // See "Boyer-Moore string search algorithm".3406 std::vector<size_t> bad_char_heuristic(256, size);3407 for (size_t idx = 0; idx < size - 1; idx++) {3408 decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];3409 bad_char_heuristic[bcu_idx] = size - idx - 1;3410 }3411 3412 // Memory we're currently searching through.3413 llvm::SmallVector<uint8_t, 0> mem;3414 // Position of the memory buffer.3415 addr_t mem_pos = low;3416 // Maximum number of bytes read (and buffered). We need to read at least3417 // `size` bytes for a successful match.3418 const size_t max_read_size = std::max<size_t>(size, 0x10000);3419 3420 for (addr_t cur_addr = low; cur_addr <= (high - size);) {3421 if (cur_addr + size > mem_pos + mem.size()) {3422 // We need to read more data. We don't attempt to reuse the data we've3423 // already read (up to `size-1` bytes from `cur_addr` to3424 // `mem_pos+mem.size()`). This is fine for patterns much smaller than3425 // max_read_size. For very3426 // long patterns we may need to do something more elaborate.3427 mem.resize_for_overwrite(max_read_size);3428 Status error;3429 mem.resize(ReadMemory(cur_addr, mem.data(),3430 std::min<addr_t>(mem.size(), high - cur_addr),3431 error));3432 mem_pos = cur_addr;3433 if (size > mem.size()) {3434 // We didn't read enough data. Skip to the next memory region.3435 MemoryRegionInfo info;3436 error = GetMemoryRegionInfo(mem_pos + mem.size(), info);3437 if (error.Fail())3438 break;3439 cur_addr = info.GetRange().GetRangeEnd();3440 continue;3441 }3442 }3443 int64_t j = size - 1;3444 while (j >= 0 && buf[j] == mem[cur_addr + j - mem_pos])3445 j--;3446 if (j < 0)3447 return cur_addr; // We have a match.3448 cur_addr += bad_char_heuristic[mem[cur_addr + size - 1 - mem_pos]];3449 }3450 3451 return LLDB_INVALID_ADDRESS;3452}3453 3454Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {3455 Status error;3456 3457 // Check both the public & private states here. If we're hung evaluating an3458 // expression, for instance, then the public state will be stopped, but we3459 // still need to interrupt.3460 if (m_public_state.GetValue() == eStateRunning ||3461 m_private_state.GetValue() == eStateRunning) {3462 Log *log = GetLog(LLDBLog::Process);3463 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);3464 3465 ListenerSP listener_sp(3466 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));3467 HijackProcessEvents(listener_sp);3468 3469 SendAsyncInterrupt();3470 3471 // Consume the interrupt event.3472 StateType state = WaitForProcessToStop(GetInterruptTimeout(),3473 &exit_event_sp, true, listener_sp);3474 3475 RestoreProcessEvents();3476 3477 // If the process exited while we were waiting for it to stop, put the3478 // exited event into the shared pointer passed in and return. Our caller3479 // doesn't need to do anything else, since they don't have a process3480 // anymore...3481 3482 if (state == eStateExited || m_private_state.GetValue() == eStateExited) {3483 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",3484 __FUNCTION__);3485 return error;3486 } else3487 exit_event_sp.reset(); // It is ok to consume any non-exit stop events3488 3489 if (state != eStateStopped) {3490 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,3491 StateAsCString(state));3492 // If we really couldn't stop the process then we should just error out3493 // here, but if the lower levels just bobbled sending the event and we3494 // really are stopped, then continue on.3495 StateType private_state = m_private_state.GetValue();3496 if (private_state != eStateStopped) {3497 return Status::FromErrorStringWithFormat(3498 "Attempt to stop the target in order to detach timed out. "3499 "State = %s",3500 StateAsCString(GetState()));3501 }3502 }3503 }3504 return error;3505}3506 3507Status Process::Detach(bool keep_stopped) {3508 EventSP exit_event_sp;3509 Status error;3510 m_destroy_in_process = true;3511 3512 error = WillDetach();3513 3514 if (error.Success()) {3515 if (DetachRequiresHalt()) {3516 error = StopForDestroyOrDetach(exit_event_sp);3517 if (!error.Success()) {3518 m_destroy_in_process = false;3519 return error;3520 } else if (exit_event_sp) {3521 // We shouldn't need to do anything else here. There's no process left3522 // to detach from...3523 StopPrivateStateThread();3524 m_destroy_in_process = false;3525 return error;3526 }3527 }3528 3529 m_thread_list.DiscardThreadPlans();3530 DisableAllBreakpointSites();3531 3532 error = DoDetach(keep_stopped);3533 if (error.Success()) {3534 DidDetach();3535 StopPrivateStateThread();3536 } else {3537 return error;3538 }3539 }3540 m_destroy_in_process = false;3541 3542 // If we exited when we were waiting for a process to stop, then forward the3543 // event here so we don't lose the event3544 if (exit_event_sp) {3545 // Directly broadcast our exited event because we shut down our private3546 // state thread above3547 BroadcastEvent(exit_event_sp);3548 }3549 3550 // If we have been interrupted (to kill us) in the middle of running, we may3551 // not end up propagating the last events through the event system, in which3552 // case we might strand the write lock. Unlock it here so when we do to tear3553 // down the process we don't get an error destroying the lock.3554 3555 m_public_run_lock.SetStopped();3556 return error;3557}3558 3559Status Process::Destroy(bool force_kill) {3560 // If we've already called Process::Finalize then there's nothing useful to3561 // be done here. Finalize has actually called Destroy already.3562 if (m_finalizing)3563 return {};3564 return DestroyImpl(force_kill);3565}3566 3567Status Process::DestroyImpl(bool force_kill) {3568 // Tell ourselves we are in the process of destroying the process, so that we3569 // don't do any unnecessary work that might hinder the destruction. Remember3570 // to set this back to false when we are done. That way if the attempt3571 // failed and the process stays around for some reason it won't be in a3572 // confused state.3573 3574 if (force_kill)3575 m_should_detach = false;3576 3577 if (GetShouldDetach()) {3578 // FIXME: This will have to be a process setting:3579 bool keep_stopped = false;3580 Detach(keep_stopped);3581 }3582 3583 m_destroy_in_process = true;3584 3585 Status error(WillDestroy());3586 if (error.Success()) {3587 EventSP exit_event_sp;3588 if (DestroyRequiresHalt()) {3589 error = StopForDestroyOrDetach(exit_event_sp);3590 }3591 3592 if (m_public_state.GetValue() == eStateStopped) {3593 // Ditch all thread plans, and remove all our breakpoints: in case we3594 // have to restart the target to kill it, we don't want it hitting a3595 // breakpoint... Only do this if we've stopped, however, since if we3596 // didn't manage to halt it above, then we're not going to have much luck3597 // doing this now.3598 m_thread_list.DiscardThreadPlans();3599 DisableAllBreakpointSites();3600 }3601 3602 error = DoDestroy();3603 if (error.Success()) {3604 DidDestroy();3605 StopPrivateStateThread();3606 }3607 m_stdio_communication.StopReadThread();3608 m_stdio_communication.Disconnect();3609 m_stdin_forward = false;3610 3611 {3612 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);3613 if (m_process_input_reader) {3614 m_process_input_reader->SetIsDone(true);3615 m_process_input_reader->Cancel();3616 m_process_input_reader.reset();3617 }3618 }3619 3620 // If we exited when we were waiting for a process to stop, then forward3621 // the event here so we don't lose the event3622 if (exit_event_sp) {3623 // Directly broadcast our exited event because we shut down our private3624 // state thread above3625 BroadcastEvent(exit_event_sp);3626 }3627 3628 // If we have been interrupted (to kill us) in the middle of running, we3629 // may not end up propagating the last events through the event system, in3630 // which case we might strand the write lock. Unlock it here so when we do3631 // to tear down the process we don't get an error destroying the lock.3632 m_public_run_lock.SetStopped();3633 }3634 3635 m_destroy_in_process = false;3636 3637 return error;3638}3639 3640Status Process::Signal(int signal) {3641 Status error(WillSignal());3642 if (error.Success()) {3643 error = DoSignal(signal);3644 if (error.Success())3645 DidSignal();3646 }3647 return error;3648}3649 3650void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {3651 assert(signals_sp && "null signals_sp");3652 m_unix_signals_sp = std::move(signals_sp);3653}3654 3655const lldb::UnixSignalsSP &Process::GetUnixSignals() {3656 assert(m_unix_signals_sp && "null m_unix_signals_sp");3657 return m_unix_signals_sp;3658}3659 3660lldb::ByteOrder Process::GetByteOrder() const {3661 return GetTarget().GetArchitecture().GetByteOrder();3662}3663 3664uint32_t Process::GetAddressByteSize() const {3665 return GetTarget().GetArchitecture().GetAddressByteSize();3666}3667 3668bool Process::ShouldBroadcastEvent(Event *event_ptr) {3669 const StateType state =3670 Process::ProcessEventData::GetStateFromEvent(event_ptr);3671 bool return_value = true;3672 Log *log(GetLog(LLDBLog::Events | LLDBLog::Process));3673 3674 switch (state) {3675 case eStateDetached:3676 case eStateExited:3677 case eStateUnloaded:3678 m_stdio_communication.SynchronizeWithReadThread();3679 m_stdio_communication.StopReadThread();3680 m_stdio_communication.Disconnect();3681 m_stdin_forward = false;3682 3683 [[fallthrough]];3684 case eStateConnected:3685 case eStateAttaching:3686 case eStateLaunching:3687 // These events indicate changes in the state of the debugging session,3688 // always report them.3689 return_value = true;3690 break;3691 case eStateInvalid:3692 // We stopped for no apparent reason, don't report it.3693 return_value = false;3694 break;3695 case eStateRunning:3696 case eStateStepping:3697 // If we've started the target running, we handle the cases where we are3698 // already running and where there is a transition from stopped to running3699 // differently. running -> running: Automatically suppress extra running3700 // events stopped -> running: Report except when there is one or more no3701 // votes3702 // and no yes votes.3703 SynchronouslyNotifyStateChanged(state);3704 if (m_force_next_event_delivery)3705 return_value = true;3706 else {3707 switch (m_last_broadcast_state) {3708 case eStateRunning:3709 case eStateStepping:3710 // We always suppress multiple runnings with no PUBLIC stop in between.3711 return_value = false;3712 break;3713 default:3714 // TODO: make this work correctly. For now always report3715 // run if we aren't running so we don't miss any running events. If I3716 // run the lldb/test/thread/a.out file and break at main.cpp:58, run3717 // and hit the breakpoints on multiple threads, then somehow during the3718 // stepping over of all breakpoints no run gets reported.3719 3720 // This is a transition from stop to run.3721 switch (m_thread_list.ShouldReportRun(event_ptr)) {3722 case eVoteYes:3723 case eVoteNoOpinion:3724 return_value = true;3725 break;3726 case eVoteNo:3727 return_value = false;3728 break;3729 }3730 break;3731 }3732 }3733 break;3734 case eStateStopped:3735 case eStateCrashed:3736 case eStateSuspended:3737 // We've stopped. First see if we're going to restart the target. If we3738 // are going to stop, then we always broadcast the event. If we aren't3739 // going to stop, let the thread plans decide if we're going to report this3740 // event. If no thread has an opinion, we don't report it.3741 3742 m_stdio_communication.SynchronizeWithReadThread();3743 RefreshStateAfterStop();3744 if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {3745 LLDB_LOGF(log,3746 "Process::ShouldBroadcastEvent (%p) stopped due to an "3747 "interrupt, state: %s",3748 static_cast<void *>(event_ptr), StateAsCString(state));3749 // Even though we know we are going to stop, we should let the threads3750 // have a look at the stop, so they can properly set their state.3751 m_thread_list.ShouldStop(event_ptr);3752 return_value = true;3753 } else {3754 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);3755 bool should_resume = false;3756 3757 // It makes no sense to ask "ShouldStop" if we've already been3758 // restarted... Asking the thread list is also not likely to go well,3759 // since we are running again. So in that case just report the event.3760 3761 if (!was_restarted)3762 should_resume = !m_thread_list.ShouldStop(event_ptr);3763 3764 if (was_restarted || should_resume || m_resume_requested) {3765 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);3766 LLDB_LOGF(log,3767 "Process::ShouldBroadcastEvent: should_resume: %i state: "3768 "%s was_restarted: %i report_stop_vote: %d.",3769 should_resume, StateAsCString(state), was_restarted,3770 report_stop_vote);3771 3772 switch (report_stop_vote) {3773 case eVoteYes:3774 return_value = true;3775 break;3776 case eVoteNoOpinion:3777 case eVoteNo:3778 return_value = false;3779 break;3780 }3781 3782 if (!was_restarted) {3783 LLDB_LOGF(log,3784 "Process::ShouldBroadcastEvent (%p) Restarting process "3785 "from state: %s",3786 static_cast<void *>(event_ptr), StateAsCString(state));3787 ProcessEventData::SetRestartedInEvent(event_ptr, true);3788 PrivateResume();3789 }3790 } else {3791 return_value = true;3792 SynchronouslyNotifyStateChanged(state);3793 }3794 }3795 break;3796 }3797 3798 // Forcing the next event delivery is a one shot deal. So reset it here.3799 m_force_next_event_delivery = false;3800 3801 // We do some coalescing of events (for instance two consecutive running3802 // events get coalesced.) But we only coalesce against events we actually3803 // broadcast. So we use m_last_broadcast_state to track that. NB - you3804 // can't use "m_public_state.GetValue()" for that purpose, as was originally3805 // done, because the PublicState reflects the last event pulled off the3806 // queue, and there may be several events stacked up on the queue unserviced.3807 // So the PublicState may not reflect the last broadcasted event yet.3808 // m_last_broadcast_state gets updated here.3809 3810 if (return_value)3811 m_last_broadcast_state = state;3812 3813 LLDB_LOGF(log,3814 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "3815 "broadcast state: %s - %s",3816 static_cast<void *>(event_ptr), StateAsCString(state),3817 StateAsCString(m_last_broadcast_state),3818 return_value ? "YES" : "NO");3819 return return_value;3820}3821 3822bool Process::StartPrivateStateThread(bool is_secondary_thread) {3823 Log *log = GetLog(LLDBLog::Events);3824 3825 bool already_running = PrivateStateThreadIsValid();3826 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,3827 already_running ? " already running"3828 : " starting private state thread");3829 3830 if (!is_secondary_thread && already_running)3831 return true;3832 3833 // Create a thread that watches our internal state and controls which events3834 // make it to clients (into the DCProcess event queue).3835 char thread_name[1024];3836 uint32_t max_len = llvm::get_max_thread_name_length();3837 if (max_len > 0 && max_len <= 30) {3838 // On platforms with abbreviated thread name lengths, choose thread names3839 // that fit within the limit.3840 if (already_running)3841 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");3842 else3843 snprintf(thread_name, sizeof(thread_name), "intern-state");3844 } else {3845 if (already_running)3846 snprintf(thread_name, sizeof(thread_name),3847 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",3848 GetID());3849 else3850 snprintf(thread_name, sizeof(thread_name),3851 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());3852 }3853 3854 llvm::Expected<HostThread> private_state_thread =3855 ThreadLauncher::LaunchThread(3856 thread_name,3857 [this, is_secondary_thread] {3858 return RunPrivateStateThread(is_secondary_thread);3859 },3860 8 * 1024 * 1024);3861 if (!private_state_thread) {3862 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),3863 "failed to launch host thread: {0}");3864 return false;3865 }3866 3867 assert(private_state_thread->IsJoinable());3868 m_private_state_thread = *private_state_thread;3869 ResumePrivateStateThread();3870 return true;3871}3872 3873void Process::PausePrivateStateThread() {3874 ControlPrivateStateThread(eBroadcastInternalStateControlPause);3875}3876 3877void Process::ResumePrivateStateThread() {3878 ControlPrivateStateThread(eBroadcastInternalStateControlResume);3879}3880 3881void Process::StopPrivateStateThread() {3882 if (m_private_state_thread.IsJoinable())3883 ControlPrivateStateThread(eBroadcastInternalStateControlStop);3884 else {3885 Log *log = GetLog(LLDBLog::Process);3886 LLDB_LOGF(3887 log,3888 "Went to stop the private state thread, but it was already invalid.");3889 }3890}3891 3892void Process::ControlPrivateStateThread(uint32_t signal) {3893 Log *log = GetLog(LLDBLog::Process);3894 3895 assert(signal == eBroadcastInternalStateControlStop ||3896 signal == eBroadcastInternalStateControlPause ||3897 signal == eBroadcastInternalStateControlResume);3898 3899 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);3900 3901 // Signal the private state thread3902 if (m_private_state_thread.IsJoinable()) {3903 // Broadcast the event.3904 // It is important to do this outside of the if below, because it's3905 // possible that the thread state is invalid but that the thread is waiting3906 // on a control event instead of simply being on its way out (this should3907 // not happen, but it apparently can).3908 LLDB_LOGF(log, "Sending control event of type: %d.", signal);3909 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());3910 m_private_state_control_broadcaster.BroadcastEvent(signal,3911 event_receipt_sp);3912 3913 // Wait for the event receipt or for the private state thread to exit3914 bool receipt_received = false;3915 if (PrivateStateThreadIsValid()) {3916 while (!receipt_received) {3917 // Check for a receipt for n seconds and then check if the private3918 // state thread is still around.3919 receipt_received =3920 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());3921 if (!receipt_received) {3922 // Check if the private state thread is still around. If it isn't3923 // then we are done waiting3924 if (!PrivateStateThreadIsValid())3925 break; // Private state thread exited or is exiting, we are done3926 }3927 }3928 }3929 3930 if (signal == eBroadcastInternalStateControlStop) {3931 thread_result_t result = {};3932 m_private_state_thread.Join(&result);3933 m_private_state_thread.Reset();3934 }3935 } else {3936 LLDB_LOGF(3937 log,3938 "Private state thread already dead, no need to signal it to stop.");3939 }3940}3941 3942void Process::SendAsyncInterrupt(Thread *thread) {3943 if (thread != nullptr)3944 m_interrupt_tid = thread->GetProtocolID();3945 else3946 m_interrupt_tid = LLDB_INVALID_THREAD_ID;3947 if (PrivateStateThreadIsValid())3948 m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,3949 nullptr);3950 else3951 BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);3952}3953 3954void Process::HandlePrivateEvent(EventSP &event_sp) {3955 Log *log = GetLog(LLDBLog::Process);3956 m_resume_requested = false;3957 3958 const StateType new_state =3959 Process::ProcessEventData::GetStateFromEvent(event_sp.get());3960 3961 // First check to see if anybody wants a shot at this event:3962 if (m_next_event_action_up) {3963 NextEventAction::EventActionResult action_result =3964 m_next_event_action_up->PerformAction(event_sp);3965 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);3966 3967 switch (action_result) {3968 case NextEventAction::eEventActionSuccess:3969 SetNextEventAction(nullptr);3970 break;3971 3972 case NextEventAction::eEventActionRetry:3973 break;3974 3975 case NextEventAction::eEventActionExit:3976 // Handle Exiting Here. If we already got an exited event, we should3977 // just propagate it. Otherwise, swallow this event, and set our state3978 // to exit so the next event will kill us.3979 if (new_state != eStateExited) {3980 // FIXME: should cons up an exited event, and discard this one.3981 SetExitStatus(0, m_next_event_action_up->GetExitString());3982 SetNextEventAction(nullptr);3983 return;3984 }3985 SetNextEventAction(nullptr);3986 break;3987 }3988 }3989 3990 // See if we should broadcast this state to external clients?3991 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());3992 3993 if (should_broadcast) {3994 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);3995 if (log) {3996 LLDB_LOGF(log,3997 "Process::%s (pid = %" PRIu643998 ") broadcasting new state %s (old state %s) to %s",3999 __FUNCTION__, GetID(), StateAsCString(new_state),4000 StateAsCString(GetState()),4001 is_hijacked ? "hijacked" : "public");4002 }4003 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());4004 if (StateIsRunningState(new_state)) {4005 // Only push the input handler if we aren't fowarding events, as this4006 // means the curses GUI is in use... Or don't push it if we are launching4007 // since it will come up stopped.4008 if (!GetTarget().GetDebugger().IsForwardingEvents() &&4009 new_state != eStateLaunching && new_state != eStateAttaching) {4010 PushProcessIOHandler();4011 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,4012 eBroadcastAlways);4013 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",4014 __FUNCTION__, m_iohandler_sync.GetValue());4015 }4016 } else if (StateIsStoppedState(new_state, false)) {4017 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {4018 // If the lldb_private::Debugger is handling the events, we don't want4019 // to pop the process IOHandler here, we want to do it when we receive4020 // the stopped event so we can carefully control when the process4021 // IOHandler is popped because when we stop we want to display some4022 // text stating how and why we stopped, then maybe some4023 // process/thread/frame info, and then we want the "(lldb) " prompt to4024 // show up. If we pop the process IOHandler here, then we will cause4025 // the command interpreter to become the top IOHandler after the4026 // process pops off and it will update its prompt right away... See the4027 // Debugger.cpp file where it calls the function as4028 // "process_sp->PopProcessIOHandler()" to see where I am talking about.4029 // Otherwise we end up getting overlapping "(lldb) " prompts and4030 // garbled output.4031 //4032 // If we aren't handling the events in the debugger (which is indicated4033 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or4034 // we are hijacked, then we always pop the process IO handler manually.4035 // Hijacking happens when the internal process state thread is running4036 // thread plans, or when commands want to run in synchronous mode and4037 // they call "process->WaitForProcessToStop()". An example of something4038 // that will hijack the events is a simple expression:4039 //4040 // (lldb) expr (int)puts("hello")4041 //4042 // This will cause the internal process state thread to resume and halt4043 // the process (and _it_ will hijack the eBroadcastBitStateChanged4044 // events) and we do need the IO handler to be pushed and popped4045 // correctly.4046 4047 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())4048 PopProcessIOHandler();4049 }4050 }4051 4052 BroadcastEvent(event_sp);4053 } else {4054 if (log) {4055 LLDB_LOGF(4056 log,4057 "Process::%s (pid = %" PRIu644058 ") suppressing state %s (old state %s): should_broadcast == false",4059 __FUNCTION__, GetID(), StateAsCString(new_state),4060 StateAsCString(GetState()));4061 }4062 }4063}4064 4065Status Process::HaltPrivate() {4066 EventSP event_sp;4067 Status error(WillHalt());4068 if (error.Fail())4069 return error;4070 4071 // Ask the process subclass to actually halt our process4072 bool caused_stop;4073 error = DoHalt(caused_stop);4074 4075 DidHalt();4076 return error;4077}4078 4079thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {4080 bool control_only = true;4081 4082 Log *log = GetLog(LLDBLog::Process);4083 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",4084 __FUNCTION__, static_cast<void *>(this), GetID());4085 4086 bool exit_now = false;4087 bool interrupt_requested = false;4088 while (!exit_now) {4089 EventSP event_sp;4090 GetEventsPrivate(event_sp, std::nullopt, control_only);4091 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {4092 LLDB_LOGF(log,4093 "Process::%s (arg = %p, pid = %" PRIu644094 ") got a control event: %d",4095 __FUNCTION__, static_cast<void *>(this), GetID(),4096 event_sp->GetType());4097 4098 switch (event_sp->GetType()) {4099 case eBroadcastInternalStateControlStop:4100 exit_now = true;4101 break; // doing any internal state management below4102 4103 case eBroadcastInternalStateControlPause:4104 control_only = true;4105 break;4106 4107 case eBroadcastInternalStateControlResume:4108 control_only = false;4109 break;4110 }4111 4112 continue;4113 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {4114 if (m_public_state.GetValue() == eStateAttaching) {4115 LLDB_LOGF(log,4116 "Process::%s (arg = %p, pid = %" PRIu644117 ") woke up with an interrupt while attaching - "4118 "forwarding interrupt.",4119 __FUNCTION__, static_cast<void *>(this), GetID());4120 // The server may be spinning waiting for a process to appear, in which4121 // case we should tell it to stop doing that. Normally, we don't NEED4122 // to do that because we will next close the communication to the stub4123 // and that will get it to shut down. But there are remote debugging4124 // cases where relying on that side-effect causes the shutdown to be4125 // flakey, so we should send a positive signal to interrupt the wait.4126 Status error = HaltPrivate();4127 BroadcastEvent(eBroadcastBitInterrupt, nullptr);4128 } else if (StateIsRunningState(m_last_broadcast_state)) {4129 LLDB_LOGF(log,4130 "Process::%s (arg = %p, pid = %" PRIu644131 ") woke up with an interrupt - Halting.",4132 __FUNCTION__, static_cast<void *>(this), GetID());4133 Status error = HaltPrivate();4134 if (error.Fail() && log)4135 LLDB_LOGF(log,4136 "Process::%s (arg = %p, pid = %" PRIu644137 ") failed to halt the process: %s",4138 __FUNCTION__, static_cast<void *>(this), GetID(),4139 error.AsCString());4140 // Halt should generate a stopped event. Make a note of the fact that4141 // we were doing the interrupt, so we can set the interrupted flag4142 // after we receive the event. We deliberately set this to true even if4143 // HaltPrivate failed, so that we can interrupt on the next natural4144 // stop.4145 interrupt_requested = true;4146 } else {4147 // This can happen when someone (e.g. Process::Halt) sees that we are4148 // running and sends an interrupt request, but the process actually4149 // stops before we receive it. In that case, we can just ignore the4150 // request. We use m_last_broadcast_state, because the Stopped event4151 // may not have been popped of the event queue yet, which is when the4152 // public state gets updated.4153 LLDB_LOGF(log,4154 "Process::%s ignoring interrupt as we have already stopped.",4155 __FUNCTION__);4156 }4157 continue;4158 }4159 4160 const StateType internal_state =4161 Process::ProcessEventData::GetStateFromEvent(event_sp.get());4162 4163 if (internal_state != eStateInvalid) {4164 if (m_clear_thread_plans_on_stop &&4165 StateIsStoppedState(internal_state, true)) {4166 m_clear_thread_plans_on_stop = false;4167 m_thread_list.DiscardThreadPlans();4168 }4169 4170 if (interrupt_requested) {4171 if (StateIsStoppedState(internal_state, true)) {4172 // Only mark interrupt event if it is not thread specific async4173 // interrupt.4174 if (m_interrupt_tid == LLDB_INVALID_THREAD_ID) {4175 // We requested the interrupt, so mark this as such in the stop4176 // event so clients can tell an interrupted process from a natural4177 // stop4178 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);4179 }4180 interrupt_requested = false;4181 } else if (log) {4182 LLDB_LOGF(log,4183 "Process::%s interrupt_requested, but a non-stopped "4184 "state '%s' received.",4185 __FUNCTION__, StateAsCString(internal_state));4186 }4187 }4188 4189 HandlePrivateEvent(event_sp);4190 }4191 4192 if (internal_state == eStateInvalid || internal_state == eStateExited ||4193 internal_state == eStateDetached) {4194 LLDB_LOGF(log,4195 "Process::%s (arg = %p, pid = %" PRIu644196 ") about to exit with internal state %s...",4197 __FUNCTION__, static_cast<void *>(this), GetID(),4198 StateAsCString(internal_state));4199 4200 break;4201 }4202 }4203 4204 // Verify log is still enabled before attempting to write to it...4205 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",4206 __FUNCTION__, static_cast<void *>(this), GetID());4207 4208 // If we are a secondary thread, then the primary thread we are working for4209 // will have already acquired the public_run_lock, and isn't done with what4210 // it was doing yet, so don't try to change it on the way out.4211 if (!is_secondary_thread)4212 m_public_run_lock.SetStopped();4213 return {};4214}4215 4216// Process Event Data4217 4218Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp() {}4219 4220Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,4221 StateType state)4222 : EventData(), m_process_wp(), m_state(state) {4223 if (process_sp)4224 m_process_wp = process_sp;4225}4226 4227Process::ProcessEventData::~ProcessEventData() = default;4228 4229llvm::StringRef Process::ProcessEventData::GetFlavorString() {4230 return "Process::ProcessEventData";4231}4232 4233llvm::StringRef Process::ProcessEventData::GetFlavor() const {4234 return ProcessEventData::GetFlavorString();4235}4236 4237bool Process::ProcessEventData::ShouldStop(Event *event_ptr,4238 bool &found_valid_stopinfo) {4239 found_valid_stopinfo = false;4240 4241 ProcessSP process_sp(m_process_wp.lock());4242 if (!process_sp)4243 return false;4244 4245 ThreadList &curr_thread_list = process_sp->GetThreadList();4246 uint32_t num_threads = curr_thread_list.GetSize();4247 4248 // The actions might change one of the thread's stop_info's opinions about4249 // whether we should stop the process, so we need to query that as we go.4250 4251 // One other complication here, is that we try to catch any case where the4252 // target has run (except for expressions) and immediately exit, but if we4253 // get that wrong (which is possible) then the thread list might have4254 // changed, and that would cause our iteration here to crash. We could4255 // make a copy of the thread list, but we'd really like to also know if it4256 // has changed at all, so we store the original thread ID's of all threads and4257 // check what we get back against this list & bag out if anything differs.4258 std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;4259 for (uint32_t idx = 0; idx < num_threads; ++idx) {4260 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);4261 4262 /*4263 Filter out all suspended threads, they could not be the reason4264 of stop and no need to perform any actions on them.4265 */4266 if (thread_sp->GetResumeState() != eStateSuspended)4267 not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());4268 }4269 4270 // Use this to track whether we should continue from here. We will only4271 // continue the target running if no thread says we should stop. Of course4272 // if some thread's PerformAction actually sets the target running, then it4273 // doesn't matter what the other threads say...4274 4275 bool still_should_stop = false;4276 4277 // Sometimes - for instance if we have a bug in the stub we are talking to,4278 // we stop but no thread has a valid stop reason. In that case we should4279 // just stop, because we have no way of telling what the right thing to do4280 // is, and it's better to let the user decide than continue behind their4281 // backs.4282 4283 for (auto [thread_sp, thread_index] : not_suspended_threads) {4284 if (curr_thread_list.GetSize() != num_threads) {4285 Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));4286 LLDB_LOGF(4287 log,4288 "Number of threads changed from %u to %u while processing event.",4289 num_threads, curr_thread_list.GetSize());4290 break;4291 }4292 4293 if (thread_sp->GetIndexID() != thread_index) {4294 Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));4295 LLDB_LOG(log,4296 "The thread {0} changed from {1} to {2} while processing event.",4297 thread_sp.get(), thread_index, thread_sp->GetIndexID());4298 break;4299 }4300 4301 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();4302 if (stop_info_sp && stop_info_sp->IsValid()) {4303 found_valid_stopinfo = true;4304 bool this_thread_wants_to_stop;4305 if (stop_info_sp->GetOverrideShouldStop()) {4306 this_thread_wants_to_stop =4307 stop_info_sp->GetOverriddenShouldStopValue();4308 } else {4309 stop_info_sp->PerformAction(event_ptr);4310 // The stop action might restart the target. If it does, then we4311 // want to mark that in the event so that whoever is receiving it4312 // will know to wait for the running event and reflect that state4313 // appropriately. We also need to stop processing actions, since they4314 // aren't expecting the target to be running.4315 4316 // Clear the selected frame which may have been set as part of utility4317 // expressions that have been run as part of this stop. If we didn't4318 // clear this, then StopInfo::GetSuggestedStackFrameIndex would not4319 // take affect when we next called SelectMostRelevantFrame.4320 // PerformAction should not be the one setting a selected frame, instead4321 // this should be done via GetSuggestedStackFrameIndex.4322 thread_sp->ClearSelectedFrameIndex();4323 4324 // FIXME: we might have run.4325 if (stop_info_sp->HasTargetRunSinceMe()) {4326 SetRestarted(true);4327 break;4328 }4329 4330 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);4331 }4332 4333 if (!still_should_stop)4334 still_should_stop = this_thread_wants_to_stop;4335 }4336 }4337 4338 return still_should_stop;4339}4340 4341bool Process::ProcessEventData::ForwardEventToPendingListeners(4342 Event *event_ptr) {4343 // STDIO and the other async event notifications should always be forwarded.4344 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)4345 return true;4346 4347 // For state changed events, if the update state is zero, we are handling4348 // this on the private state thread. We should wait for the public event.4349 return m_update_state == 1;4350}4351 4352void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {4353 // We only have work to do for state changed events:4354 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)4355 return;4356 4357 ProcessSP process_sp(m_process_wp.lock());4358 4359 if (!process_sp)4360 return;4361 4362 // This function gets called twice for each event, once when the event gets4363 // pulled off of the private process event queue, and then any number of4364 // times, first when it gets pulled off of the public event queue, then other4365 // times when we're pretending that this is where we stopped at the end of4366 // expression evaluation. m_update_state is used to distinguish these three4367 // cases; it is 0 when we're just pulling it off for private handling, and >4368 // 1 for expression evaluation, and we don't want to do the breakpoint4369 // command handling then.4370 if (m_update_state != 1)4371 return;4372 4373 process_sp->SetPublicState(4374 m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));4375 4376 if (m_state == eStateStopped && !m_restarted) {4377 // Let process subclasses know we are about to do a public stop and do4378 // anything they might need to in order to speed up register and memory4379 // accesses.4380 process_sp->WillPublicStop();4381 }4382 4383 // If this is a halt event, even if the halt stopped with some reason other4384 // than a plain interrupt (e.g. we had already stopped for a breakpoint when4385 // the halt request came through) don't do the StopInfo actions, as they may4386 // end up restarting the process.4387 if (m_interrupted)4388 return;4389 4390 // If we're not stopped or have restarted, then skip the StopInfo actions:4391 if (m_state != eStateStopped || m_restarted) {4392 return;4393 }4394 4395 bool does_anybody_have_an_opinion = false;4396 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);4397 4398 if (GetRestarted()) {4399 return;4400 }4401 4402 if (!still_should_stop && does_anybody_have_an_opinion) {4403 // We've been asked to continue, so do that here.4404 SetRestarted(true);4405 // Use the private resume method here, since we aren't changing the run4406 // lock state.4407 process_sp->PrivateResume();4408 } else {4409 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&4410 !process_sp->StateChangedIsHijackedForSynchronousResume();4411 4412 if (!hijacked) {4413 // If we didn't restart, run the Stop Hooks here.4414 // Don't do that if state changed events aren't hooked up to the4415 // public (or SyncResume) broadcasters. StopHooks are just for4416 // real public stops. They might also restart the target,4417 // so watch for that.4418 if (process_sp->GetTarget().RunStopHooks())4419 SetRestarted(true);4420 }4421 }4422}4423 4424void Process::ProcessEventData::Dump(Stream *s) const {4425 ProcessSP process_sp(m_process_wp.lock());4426 4427 if (process_sp)4428 s->Printf(" process = %p (pid = %" PRIu64 "), ",4429 static_cast<void *>(process_sp.get()), process_sp->GetID());4430 else4431 s->PutCString(" process = NULL, ");4432 4433 s->Printf("state = %s", StateAsCString(GetState()));4434}4435 4436const Process::ProcessEventData *4437Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {4438 if (event_ptr) {4439 const EventData *event_data = event_ptr->GetData();4440 if (event_data &&4441 event_data->GetFlavor() == ProcessEventData::GetFlavorString())4442 return static_cast<const ProcessEventData *>(event_ptr->GetData());4443 }4444 return nullptr;4445}4446 4447ProcessSP4448Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {4449 ProcessSP process_sp;4450 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4451 if (data)4452 process_sp = data->GetProcessSP();4453 return process_sp;4454}4455 4456StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {4457 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4458 if (data == nullptr)4459 return eStateInvalid;4460 else4461 return data->GetState();4462}4463 4464bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {4465 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4466 if (data == nullptr)4467 return false;4468 else4469 return data->GetRestarted();4470}4471 4472void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,4473 bool new_value) {4474 ProcessEventData *data =4475 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4476 if (data != nullptr)4477 data->SetRestarted(new_value);4478}4479 4480size_t4481Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {4482 ProcessEventData *data =4483 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4484 if (data != nullptr)4485 return data->GetNumRestartedReasons();4486 else4487 return 0;4488}4489 4490const char *4491Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,4492 size_t idx) {4493 ProcessEventData *data =4494 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4495 if (data != nullptr)4496 return data->GetRestartedReasonAtIndex(idx);4497 else4498 return nullptr;4499}4500 4501void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,4502 const char *reason) {4503 ProcessEventData *data =4504 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4505 if (data != nullptr)4506 data->AddRestartedReason(reason);4507}4508 4509bool Process::ProcessEventData::GetInterruptedFromEvent(4510 const Event *event_ptr) {4511 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);4512 if (data == nullptr)4513 return false;4514 else4515 return data->GetInterrupted();4516}4517 4518void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,4519 bool new_value) {4520 ProcessEventData *data =4521 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4522 if (data != nullptr)4523 data->SetInterrupted(new_value);4524}4525 4526bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {4527 ProcessEventData *data =4528 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));4529 if (data) {4530 data->SetUpdateStateOnRemoval();4531 return true;4532 }4533 return false;4534}4535 4536lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }4537 4538void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {4539 exe_ctx.SetTargetPtr(&GetTarget());4540 exe_ctx.SetProcessPtr(this);4541 exe_ctx.SetThreadPtr(nullptr);4542 exe_ctx.SetFramePtr(nullptr);4543}4544 4545// uint32_t4546// Process::ListProcessesMatchingName (const char *name, StringList &matches,4547// std::vector<lldb::pid_t> &pids)4548//{4549// return 0;4550//}4551//4552// ArchSpec4553// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)4554//{4555// return Host::GetArchSpecForExistingProcess (pid);4556//}4557//4558// ArchSpec4559// Process::GetArchSpecForExistingProcess (const char *process_name)4560//{4561// return Host::GetArchSpecForExistingProcess (process_name);4562//}4563 4564EventSP Process::CreateEventFromProcessState(uint32_t event_type) {4565 auto event_data_sp =4566 std::make_shared<ProcessEventData>(shared_from_this(), GetState());4567 return std::make_shared<Event>(event_type, event_data_sp);4568}4569 4570void Process::AppendSTDOUT(const char *s, size_t len) {4571 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4572 m_stdout_data.append(s, len);4573 auto event_sp = CreateEventFromProcessState(eBroadcastBitSTDOUT);4574 BroadcastEventIfUnique(event_sp);4575}4576 4577void Process::AppendSTDERR(const char *s, size_t len) {4578 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4579 m_stderr_data.append(s, len);4580 auto event_sp = CreateEventFromProcessState(eBroadcastBitSTDERR);4581 BroadcastEventIfUnique(event_sp);4582}4583 4584void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {4585 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);4586 m_profile_data.push_back(one_profile_data);4587 auto event_sp = CreateEventFromProcessState(eBroadcastBitProfileData);4588 BroadcastEventIfUnique(event_sp);4589}4590 4591void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,4592 const StructuredDataPluginSP &plugin_sp) {4593 auto data_sp = std::make_shared<EventDataStructuredData>(4594 shared_from_this(), object_sp, plugin_sp);4595 BroadcastEvent(eBroadcastBitStructuredData, data_sp);4596}4597 4598StructuredDataPluginSP4599Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {4600 auto find_it = m_structured_data_plugin_map.find(type_name);4601 if (find_it != m_structured_data_plugin_map.end())4602 return find_it->second;4603 else4604 return StructuredDataPluginSP();4605}4606 4607size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {4608 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);4609 if (m_profile_data.empty())4610 return 0;4611 4612 std::string &one_profile_data = m_profile_data.front();4613 size_t bytes_available = one_profile_data.size();4614 if (bytes_available > 0) {4615 Log *log = GetLog(LLDBLog::Process);4616 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",4617 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4618 if (bytes_available > buf_size) {4619 memcpy(buf, one_profile_data.c_str(), buf_size);4620 one_profile_data.erase(0, buf_size);4621 bytes_available = buf_size;4622 } else {4623 memcpy(buf, one_profile_data.c_str(), bytes_available);4624 m_profile_data.erase(m_profile_data.begin());4625 }4626 }4627 return bytes_available;4628}4629 4630// Process STDIO4631 4632size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {4633 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);4634 size_t bytes_available = m_stdout_data.size();4635 if (bytes_available > 0) {4636 Log *log = GetLog(LLDBLog::Process);4637 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",4638 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4639 if (bytes_available > buf_size) {4640 memcpy(buf, m_stdout_data.c_str(), buf_size);4641 m_stdout_data.erase(0, buf_size);4642 bytes_available = buf_size;4643 } else {4644 memcpy(buf, m_stdout_data.c_str(), bytes_available);4645 m_stdout_data.clear();4646 }4647 }4648 return bytes_available;4649}4650 4651size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {4652 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);4653 size_t bytes_available = m_stderr_data.size();4654 if (bytes_available > 0) {4655 Log *log = GetLog(LLDBLog::Process);4656 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",4657 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));4658 if (bytes_available > buf_size) {4659 memcpy(buf, m_stderr_data.c_str(), buf_size);4660 m_stderr_data.erase(0, buf_size);4661 bytes_available = buf_size;4662 } else {4663 memcpy(buf, m_stderr_data.c_str(), bytes_available);4664 m_stderr_data.clear();4665 }4666 }4667 return bytes_available;4668}4669 4670void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,4671 size_t src_len) {4672 Process *process = (Process *)baton;4673 process->AppendSTDOUT(static_cast<const char *>(src), src_len);4674}4675 4676class IOHandlerProcessSTDIO : public IOHandler {4677public:4678 IOHandlerProcessSTDIO(Process *process, int write_fd)4679 : IOHandler(process->GetTarget().GetDebugger(),4680 IOHandler::Type::ProcessIO),4681 m_process(process),4682 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),4683 m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {4684 m_pipe.CreateNew();4685 }4686 4687 ~IOHandlerProcessSTDIO() override = default;4688 4689 void SetIsRunning(bool running) {4690 std::lock_guard<std::mutex> guard(m_mutex);4691 SetIsDone(!running);4692 m_is_running = running;4693 }4694 4695 // Each IOHandler gets to run until it is done. It should read data from the4696 // "in" and place output into "out" and "err and return when done.4697 void Run() override {4698 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||4699 !m_pipe.CanRead() || !m_pipe.CanWrite()) {4700 SetIsDone(true);4701 return;4702 }4703 4704 SetIsDone(false);4705 const int read_fd = m_read_file.GetDescriptor();4706 Terminal terminal(read_fd);4707 TerminalState terminal_state(terminal, false);4708 // FIXME: error handling?4709 llvm::consumeError(terminal.SetCanonical(false));4710 llvm::consumeError(terminal.SetEcho(false));4711// FD_ZERO, FD_SET are not supported on windows4712#ifndef _WIN324713 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();4714 SetIsRunning(true);4715 while (true) {4716 {4717 std::lock_guard<std::mutex> guard(m_mutex);4718 if (GetIsDone())4719 break;4720 }4721 4722 SelectHelper select_helper;4723 select_helper.FDSetRead(read_fd);4724 select_helper.FDSetRead(pipe_read_fd);4725 Status error = select_helper.Select();4726 4727 if (error.Fail())4728 break;4729 4730 char ch = 0;4731 size_t n;4732 if (select_helper.FDIsSetRead(read_fd)) {4733 n = 1;4734 if (m_read_file.Read(&ch, n).Success() && n == 1) {4735 if (m_write_file.Write(&ch, n).Fail() || n != 1)4736 break;4737 } else4738 break;4739 }4740 4741 if (select_helper.FDIsSetRead(pipe_read_fd)) {4742 // Consume the interrupt byte4743 if (llvm::Expected<size_t> bytes_read = m_pipe.Read(&ch, 1)) {4744 if (ch == 'q')4745 break;4746 if (ch == 'i')4747 if (StateIsRunningState(m_process->GetState()))4748 m_process->SendAsyncInterrupt();4749 } else {4750 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), bytes_read.takeError(),4751 "Pipe read failed: {0}");4752 }4753 }4754 }4755 SetIsRunning(false);4756#endif4757 }4758 4759 void Cancel() override {4760 std::lock_guard<std::mutex> guard(m_mutex);4761 SetIsDone(true);4762 // Only write to our pipe to cancel if we are in4763 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that4764 // is being run from the command interpreter:4765 //4766 // (lldb) step_process_thousands_of_times4767 //4768 // In this case the command interpreter will be in the middle of handling4769 // the command and if the process pushes and pops the IOHandler thousands4770 // of times, we can end up writing to m_pipe without ever consuming the4771 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up4772 // deadlocking when the pipe gets fed up and blocks until data is consumed.4773 if (m_is_running) {4774 char ch = 'q'; // Send 'q' for quit4775 if (llvm::Error err = m_pipe.Write(&ch, 1).takeError()) {4776 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), std::move(err),4777 "Pipe write failed: {0}");4778 }4779 }4780 }4781 4782 bool Interrupt() override {4783 // Do only things that are safe to do in an interrupt context (like in a4784 // SIGINT handler), like write 1 byte to a file descriptor. This will4785 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte4786 // that was written to the pipe and then call4787 // m_process->SendAsyncInterrupt() from a much safer location in code.4788 if (m_active) {4789 char ch = 'i'; // Send 'i' for interrupt4790 return !errorToBool(m_pipe.Write(&ch, 1).takeError());4791 } else {4792 // This IOHandler might be pushed on the stack, but not being run4793 // currently so do the right thing if we aren't actively watching for4794 // STDIN by sending the interrupt to the process. Otherwise the write to4795 // the pipe above would do nothing. This can happen when the command4796 // interpreter is running and gets a "expression ...". It will be on the4797 // IOHandler thread and sending the input is complete to the delegate4798 // which will cause the expression to run, which will push the process IO4799 // handler, but not run it.4800 4801 if (StateIsRunningState(m_process->GetState())) {4802 m_process->SendAsyncInterrupt();4803 return true;4804 }4805 }4806 return false;4807 }4808 4809 void GotEOF() override {}4810 4811protected:4812 Process *m_process;4813 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB4814 NativeFile m_write_file; // Write to this file (usually the primary pty for4815 // getting io to debuggee)4816 Pipe m_pipe;4817 std::mutex m_mutex;4818 bool m_is_running = false;4819};4820 4821void Process::SetSTDIOFileDescriptor(int fd) {4822 // First set up the Read Thread for reading/handling process I/O4823 m_stdio_communication.SetConnection(4824 std::make_unique<ConnectionFileDescriptor>(fd, true));4825 if (m_stdio_communication.IsConnected()) {4826 m_stdio_communication.SetReadThreadBytesReceivedCallback(4827 STDIOReadThreadBytesReceived, this);4828 m_stdio_communication.StartReadThread();4829 4830 // Now read thread is set up, set up input reader.4831 {4832 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4833 if (!m_process_input_reader)4834 m_process_input_reader =4835 std::make_shared<IOHandlerProcessSTDIO>(this, fd);4836 }4837 }4838}4839 4840bool Process::ProcessIOHandlerIsActive() {4841 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4842 IOHandlerSP io_handler_sp(m_process_input_reader);4843 if (io_handler_sp)4844 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);4845 return false;4846}4847 4848bool Process::PushProcessIOHandler() {4849 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4850 IOHandlerSP io_handler_sp(m_process_input_reader);4851 if (io_handler_sp) {4852 Log *log = GetLog(LLDBLog::Process);4853 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);4854 4855 io_handler_sp->SetIsDone(false);4856 // If we evaluate an utility function, then we don't cancel the current4857 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the4858 // existing IOHandler that potentially provides the user interface (e.g.4859 // the IOHandler for Editline).4860 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();4861 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,4862 cancel_top_handler);4863 return true;4864 }4865 return false;4866}4867 4868bool Process::PopProcessIOHandler() {4869 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);4870 IOHandlerSP io_handler_sp(m_process_input_reader);4871 if (io_handler_sp)4872 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);4873 return false;4874}4875 4876// The process needs to know about installed plug-ins4877void Process::SettingsInitialize() { Thread::SettingsInitialize(); }4878 4879void Process::SettingsTerminate() { Thread::SettingsTerminate(); }4880 4881namespace {4882// RestorePlanState is used to record the "is private", "is controlling" and4883// "okay4884// to discard" fields of the plan we are running, and reset it on Clean or on4885// destruction. It will only reset the state once, so you can call Clean and4886// then monkey with the state and it won't get reset on you again.4887 4888class RestorePlanState {4889public:4890 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)4891 : m_thread_plan_sp(thread_plan_sp) {4892 if (m_thread_plan_sp) {4893 m_private = m_thread_plan_sp->GetPrivate();4894 m_is_controlling = m_thread_plan_sp->IsControllingPlan();4895 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();4896 }4897 }4898 4899 ~RestorePlanState() { Clean(); }4900 4901 void Clean() {4902 if (!m_already_reset && m_thread_plan_sp) {4903 m_already_reset = true;4904 m_thread_plan_sp->SetPrivate(m_private);4905 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);4906 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);4907 }4908 }4909 4910private:4911 lldb::ThreadPlanSP m_thread_plan_sp;4912 bool m_already_reset = false;4913 bool m_private = false;4914 bool m_is_controlling = false;4915 bool m_okay_to_discard = false;4916};4917} // anonymous namespace4918 4919static microseconds4920GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {4921 const milliseconds default_one_thread_timeout(250);4922 4923 // If the overall wait is forever, then we don't need to worry about it.4924 if (!options.GetTimeout()) {4925 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()4926 : default_one_thread_timeout;4927 }4928 4929 // If the one thread timeout is set, use it.4930 if (options.GetOneThreadTimeout())4931 return *options.GetOneThreadTimeout();4932 4933 // Otherwise use half the total timeout, bounded by the4934 // default_one_thread_timeout.4935 return std::min<microseconds>(default_one_thread_timeout,4936 *options.GetTimeout() / 2);4937}4938 4939static Timeout<std::micro>4940GetExpressionTimeout(const EvaluateExpressionOptions &options,4941 bool before_first_timeout) {4942 // If we are going to run all threads the whole time, or if we are only going4943 // to run one thread, we can just return the overall timeout.4944 if (!options.GetStopOthers() || !options.GetTryAllThreads())4945 return options.GetTimeout();4946 4947 if (before_first_timeout)4948 return GetOneThreadExpressionTimeout(options);4949 4950 if (!options.GetTimeout())4951 return std::nullopt;4952 else4953 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);4954}4955 4956static std::optional<ExpressionResults>4957HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,4958 RestorePlanState &restorer, const EventSP &event_sp,4959 EventSP &event_to_broadcast_sp,4960 const EvaluateExpressionOptions &options,4961 bool handle_interrupts) {4962 Log *log = GetLog(LLDBLog::Step | LLDBLog::Process);4963 4964 ThreadSP thread_sp = thread_plan_sp->GetTarget()4965 .GetProcessSP()4966 ->GetThreadList()4967 .FindThreadByID(thread_id);4968 if (!thread_sp) {4969 LLDB_LOG(log,4970 "The thread on which we were running the "4971 "expression: tid = {0}, exited while "4972 "the expression was running.",4973 thread_id);4974 return eExpressionThreadVanished;4975 }4976 4977 ThreadPlanSP plan = thread_sp->GetCompletedPlan();4978 if (plan == thread_plan_sp && plan->PlanSucceeded()) {4979 LLDB_LOG(log, "execution completed successfully");4980 4981 // Restore the plan state so it will get reported as intended when we are4982 // done.4983 restorer.Clean();4984 return eExpressionCompleted;4985 }4986 4987 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();4988 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&4989 stop_info_sp->ShouldNotify(event_sp.get())) {4990 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());4991 if (!options.DoesIgnoreBreakpoints()) {4992 // Restore the plan state and then force Private to false. We are going4993 // to stop because of this plan so we need it to become a public plan or4994 // it won't report correctly when we continue to its termination later4995 // on.4996 restorer.Clean();4997 thread_plan_sp->SetPrivate(false);4998 event_to_broadcast_sp = event_sp;4999 }5000 return eExpressionHitBreakpoint;5001 }5002 5003 if (!handle_interrupts &&5004 Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))5005 return std::nullopt;5006 5007 LLDB_LOG(log, "thread plan did not successfully complete");5008 if (!options.DoesUnwindOnError())5009 event_to_broadcast_sp = event_sp;5010 return eExpressionInterrupted;5011}5012 5013ExpressionResults5014Process::RunThreadPlan(ExecutionContext &exe_ctx,5015 lldb::ThreadPlanSP &thread_plan_sp,5016 const EvaluateExpressionOptions &options,5017 DiagnosticManager &diagnostic_manager) {5018 ExpressionResults return_value = eExpressionSetupError;5019 5020 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);5021 5022 if (!thread_plan_sp) {5023 diagnostic_manager.PutString(5024 lldb::eSeverityError, "RunThreadPlan called with empty thread plan.");5025 return eExpressionSetupError;5026 }5027 5028 if (!thread_plan_sp->ValidatePlan(nullptr)) {5029 diagnostic_manager.PutString(5030 lldb::eSeverityError,5031 "RunThreadPlan called with an invalid thread plan.");5032 return eExpressionSetupError;5033 }5034 5035 if (exe_ctx.GetProcessPtr() != this) {5036 diagnostic_manager.PutString(lldb::eSeverityError,5037 "RunThreadPlan called on wrong process.");5038 return eExpressionSetupError;5039 }5040 5041 Thread *thread = exe_ctx.GetThreadPtr();5042 if (thread == nullptr) {5043 diagnostic_manager.PutString(lldb::eSeverityError,5044 "RunThreadPlan called with invalid thread.");5045 return eExpressionSetupError;5046 }5047 5048 // Record the thread's id so we can tell when a thread we were using5049 // to run the expression exits during the expression evaluation.5050 lldb::tid_t expr_thread_id = thread->GetID();5051 5052 // We need to change some of the thread plan attributes for the thread plan5053 // runner. This will restore them when we are done:5054 5055 RestorePlanState thread_plan_restorer(thread_plan_sp);5056 5057 // We rely on the thread plan we are running returning "PlanCompleted" if5058 // when it successfully completes. For that to be true the plan can't be5059 // private - since private plans suppress themselves in the GetCompletedPlan5060 // call.5061 5062 thread_plan_sp->SetPrivate(false);5063 5064 // The plans run with RunThreadPlan also need to be terminal controlling plans5065 // or when they are done we will end up asking the plan above us whether we5066 // should stop, which may give the wrong answer.5067 5068 thread_plan_sp->SetIsControllingPlan(true);5069 thread_plan_sp->SetOkayToDiscard(false);5070 5071 // If we are running some utility expression for LLDB, we now have to mark5072 // this in the ProcesModID of this process. This RAII takes care of marking5073 // and reverting the mark it once we are done running the expression.5074 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);5075 5076 if (m_private_state.GetValue() != eStateStopped) {5077 diagnostic_manager.PutString(5078 lldb::eSeverityError,5079 "RunThreadPlan called while the private state was not stopped.");5080 return eExpressionSetupError;5081 }5082 5083 // Save the thread & frame from the exe_ctx for restoration after we run5084 const uint32_t thread_idx_id = thread->GetIndexID();5085 StackFrameSP selected_frame_sp =5086 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);5087 if (!selected_frame_sp) {5088 thread->SetSelectedFrame(nullptr);5089 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);5090 if (!selected_frame_sp) {5091 diagnostic_manager.Printf(5092 lldb::eSeverityError,5093 "RunThreadPlan called without a selected frame on thread %d",5094 thread_idx_id);5095 return eExpressionSetupError;5096 }5097 }5098 5099 // Make sure the timeout values make sense. The one thread timeout needs to5100 // be smaller than the overall timeout.5101 if (options.GetOneThreadTimeout() && options.GetTimeout() &&5102 *options.GetTimeout() < *options.GetOneThreadTimeout()) {5103 diagnostic_manager.PutString(lldb::eSeverityError,5104 "RunThreadPlan called with one thread "5105 "timeout greater than total timeout");5106 return eExpressionSetupError;5107 }5108 5109 // If the ExecutionContext has a frame, we want to make sure to save/restore5110 // that frame into exe_ctx. This can happen when we run expressions from a5111 // non-selected SBFrame, in which case we don't want some thread-plan5112 // to overwrite the ExecutionContext frame.5113 StackID ctx_frame_id = exe_ctx.HasFrameScope()5114 ? exe_ctx.GetFrameRef().GetStackID()5115 : selected_frame_sp->GetStackID();5116 5117 // N.B. Running the target may unset the currently selected thread and frame.5118 // We don't want to do that either, so we should arrange to reset them as5119 // well.5120 5121 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();5122 5123 uint32_t selected_tid;5124 StackID selected_stack_id;5125 if (selected_thread_sp) {5126 selected_tid = selected_thread_sp->GetIndexID();5127 selected_stack_id =5128 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)5129 ->GetStackID();5130 } else {5131 selected_tid = LLDB_INVALID_THREAD_ID;5132 }5133 5134 HostThread backup_private_state_thread;5135 lldb::StateType old_state = eStateInvalid;5136 lldb::ThreadPlanSP stopper_base_plan_sp;5137 5138 Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));5139 if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {5140 // Yikes, we are running on the private state thread! So we can't wait for5141 // public events on this thread, since we are the thread that is generating5142 // public events. The simplest thing to do is to spin up a temporary thread5143 // to handle private state thread events while we are fielding public5144 // events here.5145 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "5146 "another state thread to handle the events.");5147 5148 backup_private_state_thread = m_private_state_thread;5149 5150 // One other bit of business: we want to run just this thread plan and5151 // anything it pushes, and then stop, returning control here. But in the5152 // normal course of things, the plan above us on the stack would be given a5153 // shot at the stop event before deciding to stop, and we don't want that.5154 // So we insert a "stopper" base plan on the stack before the plan we want5155 // to run. Since base plans always stop and return control to the user,5156 // that will do just what we want.5157 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));5158 thread->QueueThreadPlan(stopper_base_plan_sp, false);5159 // Have to make sure our public state is stopped, since otherwise the5160 // reporting logic below doesn't work correctly.5161 old_state = m_public_state.GetValue();5162 m_public_state.SetValueNoLock(eStateStopped);5163 5164 // Now spin up the private state thread:5165 StartPrivateStateThread(true);5166 }5167 5168 thread->QueueThreadPlan(5169 thread_plan_sp, false); // This used to pass "true" does that make sense?5170 5171 if (options.GetDebug()) {5172 // In this case, we aren't actually going to run, we just want to stop5173 // right away. Flush this thread so we will refetch the stacks and show the5174 // correct backtrace.5175 // FIXME: To make this prettier we should invent some stop reason for this,5176 // but that5177 // is only cosmetic, and this functionality is only of use to lldb5178 // developers who can live with not pretty...5179 thread->Flush();5180 return eExpressionStoppedForDebug;5181 }5182 5183 ListenerSP listener_sp(5184 Listener::MakeListener("lldb.process.listener.run-thread-plan"));5185 5186 lldb::EventSP event_to_broadcast_sp;5187 5188 {5189 // This process event hijacker Hijacks the Public events and its destructor5190 // makes sure that the process events get restored on exit to the function.5191 //5192 // If the event needs to propagate beyond the hijacker (e.g., the process5193 // exits during execution), then the event is put into5194 // event_to_broadcast_sp for rebroadcasting.5195 5196 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);5197 5198 if (log) {5199 StreamString s;5200 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);5201 LLDB_LOGF(log,5202 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx645203 " to run thread plan \"%s\".",5204 thread_idx_id, expr_thread_id, s.GetData());5205 }5206 5207 bool got_event;5208 lldb::EventSP event_sp;5209 lldb::StateType stop_state = lldb::eStateInvalid;5210 5211 bool before_first_timeout = true; // This is set to false the first time5212 // that we have to halt the target.5213 bool do_resume = true;5214 bool handle_running_event = true;5215 5216 // This is just for accounting:5217 uint32_t num_resumes = 0;5218 5219 // If we are going to run all threads the whole time, or if we are only5220 // going to run one thread, then we don't need the first timeout. So we5221 // pretend we are after the first timeout already.5222 if (!options.GetStopOthers() || !options.GetTryAllThreads())5223 before_first_timeout = false;5224 5225 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",5226 options.GetStopOthers(), options.GetTryAllThreads(),5227 before_first_timeout);5228 5229 // This isn't going to work if there are unfetched events on the queue. Are5230 // there cases where we might want to run the remaining events here, and5231 // then try to call the function? That's probably being too tricky for our5232 // own good.5233 5234 Event *other_events = listener_sp->PeekAtNextEvent();5235 if (other_events != nullptr) {5236 diagnostic_manager.PutString(5237 lldb::eSeverityError,5238 "RunThreadPlan called with pending events on the queue.");5239 return eExpressionSetupError;5240 }5241 5242 // We also need to make sure that the next event is delivered. We might be5243 // calling a function as part of a thread plan, in which case the last5244 // delivered event could be the running event, and we don't want event5245 // coalescing to cause us to lose OUR running event...5246 ForceNextEventDelivery();5247 5248// This while loop must exit out the bottom, there's cleanup that we need to do5249// when we are done. So don't call return anywhere within it.5250 5251#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT5252 // It's pretty much impossible to write test cases for things like: One5253 // thread timeout expires, I go to halt, but the process already stopped on5254 // the function call stop breakpoint. Turning on this define will make us5255 // not fetch the first event till after the halt. So if you run a quick5256 // function, it will have completed, and the completion event will be5257 // waiting, when you interrupt for halt. The expression evaluation should5258 // still succeed.5259 bool miss_first_event = true;5260#endif5261 while (true) {5262 // We usually want to resume the process if we get to the top of the5263 // loop. The only exception is if we get two running events with no5264 // intervening stop, which can happen, we will just wait for then next5265 // stop event.5266 LLDB_LOGF(log,5267 "Top of while loop: do_resume: %i handle_running_event: %i "5268 "before_first_timeout: %i.",5269 do_resume, handle_running_event, before_first_timeout);5270 5271 if (do_resume || handle_running_event) {5272 // Do the initial resume and wait for the running event before going5273 // further.5274 5275 if (do_resume) {5276 num_resumes++;5277 Status resume_error = PrivateResume();5278 if (!resume_error.Success()) {5279 diagnostic_manager.Printf(5280 lldb::eSeverityError,5281 "couldn't resume inferior the %d time: \"%s\".", num_resumes,5282 resume_error.AsCString());5283 return_value = eExpressionSetupError;5284 break;5285 }5286 }5287 5288 got_event =5289 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());5290 if (!got_event) {5291 LLDB_LOGF(log,5292 "Process::RunThreadPlan(): didn't get any event after "5293 "resume %" PRIu32 ", exiting.",5294 num_resumes);5295 5296 diagnostic_manager.Printf(lldb::eSeverityError,5297 "didn't get any event after resume %" PRIu325298 ", exiting.",5299 num_resumes);5300 return_value = eExpressionSetupError;5301 break;5302 }5303 5304 stop_state =5305 Process::ProcessEventData::GetStateFromEvent(event_sp.get());5306 5307 if (stop_state != eStateRunning) {5308 bool restarted = false;5309 5310 if (stop_state == eStateStopped) {5311 restarted = Process::ProcessEventData::GetRestartedFromEvent(5312 event_sp.get());5313 LLDB_LOGF(5314 log,5315 "Process::RunThreadPlan(): didn't get running event after "5316 "resume %d, got %s instead (restarted: %i, do_resume: %i, "5317 "handle_running_event: %i).",5318 num_resumes, StateAsCString(stop_state), restarted, do_resume,5319 handle_running_event);5320 }5321 5322 if (restarted) {5323 // This is probably an overabundance of caution, I don't think I5324 // should ever get a stopped & restarted event here. But if I do,5325 // the best thing is to Halt and then get out of here.5326 const bool clear_thread_plans = false;5327 const bool use_run_lock = false;5328 Halt(clear_thread_plans, use_run_lock);5329 }5330 5331 diagnostic_manager.Printf(5332 lldb::eSeverityError,5333 "didn't get running event after initial resume, got %s instead.",5334 StateAsCString(stop_state));5335 return_value = eExpressionSetupError;5336 break;5337 }5338 5339 if (log)5340 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");5341 // We need to call the function synchronously, so spin waiting for it5342 // to return. If we get interrupted while executing, we're going to5343 // lose our context, and won't be able to gather the result at this5344 // point. We set the timeout AFTER the resume, since the resume takes5345 // some time and we don't want to charge that to the timeout.5346 } else {5347 if (log)5348 log->PutCString("Process::RunThreadPlan(): waiting for next event.");5349 }5350 5351 do_resume = true;5352 handle_running_event = true;5353 5354 // Now wait for the process to stop again:5355 event_sp.reset();5356 5357 Timeout<std::micro> timeout =5358 GetExpressionTimeout(options, before_first_timeout);5359 if (log) {5360 if (timeout) {5361 auto now = system_clock::now();5362 LLDB_LOGF(log,5363 "Process::RunThreadPlan(): about to wait - now is %s - "5364 "endpoint is %s",5365 llvm::to_string(now).c_str(),5366 llvm::to_string(now + *timeout).c_str());5367 } else {5368 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");5369 }5370 }5371 5372#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT5373 // See comment above...5374 if (miss_first_event) {5375 std::this_thread::sleep_for(std::chrono::milliseconds(1));5376 miss_first_event = false;5377 got_event = false;5378 } else5379#endif5380 got_event = listener_sp->GetEvent(event_sp, timeout);5381 5382 if (got_event) {5383 if (event_sp) {5384 bool keep_going = false;5385 if (event_sp->GetType() == eBroadcastBitInterrupt) {5386 const bool clear_thread_plans = false;5387 const bool use_run_lock = false;5388 Halt(clear_thread_plans, use_run_lock);5389 return_value = eExpressionInterrupted;5390 diagnostic_manager.PutString(lldb::eSeverityInfo,5391 "execution halted by user interrupt.");5392 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "5393 "eBroadcastBitInterrupted, exiting.");5394 break;5395 } else {5396 stop_state =5397 Process::ProcessEventData::GetStateFromEvent(event_sp.get());5398 LLDB_LOGF(log,5399 "Process::RunThreadPlan(): in while loop, got event: %s.",5400 StateAsCString(stop_state));5401 5402 switch (stop_state) {5403 case lldb::eStateStopped: {5404 if (Process::ProcessEventData::GetRestartedFromEvent(5405 event_sp.get())) {5406 // If we were restarted, we just need to go back up to fetch5407 // another event.5408 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "5409 "restart, so we'll continue waiting.");5410 keep_going = true;5411 do_resume = false;5412 handle_running_event = true;5413 } else {5414 const bool handle_interrupts = true;5415 return_value = *HandleStoppedEvent(5416 expr_thread_id, thread_plan_sp, thread_plan_restorer,5417 event_sp, event_to_broadcast_sp, options,5418 handle_interrupts);5419 if (return_value == eExpressionThreadVanished)5420 keep_going = false;5421 }5422 } break;5423 5424 case lldb::eStateRunning:5425 // This shouldn't really happen, but sometimes we do get two5426 // running events without an intervening stop, and in that case5427 // we should just go back to waiting for the stop.5428 do_resume = false;5429 keep_going = true;5430 handle_running_event = false;5431 break;5432 5433 default:5434 LLDB_LOGF(log,5435 "Process::RunThreadPlan(): execution stopped with "5436 "unexpected state: %s.",5437 StateAsCString(stop_state));5438 5439 if (stop_state == eStateExited)5440 event_to_broadcast_sp = event_sp;5441 5442 diagnostic_manager.PutString(5443 lldb::eSeverityError,5444 "execution stopped with unexpected state.");5445 return_value = eExpressionInterrupted;5446 break;5447 }5448 }5449 5450 if (keep_going)5451 continue;5452 else5453 break;5454 } else {5455 if (log)5456 log->PutCString("Process::RunThreadPlan(): got_event was true, but "5457 "the event pointer was null. How odd...");5458 return_value = eExpressionInterrupted;5459 break;5460 }5461 } else {5462 // If we didn't get an event that means we've timed out... We will5463 // interrupt the process here. Depending on what we were asked to do5464 // we will either exit, or try with all threads running for the same5465 // timeout.5466 5467 if (log) {5468 if (options.GetTryAllThreads()) {5469 if (before_first_timeout) {5470 LLDB_LOG(log,5471 "Running function with one thread timeout timed out.");5472 } else5473 LLDB_LOG(log, "Restarting function with all threads enabled and "5474 "timeout: {0} timed out, abandoning execution.",5475 timeout);5476 } else5477 LLDB_LOG(log, "Running function with timeout: {0} timed out, "5478 "abandoning execution.",5479 timeout);5480 }5481 5482 // It is possible that between the time we issued the Halt, and we get5483 // around to calling Halt the target could have stopped. That's fine,5484 // Halt will figure that out and send the appropriate Stopped event.5485 // BUT it is also possible that we stopped & restarted (e.g. hit a5486 // signal with "stop" set to false.) In5487 // that case, we'll get the stopped & restarted event, and we should go5488 // back to waiting for the Halt's stopped event. That's what this5489 // while loop does.5490 5491 bool back_to_top = true;5492 uint32_t try_halt_again = 0;5493 bool do_halt = true;5494 const uint32_t num_retries = 5;5495 while (try_halt_again < num_retries) {5496 Status halt_error;5497 if (do_halt) {5498 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");5499 const bool clear_thread_plans = false;5500 const bool use_run_lock = false;5501 Halt(clear_thread_plans, use_run_lock);5502 }5503 if (halt_error.Success()) {5504 if (log)5505 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");5506 5507 got_event =5508 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());5509 5510 if (got_event) {5511 stop_state =5512 Process::ProcessEventData::GetStateFromEvent(event_sp.get());5513 if (log) {5514 LLDB_LOGF(log,5515 "Process::RunThreadPlan(): Stopped with event: %s",5516 StateAsCString(stop_state));5517 if (stop_state == lldb::eStateStopped &&5518 Process::ProcessEventData::GetInterruptedFromEvent(5519 event_sp.get()))5520 log->PutCString(" Event was the Halt interruption event.");5521 }5522 5523 if (stop_state == lldb::eStateStopped) {5524 if (Process::ProcessEventData::GetRestartedFromEvent(5525 event_sp.get())) {5526 if (log)5527 log->PutCString("Process::RunThreadPlan(): Went to halt "5528 "but got a restarted event, there must be "5529 "an un-restarted stopped event so try "5530 "again... "5531 "Exiting wait loop.");5532 try_halt_again++;5533 do_halt = false;5534 continue;5535 }5536 5537 // Between the time we initiated the Halt and the time we5538 // delivered it, the process could have already finished its5539 // job. Check that here:5540 const bool handle_interrupts = false;5541 if (auto result = HandleStoppedEvent(5542 expr_thread_id, thread_plan_sp, thread_plan_restorer,5543 event_sp, event_to_broadcast_sp, options,5544 handle_interrupts)) {5545 return_value = *result;5546 back_to_top = false;5547 break;5548 }5549 5550 if (!options.GetTryAllThreads()) {5551 if (log)5552 log->PutCString("Process::RunThreadPlan(): try_all_threads "5553 "was false, we stopped so now we're "5554 "quitting.");5555 return_value = eExpressionInterrupted;5556 back_to_top = false;5557 break;5558 }5559 5560 if (before_first_timeout) {5561 // Set all the other threads to run, and return to the top of5562 // the loop, which will continue;5563 before_first_timeout = false;5564 thread_plan_sp->SetStopOthers(false);5565 if (log)5566 log->PutCString(5567 "Process::RunThreadPlan(): about to resume.");5568 5569 back_to_top = true;5570 break;5571 } else {5572 // Running all threads failed, so return Interrupted.5573 if (log)5574 log->PutCString("Process::RunThreadPlan(): running all "5575 "threads timed out.");5576 return_value = eExpressionInterrupted;5577 back_to_top = false;5578 break;5579 }5580 }5581 } else {5582 if (log)5583 log->PutCString("Process::RunThreadPlan(): halt said it "5584 "succeeded, but I got no event. "5585 "I'm getting out of here passing Interrupted.");5586 return_value = eExpressionInterrupted;5587 back_to_top = false;5588 break;5589 }5590 } else {5591 try_halt_again++;5592 continue;5593 }5594 }5595 5596 if (!back_to_top || try_halt_again > num_retries)5597 break;5598 else5599 continue;5600 }5601 } // END WAIT LOOP5602 5603 // If we had to start up a temporary private state thread to run this5604 // thread plan, shut it down now.5605 if (backup_private_state_thread.IsJoinable()) {5606 StopPrivateStateThread();5607 Status error;5608 m_private_state_thread = backup_private_state_thread;5609 if (stopper_base_plan_sp) {5610 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);5611 }5612 if (old_state != eStateInvalid)5613 m_public_state.SetValueNoLock(old_state);5614 }5615 5616 // If our thread went away on us, we need to get out of here without5617 // doing any more work. We don't have to clean up the thread plan, that5618 // will have happened when the Thread was destroyed.5619 if (return_value == eExpressionThreadVanished) {5620 return return_value;5621 }5622 5623 if (return_value != eExpressionCompleted && log) {5624 // Print a backtrace into the log so we can figure out where we are:5625 StreamString s;5626 s.PutCString("Thread state after unsuccessful completion: \n");5627 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX,5628 /*show_hidden*/ true);5629 log->PutString(s.GetString());5630 }5631 // Restore the thread state if we are going to discard the plan execution.5632 // There are three cases where this could happen: 1) The execution5633 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints5634 // was true 3) We got some other error, and discard_on_error was true5635 bool should_unwind = (return_value == eExpressionInterrupted &&5636 options.DoesUnwindOnError()) ||5637 (return_value == eExpressionHitBreakpoint &&5638 options.DoesIgnoreBreakpoints());5639 5640 if (return_value == eExpressionCompleted || should_unwind) {5641 thread_plan_sp->RestoreThreadState();5642 }5643 5644 // Now do some processing on the results of the run:5645 if (return_value == eExpressionInterrupted ||5646 return_value == eExpressionHitBreakpoint) {5647 if (log) {5648 StreamString s;5649 if (event_sp)5650 event_sp->Dump(&s);5651 else {5652 log->PutCString("Process::RunThreadPlan(): Stop event that "5653 "interrupted us is NULL.");5654 }5655 5656 StreamString ts;5657 5658 const char *event_explanation = nullptr;5659 5660 do {5661 if (!event_sp) {5662 event_explanation = "<no event>";5663 break;5664 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {5665 event_explanation = "<user interrupt>";5666 break;5667 } else {5668 const Process::ProcessEventData *event_data =5669 Process::ProcessEventData::GetEventDataFromEvent(5670 event_sp.get());5671 5672 if (!event_data) {5673 event_explanation = "<no event data>";5674 break;5675 }5676 5677 Process *process = event_data->GetProcessSP().get();5678 5679 if (!process) {5680 event_explanation = "<no process>";5681 break;5682 }5683 5684 ThreadList &thread_list = process->GetThreadList();5685 5686 uint32_t num_threads = thread_list.GetSize();5687 uint32_t thread_index;5688 5689 ts.Printf("<%u threads> ", num_threads);5690 5691 for (thread_index = 0; thread_index < num_threads; ++thread_index) {5692 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();5693 5694 if (!thread) {5695 ts.Printf("<?> ");5696 continue;5697 }5698 5699 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());5700 RegisterContext *register_context =5701 thread->GetRegisterContext().get();5702 5703 if (register_context)5704 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());5705 else5706 ts.Printf("[ip unknown] ");5707 5708 // Show the private stop info here, the public stop info will be5709 // from the last natural stop.5710 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();5711 if (stop_info_sp) {5712 const char *stop_desc = stop_info_sp->GetDescription();5713 if (stop_desc)5714 ts.PutCString(stop_desc);5715 }5716 ts.Printf(">");5717 }5718 5719 event_explanation = ts.GetData();5720 }5721 } while (false);5722 5723 if (event_explanation)5724 LLDB_LOGF(log,5725 "Process::RunThreadPlan(): execution interrupted: %s %s",5726 s.GetData(), event_explanation);5727 else5728 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",5729 s.GetData());5730 }5731 5732 if (should_unwind) {5733 LLDB_LOGF(log,5734 "Process::RunThreadPlan: ExecutionInterrupted - "5735 "discarding thread plans up to %p.",5736 static_cast<void *>(thread_plan_sp.get()));5737 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5738 } else {5739 LLDB_LOGF(log,5740 "Process::RunThreadPlan: ExecutionInterrupted - for "5741 "plan: %p not discarding.",5742 static_cast<void *>(thread_plan_sp.get()));5743 }5744 } else if (return_value == eExpressionSetupError) {5745 if (log)5746 log->PutCString("Process::RunThreadPlan(): execution set up error.");5747 5748 if (options.DoesUnwindOnError()) {5749 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5750 }5751 } else {5752 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {5753 if (log)5754 log->PutCString("Process::RunThreadPlan(): thread plan is done");5755 return_value = eExpressionCompleted;5756 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {5757 if (log)5758 log->PutCString(5759 "Process::RunThreadPlan(): thread plan was discarded");5760 return_value = eExpressionDiscarded;5761 } else {5762 if (log)5763 log->PutCString(5764 "Process::RunThreadPlan(): thread plan stopped in mid course");5765 if (options.DoesUnwindOnError() && thread_plan_sp) {5766 if (log)5767 log->PutCString("Process::RunThreadPlan(): discarding thread plan "5768 "'cause unwind_on_error is set.");5769 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);5770 }5771 }5772 }5773 5774 // Thread we ran the function in may have gone away because we ran the5775 // target Check that it's still there, and if it is put it back in the5776 // context. Also restore the frame in the context if it is still present.5777 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();5778 if (thread) {5779 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));5780 }5781 5782 // Also restore the current process'es selected frame & thread, since this5783 // function calling may be done behind the user's back.5784 5785 if (selected_tid != LLDB_INVALID_THREAD_ID) {5786 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&5787 selected_stack_id.IsValid()) {5788 // We were able to restore the selected thread, now restore the frame:5789 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());5790 StackFrameSP old_frame_sp =5791 GetThreadList().GetSelectedThread()->GetFrameWithStackID(5792 selected_stack_id);5793 if (old_frame_sp)5794 GetThreadList().GetSelectedThread()->SetSelectedFrame(5795 old_frame_sp.get());5796 }5797 }5798 }5799 5800 // If the process exited during the run of the thread plan, notify everyone.5801 5802 if (event_to_broadcast_sp) {5803 if (log)5804 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");5805 BroadcastEvent(event_to_broadcast_sp);5806 }5807 5808 return return_value;5809}5810 5811void Process::GetStatus(Stream &strm) {5812 const StateType state = GetState();5813 if (StateIsStoppedState(state, false)) {5814 if (state == eStateExited) {5815 int exit_status = GetExitStatus();5816 const char *exit_description = GetExitDescription();5817 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",5818 GetID(), exit_status, exit_status,5819 exit_description ? exit_description : "");5820 } else {5821 if (state == eStateConnected)5822 strm.Printf("Connected to remote target.\n");5823 else5824 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));5825 }5826 } else {5827 strm.Printf("Process %" PRIu64 " is running.\n", GetID());5828 }5829}5830 5831size_t Process::GetThreadStatus(Stream &strm,5832 bool only_threads_with_stop_reason,5833 uint32_t start_frame, uint32_t num_frames,5834 uint32_t num_frames_with_source,5835 bool stop_format) {5836 size_t num_thread_infos_dumped = 0;5837 5838 // You can't hold the thread list lock while calling Thread::GetStatus. That5839 // very well might run code (e.g. if we need it to get return values or5840 // arguments.) For that to work the process has to be able to acquire it.5841 // So instead copy the thread ID's, and look them up one by one:5842 5843 uint32_t num_threads;5844 std::vector<lldb::tid_t> thread_id_array;5845 // Scope for thread list locker;5846 {5847 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());5848 ThreadList &curr_thread_list = GetThreadList();5849 num_threads = curr_thread_list.GetSize();5850 uint32_t idx;5851 thread_id_array.resize(num_threads);5852 for (idx = 0; idx < num_threads; ++idx)5853 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();5854 }5855 5856 for (uint32_t i = 0; i < num_threads; i++) {5857 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));5858 if (thread_sp) {5859 if (only_threads_with_stop_reason) {5860 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();5861 if (!stop_info_sp || !stop_info_sp->ShouldShow())5862 continue;5863 }5864 thread_sp->GetStatus(strm, start_frame, num_frames,5865 num_frames_with_source, stop_format,5866 /*show_hidden*/ num_frames <= 1);5867 ++num_thread_infos_dumped;5868 } else {5869 Log *log = GetLog(LLDBLog::Process);5870 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu645871 " vanished while running Thread::GetStatus.");5872 }5873 }5874 return num_thread_infos_dumped;5875}5876 5877void Process::AddInvalidMemoryRegion(const LoadRange ®ion) {5878 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());5879}5880 5881bool Process::RemoveInvalidMemoryRange(const LoadRange ®ion) {5882 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),5883 region.GetByteSize());5884}5885 5886void Process::AddPreResumeAction(PreResumeActionCallback callback,5887 void *baton) {5888 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));5889}5890 5891bool Process::RunPreResumeActions() {5892 bool result = true;5893 while (!m_pre_resume_actions.empty()) {5894 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();5895 m_pre_resume_actions.pop_back();5896 bool this_result = action.callback(action.baton);5897 if (result)5898 result = this_result;5899 }5900 return result;5901}5902 5903void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }5904 5905void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)5906{5907 PreResumeCallbackAndBaton element(callback, baton);5908 auto found_iter = llvm::find(m_pre_resume_actions, element);5909 if (found_iter != m_pre_resume_actions.end())5910 {5911 m_pre_resume_actions.erase(found_iter);5912 }5913}5914 5915ProcessRunLock &Process::GetRunLock() {5916 if (Process::CurrentThreadIsPrivateStateThread())5917 return m_private_run_lock;5918 return m_public_run_lock;5919}5920 5921bool Process::CurrentThreadIsPrivateStateThread()5922{5923 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());5924}5925 5926bool Process::CurrentThreadPosesAsPrivateStateThread() {5927 // If we haven't started up the private state thread yet, then whatever thread5928 // is fetching this event should be temporarily the private state thread.5929 if (!m_private_state_thread.HasThread())5930 return true;5931 return m_private_state_thread.EqualsThread(Host::GetCurrentThread());5932}5933 5934void Process::Flush() {5935 m_thread_list.Flush();5936 m_extended_thread_list.Flush();5937 m_extended_thread_stop_id = 0;5938 m_queue_list.Clear();5939 m_queue_list_stop_id = 0;5940}5941 5942lldb::addr_t Process::GetCodeAddressMask() {5943 if (uint32_t num_bits_setting = GetVirtualAddressableBits())5944 return AddressableBits::AddressableBitToMask(num_bits_setting);5945 5946 return m_code_address_mask;5947}5948 5949lldb::addr_t Process::GetDataAddressMask() {5950 if (uint32_t num_bits_setting = GetVirtualAddressableBits())5951 return AddressableBits::AddressableBitToMask(num_bits_setting);5952 5953 return m_data_address_mask;5954}5955 5956lldb::addr_t Process::GetHighmemCodeAddressMask() {5957 if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())5958 return AddressableBits::AddressableBitToMask(num_bits_setting);5959 5960 if (m_highmem_code_address_mask != LLDB_INVALID_ADDRESS_MASK)5961 return m_highmem_code_address_mask;5962 return GetCodeAddressMask();5963}5964 5965lldb::addr_t Process::GetHighmemDataAddressMask() {5966 if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())5967 return AddressableBits::AddressableBitToMask(num_bits_setting);5968 5969 if (m_highmem_data_address_mask != LLDB_INVALID_ADDRESS_MASK)5970 return m_highmem_data_address_mask;5971 return GetDataAddressMask();5972}5973 5974void Process::SetCodeAddressMask(lldb::addr_t code_address_mask) {5975 LLDB_LOG(GetLog(LLDBLog::Process),5976 "Setting Process code address mask to {0:x}", code_address_mask);5977 m_code_address_mask = code_address_mask;5978}5979 5980void Process::SetDataAddressMask(lldb::addr_t data_address_mask) {5981 LLDB_LOG(GetLog(LLDBLog::Process),5982 "Setting Process data address mask to {0:x}", data_address_mask);5983 m_data_address_mask = data_address_mask;5984}5985 5986void Process::SetHighmemCodeAddressMask(lldb::addr_t code_address_mask) {5987 LLDB_LOG(GetLog(LLDBLog::Process),5988 "Setting Process highmem code address mask to {0:x}",5989 code_address_mask);5990 m_highmem_code_address_mask = code_address_mask;5991}5992 5993void Process::SetHighmemDataAddressMask(lldb::addr_t data_address_mask) {5994 LLDB_LOG(GetLog(LLDBLog::Process),5995 "Setting Process highmem data address mask to {0:x}",5996 data_address_mask);5997 m_highmem_data_address_mask = data_address_mask;5998}5999 6000addr_t Process::FixCodeAddress(addr_t addr) {6001 if (ABISP abi_sp = GetABI())6002 addr = abi_sp->FixCodeAddress(addr);6003 return addr;6004}6005 6006addr_t Process::FixDataAddress(addr_t addr) {6007 if (ABISP abi_sp = GetABI())6008 addr = abi_sp->FixDataAddress(addr);6009 return addr;6010}6011 6012addr_t Process::FixAnyAddress(addr_t addr) {6013 if (ABISP abi_sp = GetABI())6014 addr = abi_sp->FixAnyAddress(addr);6015 return addr;6016}6017 6018void Process::DidExec() {6019 Log *log = GetLog(LLDBLog::Process);6020 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);6021 6022 Target &target = GetTarget();6023 target.CleanupProcess();6024 target.ClearModules(false);6025 m_dynamic_checkers_up.reset();6026 m_abi_sp.reset();6027 m_system_runtime_up.reset();6028 m_os_up.reset();6029 m_dyld_up.reset();6030 m_jit_loaders_up.reset();6031 m_image_tokens.clear();6032 // After an exec, the inferior is a new process and these memory regions are6033 // no longer allocated.6034 m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);6035 {6036 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);6037 m_language_runtimes.clear();6038 }6039 m_instrumentation_runtimes.clear();6040 m_thread_list.DiscardThreadPlans();6041 m_memory_cache.Clear(true);6042 DoDidExec();6043 CompleteAttach();6044 // Flush the process (threads and all stack frames) after running6045 // CompleteAttach() in case the dynamic loader loaded things in new6046 // locations.6047 Flush();6048 6049 // After we figure out what was loaded/unloaded in CompleteAttach, we need to6050 // let the target know so it can do any cleanup it needs to.6051 target.DidExec();6052}6053 6054addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {6055 if (address == nullptr) {6056 error = Status::FromErrorString("Invalid address argument");6057 return LLDB_INVALID_ADDRESS;6058 }6059 6060 addr_t function_addr = LLDB_INVALID_ADDRESS;6061 6062 addr_t addr = address->GetLoadAddress(&GetTarget());6063 std::map<addr_t, addr_t>::const_iterator iter =6064 m_resolved_indirect_addresses.find(addr);6065 if (iter != m_resolved_indirect_addresses.end()) {6066 function_addr = (*iter).second;6067 } else {6068 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {6069 Symbol *symbol = address->CalculateSymbolContextSymbol();6070 error = Status::FromErrorStringWithFormat(6071 "Unable to call resolver for indirect function %s",6072 symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");6073 function_addr = LLDB_INVALID_ADDRESS;6074 } else {6075 if (ABISP abi_sp = GetABI())6076 function_addr = abi_sp->FixCodeAddress(function_addr);6077 m_resolved_indirect_addresses.insert(6078 std::pair<addr_t, addr_t>(addr, function_addr));6079 }6080 }6081 return function_addr;6082}6083 6084void Process::ModulesDidLoad(ModuleList &module_list) {6085 // Inform the system runtime of the modified modules.6086 SystemRuntime *sys_runtime = GetSystemRuntime();6087 if (sys_runtime)6088 sys_runtime->ModulesDidLoad(module_list);6089 6090 GetJITLoaders().ModulesDidLoad(module_list);6091 6092 // Give the instrumentation runtimes a chance to be created before informing6093 // them of the modified modules.6094 InstrumentationRuntime::ModulesDidLoad(module_list, this,6095 m_instrumentation_runtimes);6096 for (auto &runtime : m_instrumentation_runtimes)6097 runtime.second->ModulesDidLoad(module_list);6098 6099 // Give the language runtimes a chance to be created before informing them of6100 // the modified modules.6101 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {6102 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))6103 runtime->ModulesDidLoad(module_list);6104 }6105 6106 // If we don't have an operating system plug-in, try to load one since6107 // loading shared libraries might cause a new one to try and load6108 if (!m_os_up)6109 LoadOperatingSystemPlugin(false);6110 6111 // Inform the structured-data plugins of the modified modules.6112 for (auto &pair : m_structured_data_plugin_map) {6113 if (pair.second)6114 pair.second->ModulesDidLoad(*this, module_list);6115 }6116}6117 6118void Process::PrintWarningOptimization(const SymbolContext &sc) {6119 if (!GetWarningsOptimization())6120 return;6121 if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())6122 return;6123 sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());6124}6125 6126void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {6127 if (!GetWarningsUnsupportedLanguage())6128 return;6129 if (!sc.module_sp)6130 return;6131 LanguageType language = sc.GetLanguage();6132 if (language == eLanguageTypeUnknown ||6133 language == lldb::eLanguageTypeAssembly ||6134 language == lldb::eLanguageTypeMipsAssembler)6135 return;6136 LanguageSet plugins =6137 PluginManager::GetAllTypeSystemSupportedLanguagesForTypes();6138 if (plugins[language])6139 return;6140 sc.module_sp->ReportWarningUnsupportedLanguage(6141 language, GetTarget().GetDebugger().GetID());6142}6143 6144bool Process::GetProcessInfo(ProcessInstanceInfo &info) {6145 info.Clear();6146 6147 PlatformSP platform_sp = GetTarget().GetPlatform();6148 if (!platform_sp)6149 return false;6150 6151 return platform_sp->GetProcessInfo(GetID(), info);6152}6153 6154lldb_private::UUID Process::FindModuleUUID(const llvm::StringRef path) {6155 return lldb_private::UUID();6156}6157 6158ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {6159 ThreadCollectionSP threads;6160 6161 const MemoryHistorySP &memory_history =6162 MemoryHistory::FindPlugin(shared_from_this());6163 6164 if (!memory_history) {6165 return threads;6166 }6167 6168 threads = std::make_shared<ThreadCollection>(6169 memory_history->GetHistoryThreads(addr));6170 6171 return threads;6172}6173 6174InstrumentationRuntimeSP6175Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {6176 InstrumentationRuntimeCollection::iterator pos;6177 pos = m_instrumentation_runtimes.find(type);6178 if (pos == m_instrumentation_runtimes.end()) {6179 return InstrumentationRuntimeSP();6180 } else6181 return (*pos).second;6182}6183 6184bool Process::GetModuleSpec(const FileSpec &module_file_spec,6185 const ArchSpec &arch, ModuleSpec &module_spec) {6186 module_spec.Clear();6187 return false;6188}6189 6190size_t Process::AddImageToken(lldb::addr_t image_ptr) {6191 m_image_tokens.push_back(image_ptr);6192 return m_image_tokens.size() - 1;6193}6194 6195lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {6196 if (token < m_image_tokens.size())6197 return m_image_tokens[token];6198 return LLDB_INVALID_IMAGE_TOKEN;6199}6200 6201void Process::ResetImageToken(size_t token) {6202 if (token < m_image_tokens.size())6203 m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;6204}6205 6206Address6207Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,6208 AddressRange range_bounds) {6209 Target &target = GetTarget();6210 DisassemblerSP disassembler_sp;6211 InstructionList *insn_list = nullptr;6212 6213 Address retval = default_stop_addr;6214 6215 if (!target.GetUseFastStepping())6216 return retval;6217 if (!default_stop_addr.IsValid())6218 return retval;6219 6220 const char *plugin_name = nullptr;6221 const char *flavor = nullptr;6222 const char *cpu = nullptr;6223 const char *features = nullptr;6224 disassembler_sp = Disassembler::DisassembleRange(6225 target.GetArchitecture(), plugin_name, flavor, cpu, features, GetTarget(),6226 range_bounds);6227 if (disassembler_sp)6228 insn_list = &disassembler_sp->GetInstructionList();6229 6230 if (insn_list == nullptr) {6231 return retval;6232 }6233 6234 size_t insn_offset =6235 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);6236 if (insn_offset == UINT32_MAX) {6237 return retval;6238 }6239 6240 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(6241 insn_offset, false /* ignore_calls*/, nullptr);6242 if (branch_index == UINT32_MAX) {6243 return retval;6244 }6245 6246 if (branch_index > insn_offset) {6247 Address next_branch_insn_address =6248 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();6249 if (next_branch_insn_address.IsValid() &&6250 range_bounds.ContainsFileAddress(next_branch_insn_address)) {6251 retval = next_branch_insn_address;6252 }6253 }6254 6255 return retval;6256}6257 6258Status Process::GetMemoryRegionInfo(lldb::addr_t load_addr,6259 MemoryRegionInfo &range_info) {6260 if (const lldb::ABISP &abi = GetABI())6261 load_addr = abi->FixAnyAddress(load_addr);6262 Status error = DoGetMemoryRegionInfo(load_addr, range_info);6263 // Reject a region that does not contain the requested address.6264 if (error.Success() && !range_info.GetRange().Contains(load_addr))6265 error = Status::FromErrorString("Invalid memory region");6266 6267 return error;6268}6269 6270Status Process::GetMemoryRegions(lldb_private::MemoryRegionInfos ®ion_list) {6271 Status error;6272 6273 lldb::addr_t range_end = 0;6274 const lldb::ABISP &abi = GetABI();6275 6276 region_list.clear();6277 do {6278 lldb_private::MemoryRegionInfo region_info;6279 error = GetMemoryRegionInfo(range_end, region_info);6280 // GetMemoryRegionInfo should only return an error if it is unimplemented.6281 if (error.Fail()) {6282 region_list.clear();6283 break;6284 }6285 6286 // We only check the end address, not start and end, because we assume that6287 // the start will not have non-address bits until the first unmappable6288 // region. We will have exited the loop by that point because the previous6289 // region, the last mappable region, will have non-address bits in its end6290 // address.6291 range_end = region_info.GetRange().GetRangeEnd();6292 if (region_info.GetMapped() == MemoryRegionInfo::eYes) {6293 region_list.push_back(std::move(region_info));6294 }6295 } while (6296 // For a process with no non-address bits, all address bits6297 // set means the end of memory.6298 range_end != LLDB_INVALID_ADDRESS &&6299 // If we have non-address bits and some are set then the end6300 // is at or beyond the end of mappable memory.6301 !(abi && (abi->FixAnyAddress(range_end) != range_end)));6302 6303 return error;6304}6305 6306Status6307Process::ConfigureStructuredData(llvm::StringRef type_name,6308 const StructuredData::ObjectSP &config_sp) {6309 // If you get this, the Process-derived class needs to implement a method to6310 // enable an already-reported asynchronous structured data feature. See6311 // ProcessGDBRemote for an example implementation over gdb-remote.6312 return Status::FromErrorString("unimplemented");6313}6314 6315void Process::MapSupportedStructuredDataPlugins(6316 const StructuredData::Array &supported_type_names) {6317 Log *log = GetLog(LLDBLog::Process);6318 6319 // Bail out early if there are no type names to map.6320 if (supported_type_names.GetSize() == 0) {6321 LLDB_LOG(log, "no structured data types supported");6322 return;6323 }6324 6325 // These StringRefs are backed by the input parameter.6326 std::set<llvm::StringRef> type_names;6327 6328 LLDB_LOG(log,6329 "the process supports the following async structured data types:");6330 6331 supported_type_names.ForEach(6332 [&type_names, &log](StructuredData::Object *object) {6333 // There shouldn't be null objects in the array.6334 if (!object)6335 return false;6336 6337 // All type names should be strings.6338 const llvm::StringRef type_name = object->GetStringValue();6339 if (type_name.empty())6340 return false;6341 6342 type_names.insert(type_name);6343 LLDB_LOG(log, "- {0}", type_name);6344 return true;6345 });6346 6347 // For each StructuredDataPlugin, if the plugin handles any of the types in6348 // the supported_type_names, map that type name to that plugin. Stop when6349 // we've consumed all the type names.6350 // FIXME: should we return an error if there are type names nobody6351 // supports?6352 for (uint32_t plugin_index = 0; !type_names.empty(); plugin_index++) {6353 auto create_instance =6354 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(6355 plugin_index);6356 if (!create_instance)6357 break;6358 6359 // Create the plugin.6360 StructuredDataPluginSP plugin_sp = (*create_instance)(*this);6361 if (!plugin_sp) {6362 // This plugin doesn't think it can work with the process. Move on to the6363 // next.6364 continue;6365 }6366 6367 // For any of the remaining type names, map any that this plugin supports.6368 std::vector<llvm::StringRef> names_to_remove;6369 for (llvm::StringRef type_name : type_names) {6370 if (plugin_sp->SupportsStructuredDataType(type_name)) {6371 m_structured_data_plugin_map.insert(6372 std::make_pair(type_name, plugin_sp));6373 names_to_remove.push_back(type_name);6374 LLDB_LOG(log, "using plugin {0} for type name {1}",6375 plugin_sp->GetPluginName(), type_name);6376 }6377 }6378 6379 // Remove the type names that were consumed by this plugin.6380 for (llvm::StringRef type_name : names_to_remove)6381 type_names.erase(type_name);6382 }6383}6384 6385bool Process::RouteAsyncStructuredData(6386 const StructuredData::ObjectSP object_sp) {6387 // Nothing to do if there's no data.6388 if (!object_sp)6389 return false;6390 6391 // The contract is this must be a dictionary, so we can look up the routing6392 // key via the top-level 'type' string value within the dictionary.6393 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();6394 if (!dictionary)6395 return false;6396 6397 // Grab the async structured type name (i.e. the feature/plugin name).6398 llvm::StringRef type_name;6399 if (!dictionary->GetValueForKeyAsString("type", type_name))6400 return false;6401 6402 // Check if there's a plugin registered for this type name.6403 auto find_it = m_structured_data_plugin_map.find(type_name);6404 if (find_it == m_structured_data_plugin_map.end()) {6405 // We don't have a mapping for this structured data type.6406 return false;6407 }6408 6409 // Route the structured data to the plugin.6410 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);6411 return true;6412}6413 6414Status Process::UpdateAutomaticSignalFiltering() {6415 // Default implementation does nothign.6416 // No automatic signal filtering to speak of.6417 return Status();6418}6419 6420UtilityFunction *Process::GetLoadImageUtilityFunction(6421 Platform *platform,6422 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {6423 if (platform != GetTarget().GetPlatform().get())6424 return nullptr;6425 llvm::call_once(m_dlopen_utility_func_flag_once,6426 [&] { m_dlopen_utility_func_up = factory(); });6427 return m_dlopen_utility_func_up.get();6428}6429 6430llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {6431 if (!IsLiveDebugSession())6432 return llvm::createStringError(llvm::inconvertibleErrorCode(),6433 "Can't trace a non-live process.");6434 return llvm::make_error<UnimplementedError>();6435}6436 6437bool Process::CallVoidArgVoidPtrReturn(const Address *address,6438 addr_t &returned_func,6439 bool trap_exceptions) {6440 Thread *thread = GetThreadList().GetExpressionExecutionThread().get();6441 if (thread == nullptr || address == nullptr)6442 return false;6443 6444 EvaluateExpressionOptions options;6445 options.SetStopOthers(true);6446 options.SetUnwindOnError(true);6447 options.SetIgnoreBreakpoints(true);6448 options.SetTryAllThreads(true);6449 options.SetDebug(false);6450 options.SetTimeout(GetUtilityExpressionTimeout());6451 options.SetTrapExceptions(trap_exceptions);6452 6453 auto type_system_or_err =6454 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);6455 if (!type_system_or_err) {6456 llvm::consumeError(type_system_or_err.takeError());6457 return false;6458 }6459 auto ts = *type_system_or_err;6460 if (!ts)6461 return false;6462 CompilerType void_ptr_type =6463 ts->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();6464 lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(6465 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));6466 if (call_plan_sp) {6467 DiagnosticManager diagnostics;6468 6469 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();6470 if (frame) {6471 ExecutionContext exe_ctx;6472 frame->CalculateExecutionContext(exe_ctx);6473 ExpressionResults result =6474 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);6475 if (result == eExpressionCompleted) {6476 returned_func =6477 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(6478 LLDB_INVALID_ADDRESS);6479 6480 if (GetAddressByteSize() == 4) {6481 if (returned_func == UINT32_MAX)6482 return false;6483 } else if (GetAddressByteSize() == 8) {6484 if (returned_func == UINT64_MAX)6485 return false;6486 }6487 return true;6488 }6489 }6490 }6491 6492 return false;6493}6494 6495llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {6496 Architecture *arch = GetTarget().GetArchitecturePlugin();6497 const MemoryTagManager *tag_manager =6498 arch ? arch->GetMemoryTagManager() : nullptr;6499 if (!arch || !tag_manager) {6500 return llvm::createStringError(6501 llvm::inconvertibleErrorCode(),6502 "This architecture does not support memory tagging");6503 }6504 6505 if (!SupportsMemoryTagging()) {6506 return llvm::createStringError(llvm::inconvertibleErrorCode(),6507 "Process does not support memory tagging");6508 }6509 6510 return tag_manager;6511}6512 6513llvm::Expected<std::vector<lldb::addr_t>>6514Process::ReadMemoryTags(lldb::addr_t addr, size_t len) {6515 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =6516 GetMemoryTagManager();6517 if (!tag_manager_or_err)6518 return tag_manager_or_err.takeError();6519 6520 const MemoryTagManager *tag_manager = *tag_manager_or_err;6521 llvm::Expected<std::vector<uint8_t>> tag_data =6522 DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());6523 if (!tag_data)6524 return tag_data.takeError();6525 6526 return tag_manager->UnpackTagsData(*tag_data,6527 len / tag_manager->GetGranuleSize());6528}6529 6530Status Process::WriteMemoryTags(lldb::addr_t addr, size_t len,6531 const std::vector<lldb::addr_t> &tags) {6532 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =6533 GetMemoryTagManager();6534 if (!tag_manager_or_err)6535 return Status::FromError(tag_manager_or_err.takeError());6536 6537 const MemoryTagManager *tag_manager = *tag_manager_or_err;6538 llvm::Expected<std::vector<uint8_t>> packed_tags =6539 tag_manager->PackTags(tags);6540 if (!packed_tags) {6541 return Status::FromError(packed_tags.takeError());6542 }6543 6544 return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),6545 *packed_tags);6546}6547 6548// Create a CoreFileMemoryRange from a MemoryRegionInfo6549static CoreFileMemoryRange6550CreateCoreFileMemoryRange(const lldb_private::MemoryRegionInfo ®ion) {6551 const addr_t addr = region.GetRange().GetRangeBase();6552 llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());6553 return {range, region.GetLLDBPermissions()};6554}6555 6556// Add dirty pages to the core file ranges and return true if dirty pages6557// were added. Return false if the dirty page information is not valid or in6558// the region.6559static bool AddDirtyPages(const lldb_private::MemoryRegionInfo ®ion,6560 CoreFileMemoryRanges &ranges) {6561 const auto &dirty_page_list = region.GetDirtyPageList();6562 if (!dirty_page_list)6563 return false;6564 const uint32_t lldb_permissions = region.GetLLDBPermissions();6565 const addr_t page_size = region.GetPageSize();6566 if (page_size == 0)6567 return false;6568 llvm::AddressRange range(0, 0);6569 for (addr_t page_addr : *dirty_page_list) {6570 if (range.empty()) {6571 // No range yet, initialize the range with the current dirty page.6572 range = llvm::AddressRange(page_addr, page_addr + page_size);6573 } else {6574 if (range.end() == page_addr) {6575 // Combine consective ranges.6576 range = llvm::AddressRange(range.start(), page_addr + page_size);6577 } else {6578 // Add previous contiguous range and init the new range with the6579 // current dirty page.6580 ranges.Append(range.start(), range.size(), {range, lldb_permissions});6581 range = llvm::AddressRange(page_addr, page_addr + page_size);6582 }6583 }6584 }6585 // The last range6586 if (!range.empty())6587 ranges.Append(range.start(), range.size(), {range, lldb_permissions});6588 return true;6589}6590 6591// Given a region, add the region to \a ranges.6592//6593// Only add the region if it isn't empty and if it has some permissions.6594// If \a try_dirty_pages is true, then try to add only the dirty pages for a6595// given region. If the region has dirty page information, only dirty pages6596// will be added to \a ranges, else the entire range will be added to \a6597// ranges.6598static void AddRegion(const lldb_private::MemoryRegionInfo ®ion,6599 bool try_dirty_pages, CoreFileMemoryRanges &ranges) {6600 // Don't add empty ranges.6601 if (region.GetRange().GetByteSize() == 0)6602 return;6603 // Don't add ranges with no read permissions.6604 if ((region.GetLLDBPermissions() & lldb::ePermissionsReadable) == 0)6605 return;6606 if (try_dirty_pages && AddDirtyPages(region, ranges))6607 return;6608 6609 ranges.Append(region.GetRange().GetRangeBase(),6610 region.GetRange().GetByteSize(),6611 CreateCoreFileMemoryRange(region));6612}6613 6614static void SaveDynamicLoaderSections(Process &process,6615 const SaveCoreOptions &options,6616 CoreFileMemoryRanges &ranges,6617 std::set<addr_t> &stack_ends) {6618 DynamicLoader *dyld = process.GetDynamicLoader();6619 if (!dyld)6620 return;6621 6622 std::vector<lldb_private::MemoryRegionInfo> dynamic_loader_mem_regions;6623 std::function<bool(const lldb_private::Thread &)> save_thread_predicate =6624 [&](const lldb_private::Thread &t) -> bool {6625 return options.ShouldThreadBeSaved(t.GetID());6626 };6627 dyld->CalculateDynamicSaveCoreRanges(process, dynamic_loader_mem_regions,6628 save_thread_predicate);6629 for (const auto ®ion : dynamic_loader_mem_regions) {6630 // The Dynamic Loader can give us regions that could include a truncated6631 // stack6632 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)6633 AddRegion(region, true, ranges);6634 }6635}6636 6637static void SaveOffRegionsWithStackPointers(Process &process,6638 const SaveCoreOptions &core_options,6639 const MemoryRegionInfos ®ions,6640 CoreFileMemoryRanges &ranges,6641 std::set<addr_t> &stack_ends) {6642 const bool try_dirty_pages = true;6643 6644 // Before we take any dump, we want to save off the used portions of the6645 // stacks and mark those memory regions as saved. This prevents us from saving6646 // the unused portion of the stack below the stack pointer. Saving space on6647 // the dump.6648 for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {6649 if (!thread_sp)6650 continue;6651 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);6652 if (!frame_sp)6653 continue;6654 RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();6655 if (!reg_ctx_sp)6656 continue;6657 const addr_t sp = reg_ctx_sp->GetSP();6658 const size_t red_zone = process.GetABI()->GetRedZoneSize();6659 lldb_private::MemoryRegionInfo sp_region;6660 if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {6661 const size_t stack_head = (sp - red_zone);6662 const size_t stack_size = sp_region.GetRange().GetRangeEnd() - stack_head;6663 // Even if the SaveCoreOption doesn't want us to save the stack6664 // we still need to populate the stack_ends set so it doesn't get saved6665 // off in other calls6666 sp_region.GetRange().SetRangeBase(stack_head);6667 sp_region.GetRange().SetByteSize(stack_size);6668 const addr_t range_end = sp_region.GetRange().GetRangeEnd();6669 stack_ends.insert(range_end);6670 // This will return true if the threadlist the user specified is empty,6671 // or contains the thread id from thread_sp.6672 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {6673 AddRegion(sp_region, try_dirty_pages, ranges);6674 }6675 }6676 }6677}6678 6679// Save all memory regions that are not empty or have at least some permissions6680// for a full core file style.6681static void GetCoreFileSaveRangesFull(Process &process,6682 const MemoryRegionInfos ®ions,6683 CoreFileMemoryRanges &ranges,6684 std::set<addr_t> &stack_ends) {6685 6686 // Don't add only dirty pages, add full regions.6687 const bool try_dirty_pages = false;6688 for (const auto ®ion : regions)6689 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)6690 AddRegion(region, try_dirty_pages, ranges);6691}6692 6693// Save only the dirty pages to the core file. Make sure the process has at6694// least some dirty pages, as some OS versions don't support reporting what6695// pages are dirty within an memory region. If no memory regions have dirty6696// page information fall back to saving out all ranges with write permissions.6697static void GetCoreFileSaveRangesDirtyOnly(Process &process,6698 const MemoryRegionInfos ®ions,6699 CoreFileMemoryRanges &ranges,6700 std::set<addr_t> &stack_ends) {6701 6702 // Iterate over the regions and find all dirty pages.6703 bool have_dirty_page_info = false;6704 for (const auto ®ion : regions) {6705 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6706 AddDirtyPages(region, ranges))6707 have_dirty_page_info = true;6708 }6709 6710 if (!have_dirty_page_info) {6711 // We didn't find support for reporting dirty pages from the process6712 // plug-in so fall back to any region with write access permissions.6713 const bool try_dirty_pages = false;6714 for (const auto ®ion : regions)6715 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6716 region.GetWritable() == MemoryRegionInfo::eYes)6717 AddRegion(region, try_dirty_pages, ranges);6718 }6719}6720 6721// Save all thread stacks to the core file. Some OS versions support reporting6722// when a memory region is stack related. We check on this information, but we6723// also use the stack pointers of each thread and add those in case the OS6724// doesn't support reporting stack memory. This function also attempts to only6725// emit dirty pages from the stack if the memory regions support reporting6726// dirty regions as this will make the core file smaller. If the process6727// doesn't support dirty regions, then it will fall back to adding the full6728// stack region.6729static void GetCoreFileSaveRangesStackOnly(Process &process,6730 const MemoryRegionInfos ®ions,6731 CoreFileMemoryRanges &ranges,6732 std::set<addr_t> &stack_ends) {6733 const bool try_dirty_pages = true;6734 // Some platforms support annotating the region information that tell us that6735 // it comes from a thread stack. So look for those regions first.6736 6737 for (const auto ®ion : regions) {6738 // Save all the stack memory ranges not associated with a stack pointer.6739 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&6740 region.IsStackMemory() == MemoryRegionInfo::eYes)6741 AddRegion(region, try_dirty_pages, ranges);6742 }6743}6744 6745// TODO: We should refactor CoreFileMemoryRanges to use the lldb range type, and6746// then add an intersect method on it, or MemoryRegionInfo.6747static lldb_private::MemoryRegionInfo6748Intersect(const lldb_private::MemoryRegionInfo &lhs,6749 const lldb_private::MemoryRegionInfo::RangeType &rhs) {6750 6751 lldb_private::MemoryRegionInfo region_info;6752 region_info.SetLLDBPermissions(lhs.GetLLDBPermissions());6753 region_info.GetRange() = lhs.GetRange().Intersect(rhs);6754 6755 return region_info;6756}6757 6758static void GetUserSpecifiedCoreFileSaveRanges(Process &process,6759 const MemoryRegionInfos ®ions,6760 const SaveCoreOptions &options,6761 CoreFileMemoryRanges &ranges) {6762 const auto &option_ranges = options.GetCoreFileMemoryRanges();6763 if (option_ranges.IsEmpty())6764 return;6765 6766 for (const auto &range : regions) {6767 auto *entry = option_ranges.FindEntryThatIntersects(range.GetRange());6768 if (entry) {6769 if (*entry != range.GetRange()) {6770 AddRegion(Intersect(range, *entry), true, ranges);6771 } else {6772 // If they match, add the range directly.6773 AddRegion(range, true, ranges);6774 }6775 }6776 }6777}6778 6779Status Process::CalculateCoreFileSaveRanges(const SaveCoreOptions &options,6780 CoreFileMemoryRanges &ranges) {6781 lldb_private::MemoryRegionInfos regions;6782 Status err = GetMemoryRegions(regions);6783 SaveCoreStyle core_style = options.GetStyle();6784 if (err.Fail())6785 return err;6786 if (regions.empty())6787 return Status::FromErrorString(6788 "failed to get any valid memory regions from the process");6789 if (core_style == eSaveCoreUnspecified)6790 return Status::FromErrorString(6791 "callers must set the core_style to something other than "6792 "eSaveCoreUnspecified");6793 6794 GetUserSpecifiedCoreFileSaveRanges(*this, regions, options, ranges);6795 6796 std::set<addr_t> stack_ends;6797 // For fully custom set ups, we don't want to even look at threads if there6798 // are no threads specified.6799 if (core_style != lldb::eSaveCoreCustomOnly ||6800 options.HasSpecifiedThreads()) {6801 SaveOffRegionsWithStackPointers(*this, options, regions, ranges,6802 stack_ends);6803 // Save off the dynamic loader sections, so if we are on an architecture6804 // that supports Thread Locals, that we include those as well.6805 SaveDynamicLoaderSections(*this, options, ranges, stack_ends);6806 }6807 6808 switch (core_style) {6809 case eSaveCoreUnspecified:6810 case eSaveCoreCustomOnly:6811 break;6812 6813 case eSaveCoreFull:6814 GetCoreFileSaveRangesFull(*this, regions, ranges, stack_ends);6815 break;6816 6817 case eSaveCoreDirtyOnly:6818 GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges, stack_ends);6819 break;6820 6821 case eSaveCoreStackOnly:6822 GetCoreFileSaveRangesStackOnly(*this, regions, ranges, stack_ends);6823 break;6824 }6825 6826 if (err.Fail())6827 return err;6828 6829 if (ranges.IsEmpty())6830 return Status::FromErrorStringWithFormat(6831 "no valid address ranges found for core style");6832 6833 return ranges.FinalizeCoreFileSaveRanges();6834}6835 6836std::vector<ThreadSP>6837Process::CalculateCoreFileThreadList(const SaveCoreOptions &core_options) {6838 std::vector<ThreadSP> thread_list;6839 for (const lldb::ThreadSP &thread_sp : m_thread_list.Threads()) {6840 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {6841 thread_list.push_back(thread_sp);6842 }6843 }6844 6845 return thread_list;6846}6847 6848void Process::SetAddressableBitMasks(AddressableBits bit_masks) {6849 uint32_t low_memory_addr_bits = bit_masks.GetLowmemAddressableBits();6850 uint32_t high_memory_addr_bits = bit_masks.GetHighmemAddressableBits();6851 6852 if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)6853 return;6854 6855 if (low_memory_addr_bits != 0) {6856 addr_t low_addr_mask =6857 AddressableBits::AddressableBitToMask(low_memory_addr_bits);6858 SetCodeAddressMask(low_addr_mask);6859 SetDataAddressMask(low_addr_mask);6860 }6861 6862 if (high_memory_addr_bits != 0) {6863 addr_t high_addr_mask =6864 AddressableBits::AddressableBitToMask(high_memory_addr_bits);6865 SetHighmemCodeAddressMask(high_addr_mask);6866 SetHighmemDataAddressMask(high_addr_mask);6867 }6868}6869