15ffd83dbSDimitry Andric //===-- Process.cpp -------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include <atomic>
100b57cec5SDimitry Andric #include <memory>
110b57cec5SDimitry Andric #include <mutex>
120b57cec5SDimitry Andric 
13*5f7ddb14SDimitry Andric #include "llvm/ADT/ScopeExit.h"
140b57cec5SDimitry Andric #include "llvm/Support/ScopedPrinter.h"
150b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
160b57cec5SDimitry Andric 
170b57cec5SDimitry Andric #include "lldb/Breakpoint/BreakpointLocation.h"
180b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
190b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
200b57cec5SDimitry Andric #include "lldb/Core/Module.h"
210b57cec5SDimitry Andric #include "lldb/Core/ModuleSpec.h"
220b57cec5SDimitry Andric #include "lldb/Core/PluginManager.h"
230b57cec5SDimitry Andric #include "lldb/Core/StreamFile.h"
240b57cec5SDimitry Andric #include "lldb/Expression/DiagnosticManager.h"
250b57cec5SDimitry Andric #include "lldb/Expression/DynamicCheckerFunctions.h"
260b57cec5SDimitry Andric #include "lldb/Expression/UserExpression.h"
270b57cec5SDimitry Andric #include "lldb/Expression/UtilityFunction.h"
280b57cec5SDimitry Andric #include "lldb/Host/ConnectionFileDescriptor.h"
290b57cec5SDimitry Andric #include "lldb/Host/FileSystem.h"
300b57cec5SDimitry Andric #include "lldb/Host/Host.h"
310b57cec5SDimitry Andric #include "lldb/Host/HostInfo.h"
320b57cec5SDimitry Andric #include "lldb/Host/OptionParser.h"
330b57cec5SDimitry Andric #include "lldb/Host/Pipe.h"
340b57cec5SDimitry Andric #include "lldb/Host/Terminal.h"
350b57cec5SDimitry Andric #include "lldb/Host/ThreadLauncher.h"
360b57cec5SDimitry Andric #include "lldb/Interpreter/CommandInterpreter.h"
370b57cec5SDimitry Andric #include "lldb/Interpreter/OptionArgParser.h"
380b57cec5SDimitry Andric #include "lldb/Interpreter/OptionValueProperties.h"
390b57cec5SDimitry Andric #include "lldb/Symbol/Function.h"
400b57cec5SDimitry Andric #include "lldb/Symbol/Symbol.h"
410b57cec5SDimitry Andric #include "lldb/Target/ABI.h"
425ffd83dbSDimitry Andric #include "lldb/Target/AssertFrameRecognizer.h"
430b57cec5SDimitry Andric #include "lldb/Target/DynamicLoader.h"
440b57cec5SDimitry Andric #include "lldb/Target/InstrumentationRuntime.h"
450b57cec5SDimitry Andric #include "lldb/Target/JITLoader.h"
460b57cec5SDimitry Andric #include "lldb/Target/JITLoaderList.h"
470b57cec5SDimitry Andric #include "lldb/Target/Language.h"
480b57cec5SDimitry Andric #include "lldb/Target/LanguageRuntime.h"
490b57cec5SDimitry Andric #include "lldb/Target/MemoryHistory.h"
500b57cec5SDimitry Andric #include "lldb/Target/MemoryRegionInfo.h"
510b57cec5SDimitry Andric #include "lldb/Target/OperatingSystem.h"
520b57cec5SDimitry Andric #include "lldb/Target/Platform.h"
530b57cec5SDimitry Andric #include "lldb/Target/Process.h"
540b57cec5SDimitry Andric #include "lldb/Target/RegisterContext.h"
550b57cec5SDimitry Andric #include "lldb/Target/StopInfo.h"
560b57cec5SDimitry Andric #include "lldb/Target/StructuredDataPlugin.h"
570b57cec5SDimitry Andric #include "lldb/Target/SystemRuntime.h"
580b57cec5SDimitry Andric #include "lldb/Target/Target.h"
590b57cec5SDimitry Andric #include "lldb/Target/TargetList.h"
600b57cec5SDimitry Andric #include "lldb/Target/Thread.h"
610b57cec5SDimitry Andric #include "lldb/Target/ThreadPlan.h"
620b57cec5SDimitry Andric #include "lldb/Target/ThreadPlanBase.h"
639dba64beSDimitry Andric #include "lldb/Target/ThreadPlanCallFunction.h"
645ffd83dbSDimitry Andric #include "lldb/Target/ThreadPlanStack.h"
650b57cec5SDimitry Andric #include "lldb/Target/UnixSignals.h"
660b57cec5SDimitry Andric #include "lldb/Utility/Event.h"
670b57cec5SDimitry Andric #include "lldb/Utility/Log.h"
680b57cec5SDimitry Andric #include "lldb/Utility/NameMatches.h"
690b57cec5SDimitry Andric #include "lldb/Utility/ProcessInfo.h"
700b57cec5SDimitry Andric #include "lldb/Utility/SelectHelper.h"
710b57cec5SDimitry Andric #include "lldb/Utility/State.h"
72*5f7ddb14SDimitry Andric #include "lldb/Utility/Timer.h"
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric using namespace lldb;
750b57cec5SDimitry Andric using namespace lldb_private;
760b57cec5SDimitry Andric using namespace std::chrono;
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric // Comment out line below to disable memory caching, overriding the process
790b57cec5SDimitry Andric // setting target.process.disable-memory-cache
800b57cec5SDimitry Andric #define ENABLE_MEMORY_CACHING
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric #ifdef ENABLE_MEMORY_CACHING
830b57cec5SDimitry Andric #define DISABLE_MEM_CACHE_DEFAULT false
840b57cec5SDimitry Andric #else
850b57cec5SDimitry Andric #define DISABLE_MEM_CACHE_DEFAULT true
860b57cec5SDimitry Andric #endif
870b57cec5SDimitry Andric 
88*5f7ddb14SDimitry Andric class ProcessOptionValueProperties
89*5f7ddb14SDimitry Andric     : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
900b57cec5SDimitry Andric public:
ProcessOptionValueProperties(ConstString name)91*5f7ddb14SDimitry Andric   ProcessOptionValueProperties(ConstString name) : Cloneable(name) {}
920b57cec5SDimitry Andric 
GetPropertyAtIndex(const ExecutionContext * exe_ctx,bool will_modify,uint32_t idx) const930b57cec5SDimitry Andric   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
940b57cec5SDimitry Andric                                      bool will_modify,
950b57cec5SDimitry Andric                                      uint32_t idx) const override {
960b57cec5SDimitry Andric     // When getting the value for a key from the process options, we will
970b57cec5SDimitry Andric     // always try and grab the setting from the current process if there is
980b57cec5SDimitry Andric     // one. Else we just use the one from this instance.
990b57cec5SDimitry Andric     if (exe_ctx) {
1000b57cec5SDimitry Andric       Process *process = exe_ctx->GetProcessPtr();
1010b57cec5SDimitry Andric       if (process) {
1020b57cec5SDimitry Andric         ProcessOptionValueProperties *instance_properties =
1030b57cec5SDimitry Andric             static_cast<ProcessOptionValueProperties *>(
1040b57cec5SDimitry Andric                 process->GetValueProperties().get());
1050b57cec5SDimitry Andric         if (this != instance_properties)
1060b57cec5SDimitry Andric           return instance_properties->ProtectedGetPropertyAtIndex(idx);
1070b57cec5SDimitry Andric       }
1080b57cec5SDimitry Andric     }
1090b57cec5SDimitry Andric     return ProtectedGetPropertyAtIndex(idx);
1100b57cec5SDimitry Andric   }
1110b57cec5SDimitry Andric };
1120b57cec5SDimitry Andric 
1139dba64beSDimitry Andric #define LLDB_PROPERTIES_process
1149dba64beSDimitry Andric #include "TargetProperties.inc"
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric enum {
1179dba64beSDimitry Andric #define LLDB_PROPERTIES_process
1189dba64beSDimitry Andric #include "TargetPropertiesEnum.inc"
1195ffd83dbSDimitry Andric   ePropertyExperimental,
1200b57cec5SDimitry Andric };
1210b57cec5SDimitry Andric 
1225ffd83dbSDimitry Andric #define LLDB_PROPERTIES_process_experimental
1235ffd83dbSDimitry Andric #include "TargetProperties.inc"
1245ffd83dbSDimitry Andric 
1255ffd83dbSDimitry Andric enum {
1265ffd83dbSDimitry Andric #define LLDB_PROPERTIES_process_experimental
1275ffd83dbSDimitry Andric #include "TargetPropertiesEnum.inc"
1285ffd83dbSDimitry Andric };
1295ffd83dbSDimitry Andric 
130*5f7ddb14SDimitry Andric class ProcessExperimentalOptionValueProperties
131*5f7ddb14SDimitry Andric     : public Cloneable<ProcessExperimentalOptionValueProperties,
132*5f7ddb14SDimitry Andric                        OptionValueProperties> {
1335ffd83dbSDimitry Andric public:
ProcessExperimentalOptionValueProperties()1345ffd83dbSDimitry Andric   ProcessExperimentalOptionValueProperties()
135*5f7ddb14SDimitry Andric       : Cloneable(
1365ffd83dbSDimitry Andric             ConstString(Properties::GetExperimentalSettingsName())) {}
1375ffd83dbSDimitry Andric };
1385ffd83dbSDimitry Andric 
ProcessExperimentalProperties()1395ffd83dbSDimitry Andric ProcessExperimentalProperties::ProcessExperimentalProperties()
1405ffd83dbSDimitry Andric     : Properties(OptionValuePropertiesSP(
1415ffd83dbSDimitry Andric           new ProcessExperimentalOptionValueProperties())) {
1425ffd83dbSDimitry Andric   m_collection_sp->Initialize(g_process_experimental_properties);
1435ffd83dbSDimitry Andric }
1445ffd83dbSDimitry Andric 
ProcessProperties(lldb_private::Process * process)1450b57cec5SDimitry Andric ProcessProperties::ProcessProperties(lldb_private::Process *process)
1460b57cec5SDimitry Andric     : Properties(),
1470b57cec5SDimitry Andric       m_process(process) // Can be nullptr for global ProcessProperties
1480b57cec5SDimitry Andric {
1490b57cec5SDimitry Andric   if (process == nullptr) {
1500b57cec5SDimitry Andric     // Global process properties, set them up one time
1510b57cec5SDimitry Andric     m_collection_sp =
1520b57cec5SDimitry Andric         std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
1539dba64beSDimitry Andric     m_collection_sp->Initialize(g_process_properties);
1540b57cec5SDimitry Andric     m_collection_sp->AppendProperty(
1550b57cec5SDimitry Andric         ConstString("thread"), ConstString("Settings specific to threads."),
1560b57cec5SDimitry Andric         true, Thread::GetGlobalProperties()->GetValueProperties());
1570b57cec5SDimitry Andric   } else {
158*5f7ddb14SDimitry Andric     m_collection_sp =
159*5f7ddb14SDimitry Andric         OptionValueProperties::CreateLocalCopy(*Process::GetGlobalProperties());
1600b57cec5SDimitry Andric     m_collection_sp->SetValueChangedCallback(
1610b57cec5SDimitry Andric         ePropertyPythonOSPluginPath,
162480093f4SDimitry Andric         [this] { m_process->LoadOperatingSystemPlugin(true); });
1630b57cec5SDimitry Andric   }
1645ffd83dbSDimitry Andric 
1655ffd83dbSDimitry Andric   m_experimental_properties_up =
1665ffd83dbSDimitry Andric       std::make_unique<ProcessExperimentalProperties>();
1675ffd83dbSDimitry Andric   m_collection_sp->AppendProperty(
1685ffd83dbSDimitry Andric       ConstString(Properties::GetExperimentalSettingsName()),
1695ffd83dbSDimitry Andric       ConstString("Experimental settings - setting these won't produce "
1705ffd83dbSDimitry Andric                   "errors if the setting is not present."),
1715ffd83dbSDimitry Andric       true, m_experimental_properties_up->GetValueProperties());
1720b57cec5SDimitry Andric }
1730b57cec5SDimitry Andric 
1740b57cec5SDimitry Andric ProcessProperties::~ProcessProperties() = default;
1750b57cec5SDimitry Andric 
GetDisableMemoryCache() const1760b57cec5SDimitry Andric bool ProcessProperties::GetDisableMemoryCache() const {
1770b57cec5SDimitry Andric   const uint32_t idx = ePropertyDisableMemCache;
1780b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
1799dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
1800b57cec5SDimitry Andric }
1810b57cec5SDimitry Andric 
GetMemoryCacheLineSize() const1820b57cec5SDimitry Andric uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
1830b57cec5SDimitry Andric   const uint32_t idx = ePropertyMemCacheLineSize;
1840b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsUInt64(
1859dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value);
1860b57cec5SDimitry Andric }
1870b57cec5SDimitry Andric 
GetExtraStartupCommands() const1880b57cec5SDimitry Andric Args ProcessProperties::GetExtraStartupCommands() const {
1890b57cec5SDimitry Andric   Args args;
1900b57cec5SDimitry Andric   const uint32_t idx = ePropertyExtraStartCommand;
1910b57cec5SDimitry Andric   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
1920b57cec5SDimitry Andric   return args;
1930b57cec5SDimitry Andric }
1940b57cec5SDimitry Andric 
SetExtraStartupCommands(const Args & args)1950b57cec5SDimitry Andric void ProcessProperties::SetExtraStartupCommands(const Args &args) {
1960b57cec5SDimitry Andric   const uint32_t idx = ePropertyExtraStartCommand;
1970b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
GetPythonOSPluginPath() const2000b57cec5SDimitry Andric FileSpec ProcessProperties::GetPythonOSPluginPath() const {
2010b57cec5SDimitry Andric   const uint32_t idx = ePropertyPythonOSPluginPath;
2020b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
2030b57cec5SDimitry Andric }
2040b57cec5SDimitry Andric 
GetVirtualAddressableBits() const205*5f7ddb14SDimitry Andric uint32_t ProcessProperties::GetVirtualAddressableBits() const {
206*5f7ddb14SDimitry Andric   const uint32_t idx = ePropertyVirtualAddressableBits;
207*5f7ddb14SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsUInt64(
208*5f7ddb14SDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value);
209*5f7ddb14SDimitry Andric }
210*5f7ddb14SDimitry Andric 
SetVirtualAddressableBits(uint32_t bits)211*5f7ddb14SDimitry Andric void ProcessProperties::SetVirtualAddressableBits(uint32_t bits) {
212*5f7ddb14SDimitry Andric   const uint32_t idx = ePropertyVirtualAddressableBits;
213*5f7ddb14SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, bits);
214*5f7ddb14SDimitry Andric }
SetPythonOSPluginPath(const FileSpec & file)2150b57cec5SDimitry Andric void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
2160b57cec5SDimitry Andric   const uint32_t idx = ePropertyPythonOSPluginPath;
2170b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
2180b57cec5SDimitry Andric }
2190b57cec5SDimitry Andric 
GetIgnoreBreakpointsInExpressions() const2200b57cec5SDimitry Andric bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
2210b57cec5SDimitry Andric   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
2220b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2239dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2240b57cec5SDimitry Andric }
2250b57cec5SDimitry Andric 
SetIgnoreBreakpointsInExpressions(bool ignore)2260b57cec5SDimitry Andric void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
2270b57cec5SDimitry Andric   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
2280b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
2290b57cec5SDimitry Andric }
2300b57cec5SDimitry Andric 
GetUnwindOnErrorInExpressions() const2310b57cec5SDimitry Andric bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
2320b57cec5SDimitry Andric   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
2330b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2349dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2350b57cec5SDimitry Andric }
2360b57cec5SDimitry Andric 
SetUnwindOnErrorInExpressions(bool ignore)2370b57cec5SDimitry Andric void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
2380b57cec5SDimitry Andric   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
2390b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
2400b57cec5SDimitry Andric }
2410b57cec5SDimitry Andric 
GetStopOnSharedLibraryEvents() const2420b57cec5SDimitry Andric bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
2430b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
2440b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2459dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2460b57cec5SDimitry Andric }
2470b57cec5SDimitry Andric 
SetStopOnSharedLibraryEvents(bool stop)2480b57cec5SDimitry Andric void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
2490b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
2500b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
2510b57cec5SDimitry Andric }
2520b57cec5SDimitry Andric 
GetDisableLangRuntimeUnwindPlans() const253*5f7ddb14SDimitry Andric bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const {
254*5f7ddb14SDimitry Andric   const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
255*5f7ddb14SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
256*5f7ddb14SDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
257*5f7ddb14SDimitry Andric }
258*5f7ddb14SDimitry Andric 
SetDisableLangRuntimeUnwindPlans(bool disable)259*5f7ddb14SDimitry Andric void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable) {
260*5f7ddb14SDimitry Andric   const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
261*5f7ddb14SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, disable);
262*5f7ddb14SDimitry Andric   m_process->Flush();
263*5f7ddb14SDimitry Andric }
264*5f7ddb14SDimitry Andric 
GetDetachKeepsStopped() const2650b57cec5SDimitry Andric bool ProcessProperties::GetDetachKeepsStopped() const {
2660b57cec5SDimitry Andric   const uint32_t idx = ePropertyDetachKeepsStopped;
2670b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2689dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2690b57cec5SDimitry Andric }
2700b57cec5SDimitry Andric 
SetDetachKeepsStopped(bool stop)2710b57cec5SDimitry Andric void ProcessProperties::SetDetachKeepsStopped(bool stop) {
2720b57cec5SDimitry Andric   const uint32_t idx = ePropertyDetachKeepsStopped;
2730b57cec5SDimitry Andric   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
2740b57cec5SDimitry Andric }
2750b57cec5SDimitry Andric 
GetWarningsOptimization() const2760b57cec5SDimitry Andric bool ProcessProperties::GetWarningsOptimization() const {
2770b57cec5SDimitry Andric   const uint32_t idx = ePropertyWarningOptimization;
2780b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2799dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric 
GetWarningsUnsupportedLanguage() const2825ffd83dbSDimitry Andric bool ProcessProperties::GetWarningsUnsupportedLanguage() const {
2835ffd83dbSDimitry Andric   const uint32_t idx = ePropertyWarningUnsupportedLanguage;
2845ffd83dbSDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2855ffd83dbSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2865ffd83dbSDimitry Andric }
2875ffd83dbSDimitry Andric 
GetStopOnExec() const2880b57cec5SDimitry Andric bool ProcessProperties::GetStopOnExec() const {
2890b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnExec;
2900b57cec5SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
2919dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
2920b57cec5SDimitry Andric }
2930b57cec5SDimitry Andric 
GetUtilityExpressionTimeout() const2940b57cec5SDimitry Andric std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
2950b57cec5SDimitry Andric   const uint32_t idx = ePropertyUtilityExpressionTimeout;
2960b57cec5SDimitry Andric   uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
2979dba64beSDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value);
2980b57cec5SDimitry Andric   return std::chrono::seconds(value);
2990b57cec5SDimitry Andric }
3000b57cec5SDimitry Andric 
GetInterruptTimeout() const301*5f7ddb14SDimitry Andric std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {
302*5f7ddb14SDimitry Andric   const uint32_t idx = ePropertyInterruptTimeout;
303*5f7ddb14SDimitry Andric   uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
304*5f7ddb14SDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value);
305*5f7ddb14SDimitry Andric   return std::chrono::seconds(value);
306*5f7ddb14SDimitry Andric }
307*5f7ddb14SDimitry Andric 
GetSteppingRunsAllThreads() const308af732203SDimitry Andric bool ProcessProperties::GetSteppingRunsAllThreads() const {
309af732203SDimitry Andric   const uint32_t idx = ePropertySteppingRunsAllThreads;
310af732203SDimitry Andric   return m_collection_sp->GetPropertyAtIndexAsBoolean(
311af732203SDimitry Andric       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
312af732203SDimitry Andric }
313af732203SDimitry Andric 
GetOSPluginReportsAllThreads() const3145ffd83dbSDimitry Andric bool ProcessProperties::GetOSPluginReportsAllThreads() const {
3155ffd83dbSDimitry Andric   const bool fail_value = true;
3165ffd83dbSDimitry Andric   const Property *exp_property =
3175ffd83dbSDimitry Andric       m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
3185ffd83dbSDimitry Andric   OptionValueProperties *exp_values =
3195ffd83dbSDimitry Andric       exp_property->GetValue()->GetAsProperties();
3205ffd83dbSDimitry Andric   if (!exp_values)
3215ffd83dbSDimitry Andric     return fail_value;
3225ffd83dbSDimitry Andric 
3235ffd83dbSDimitry Andric   return exp_values->GetPropertyAtIndexAsBoolean(
3245ffd83dbSDimitry Andric       nullptr, ePropertyOSPluginReportsAllThreads, fail_value);
3255ffd83dbSDimitry Andric }
3265ffd83dbSDimitry Andric 
SetOSPluginReportsAllThreads(bool does_report)3275ffd83dbSDimitry Andric void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {
3285ffd83dbSDimitry Andric   const Property *exp_property =
3295ffd83dbSDimitry Andric       m_collection_sp->GetPropertyAtIndex(nullptr, true, ePropertyExperimental);
3305ffd83dbSDimitry Andric   OptionValueProperties *exp_values =
3315ffd83dbSDimitry Andric       exp_property->GetValue()->GetAsProperties();
3325ffd83dbSDimitry Andric   if (exp_values)
3335ffd83dbSDimitry Andric     exp_values->SetPropertyAtIndexAsBoolean(
3345ffd83dbSDimitry Andric         nullptr, ePropertyOSPluginReportsAllThreads, does_report);
3355ffd83dbSDimitry Andric }
3365ffd83dbSDimitry Andric 
FindPlugin(lldb::TargetSP target_sp,llvm::StringRef plugin_name,ListenerSP listener_sp,const FileSpec * crash_file_path,bool can_connect)3370b57cec5SDimitry Andric ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
3380b57cec5SDimitry Andric                               llvm::StringRef plugin_name,
3390b57cec5SDimitry Andric                               ListenerSP listener_sp,
340af732203SDimitry Andric                               const FileSpec *crash_file_path,
341af732203SDimitry Andric                               bool can_connect) {
3420b57cec5SDimitry Andric   static uint32_t g_process_unique_id = 0;
3430b57cec5SDimitry Andric 
3440b57cec5SDimitry Andric   ProcessSP process_sp;
3450b57cec5SDimitry Andric   ProcessCreateInstance create_callback = nullptr;
3460b57cec5SDimitry Andric   if (!plugin_name.empty()) {
3470b57cec5SDimitry Andric     ConstString const_plugin_name(plugin_name);
3480b57cec5SDimitry Andric     create_callback =
3490b57cec5SDimitry Andric         PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
3500b57cec5SDimitry Andric     if (create_callback) {
351af732203SDimitry Andric       process_sp = create_callback(target_sp, listener_sp, crash_file_path,
352af732203SDimitry Andric                                    can_connect);
3530b57cec5SDimitry Andric       if (process_sp) {
3540b57cec5SDimitry Andric         if (process_sp->CanDebug(target_sp, true)) {
3550b57cec5SDimitry Andric           process_sp->m_process_unique_id = ++g_process_unique_id;
3560b57cec5SDimitry Andric         } else
3570b57cec5SDimitry Andric           process_sp.reset();
3580b57cec5SDimitry Andric       }
3590b57cec5SDimitry Andric     }
3600b57cec5SDimitry Andric   } else {
3610b57cec5SDimitry Andric     for (uint32_t idx = 0;
3620b57cec5SDimitry Andric          (create_callback =
3630b57cec5SDimitry Andric               PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
3640b57cec5SDimitry Andric          ++idx) {
365af732203SDimitry Andric       process_sp = create_callback(target_sp, listener_sp, crash_file_path,
366af732203SDimitry Andric                                    can_connect);
3670b57cec5SDimitry Andric       if (process_sp) {
3680b57cec5SDimitry Andric         if (process_sp->CanDebug(target_sp, false)) {
3690b57cec5SDimitry Andric           process_sp->m_process_unique_id = ++g_process_unique_id;
3700b57cec5SDimitry Andric           break;
3710b57cec5SDimitry Andric         } else
3720b57cec5SDimitry Andric           process_sp.reset();
3730b57cec5SDimitry Andric       }
3740b57cec5SDimitry Andric     }
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric   return process_sp;
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
GetStaticBroadcasterClass()3790b57cec5SDimitry Andric ConstString &Process::GetStaticBroadcasterClass() {
3800b57cec5SDimitry Andric   static ConstString class_name("lldb.process");
3810b57cec5SDimitry Andric   return class_name;
3820b57cec5SDimitry Andric }
3830b57cec5SDimitry Andric 
Process(lldb::TargetSP target_sp,ListenerSP listener_sp)3840b57cec5SDimitry Andric Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
3850b57cec5SDimitry Andric     : Process(target_sp, listener_sp,
3860b57cec5SDimitry Andric               UnixSignals::Create(HostInfo::GetArchitecture())) {
3870b57cec5SDimitry Andric   // This constructor just delegates to the full Process constructor,
3880b57cec5SDimitry Andric   // defaulting to using the Host's UnixSignals.
3890b57cec5SDimitry Andric }
3900b57cec5SDimitry Andric 
Process(lldb::TargetSP target_sp,ListenerSP listener_sp,const UnixSignalsSP & unix_signals_sp)3910b57cec5SDimitry Andric Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
3920b57cec5SDimitry Andric                  const UnixSignalsSP &unix_signals_sp)
393af732203SDimitry Andric     : ProcessProperties(this),
3940b57cec5SDimitry Andric       Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
3950b57cec5SDimitry Andric                   Process::GetStaticBroadcasterClass().AsCString()),
3960b57cec5SDimitry Andric       m_target_wp(target_sp), m_public_state(eStateUnloaded),
3970b57cec5SDimitry Andric       m_private_state(eStateUnloaded),
3980b57cec5SDimitry Andric       m_private_state_broadcaster(nullptr,
3990b57cec5SDimitry Andric                                   "lldb.process.internal_state_broadcaster"),
4000b57cec5SDimitry Andric       m_private_state_control_broadcaster(
4010b57cec5SDimitry Andric           nullptr, "lldb.process.internal_state_control_broadcaster"),
4020b57cec5SDimitry Andric       m_private_state_listener_sp(
4030b57cec5SDimitry Andric           Listener::MakeListener("lldb.process.internal_state_listener")),
4040b57cec5SDimitry Andric       m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
4050b57cec5SDimitry Andric       m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
4060b57cec5SDimitry Andric       m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
4075ffd83dbSDimitry Andric       m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
4080b57cec5SDimitry Andric       m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
4090b57cec5SDimitry Andric       m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
4100b57cec5SDimitry Andric       m_breakpoint_site_list(), m_dynamic_checkers_up(),
4110b57cec5SDimitry Andric       m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
4120b57cec5SDimitry Andric       m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
4130b57cec5SDimitry Andric       m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
4140b57cec5SDimitry Andric       m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
4150b57cec5SDimitry Andric       m_memory_cache(*this), m_allocated_memory_cache(*this),
4160b57cec5SDimitry Andric       m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
417af732203SDimitry Andric       m_private_run_lock(), m_finalizing(false),
4180b57cec5SDimitry Andric       m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
4190b57cec5SDimitry Andric       m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
4200b57cec5SDimitry Andric       m_can_interpret_function_calls(false), m_warnings_issued(),
4210b57cec5SDimitry Andric       m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
4220b57cec5SDimitry Andric   CheckInWithManager();
4230b57cec5SDimitry Andric 
4240b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
4259dba64beSDimitry Andric   LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
4260b57cec5SDimitry Andric 
4270b57cec5SDimitry Andric   if (!m_unix_signals_sp)
4280b57cec5SDimitry Andric     m_unix_signals_sp = std::make_shared<UnixSignals>();
4290b57cec5SDimitry Andric 
4300b57cec5SDimitry Andric   SetEventName(eBroadcastBitStateChanged, "state-changed");
4310b57cec5SDimitry Andric   SetEventName(eBroadcastBitInterrupt, "interrupt");
4320b57cec5SDimitry Andric   SetEventName(eBroadcastBitSTDOUT, "stdout-available");
4330b57cec5SDimitry Andric   SetEventName(eBroadcastBitSTDERR, "stderr-available");
4340b57cec5SDimitry Andric   SetEventName(eBroadcastBitProfileData, "profile-data-available");
4350b57cec5SDimitry Andric   SetEventName(eBroadcastBitStructuredData, "structured-data-available");
4360b57cec5SDimitry Andric 
4370b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4380b57cec5SDimitry Andric       eBroadcastInternalStateControlStop, "control-stop");
4390b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4400b57cec5SDimitry Andric       eBroadcastInternalStateControlPause, "control-pause");
4410b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4420b57cec5SDimitry Andric       eBroadcastInternalStateControlResume, "control-resume");
4430b57cec5SDimitry Andric 
4440b57cec5SDimitry Andric   m_listener_sp->StartListeningForEvents(
4450b57cec5SDimitry Andric       this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
4460b57cec5SDimitry Andric                 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
4470b57cec5SDimitry Andric                 eBroadcastBitProfileData | eBroadcastBitStructuredData);
4480b57cec5SDimitry Andric 
4490b57cec5SDimitry Andric   m_private_state_listener_sp->StartListeningForEvents(
4500b57cec5SDimitry Andric       &m_private_state_broadcaster,
4510b57cec5SDimitry Andric       eBroadcastBitStateChanged | eBroadcastBitInterrupt);
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric   m_private_state_listener_sp->StartListeningForEvents(
4540b57cec5SDimitry Andric       &m_private_state_control_broadcaster,
4550b57cec5SDimitry Andric       eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
4560b57cec5SDimitry Andric           eBroadcastInternalStateControlResume);
4570b57cec5SDimitry Andric   // We need something valid here, even if just the default UnixSignalsSP.
4580b57cec5SDimitry Andric   assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric   // Allow the platform to override the default cache line size
4610b57cec5SDimitry Andric   OptionValueSP value_sp =
4620b57cec5SDimitry Andric       m_collection_sp
4630b57cec5SDimitry Andric           ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
4640b57cec5SDimitry Andric           ->GetValue();
4650b57cec5SDimitry Andric   uint32_t platform_cache_line_size =
4660b57cec5SDimitry Andric       target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
4670b57cec5SDimitry Andric   if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
4680b57cec5SDimitry Andric     value_sp->SetUInt64Value(platform_cache_line_size);
4695ffd83dbSDimitry Andric 
4705ffd83dbSDimitry Andric   RegisterAssertFrameRecognizer(this);
4710b57cec5SDimitry Andric }
4720b57cec5SDimitry Andric 
~Process()4730b57cec5SDimitry Andric Process::~Process() {
4740b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
4759dba64beSDimitry Andric   LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
4760b57cec5SDimitry Andric   StopPrivateStateThread();
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   // ThreadList::Clear() will try to acquire this process's mutex, so
4790b57cec5SDimitry Andric   // explicitly clear the thread list here to ensure that the mutex is not
4800b57cec5SDimitry Andric   // destroyed before the thread list.
4810b57cec5SDimitry Andric   m_thread_list.Clear();
4820b57cec5SDimitry Andric }
4830b57cec5SDimitry Andric 
GetGlobalProperties()4840b57cec5SDimitry Andric const ProcessPropertiesSP &Process::GetGlobalProperties() {
4850b57cec5SDimitry Andric   // NOTE: intentional leak so we don't crash if global destructor chain gets
4860b57cec5SDimitry Andric   // called as other threads still use the result of this function
4870b57cec5SDimitry Andric   static ProcessPropertiesSP *g_settings_sp_ptr =
4880b57cec5SDimitry Andric       new ProcessPropertiesSP(new ProcessProperties(nullptr));
4890b57cec5SDimitry Andric   return *g_settings_sp_ptr;
4900b57cec5SDimitry Andric }
4910b57cec5SDimitry Andric 
Finalize()4920b57cec5SDimitry Andric void Process::Finalize() {
493af732203SDimitry Andric   if (m_finalizing.exchange(true))
494af732203SDimitry Andric     return;
4950b57cec5SDimitry Andric 
496*5f7ddb14SDimitry Andric   // Destroy the process. This will call the virtual function DoDestroy under
497*5f7ddb14SDimitry Andric   // the hood, giving our derived class a chance to do the ncessary tear down.
498af732203SDimitry Andric   DestroyImpl(false);
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   // Clear our broadcaster before we proceed with destroying
5010b57cec5SDimitry Andric   Broadcaster::Clear();
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   // Do any cleanup needed prior to being destructed... Subclasses that
5040b57cec5SDimitry Andric   // override this method should call this superclass method as well.
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   // We need to destroy the loader before the derived Process class gets
5070b57cec5SDimitry Andric   // destroyed since it is very likely that undoing the loader will require
5080b57cec5SDimitry Andric   // access to the real process.
5090b57cec5SDimitry Andric   m_dynamic_checkers_up.reset();
5100b57cec5SDimitry Andric   m_abi_sp.reset();
5110b57cec5SDimitry Andric   m_os_up.reset();
5120b57cec5SDimitry Andric   m_system_runtime_up.reset();
5130b57cec5SDimitry Andric   m_dyld_up.reset();
5140b57cec5SDimitry Andric   m_jit_loaders_up.reset();
5155ffd83dbSDimitry Andric   m_thread_plans.Clear();
5160b57cec5SDimitry Andric   m_thread_list_real.Destroy();
5170b57cec5SDimitry Andric   m_thread_list.Destroy();
5180b57cec5SDimitry Andric   m_extended_thread_list.Destroy();
5190b57cec5SDimitry Andric   m_queue_list.Clear();
5200b57cec5SDimitry Andric   m_queue_list_stop_id = 0;
5210b57cec5SDimitry Andric   std::vector<Notifications> empty_notifications;
5220b57cec5SDimitry Andric   m_notifications.swap(empty_notifications);
5230b57cec5SDimitry Andric   m_image_tokens.clear();
5240b57cec5SDimitry Andric   m_memory_cache.Clear();
5250b57cec5SDimitry Andric   m_allocated_memory_cache.Clear();
5260b57cec5SDimitry Andric   {
5270b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5280b57cec5SDimitry Andric     m_language_runtimes.clear();
5290b57cec5SDimitry Andric   }
5300b57cec5SDimitry Andric   m_instrumentation_runtimes.clear();
5310b57cec5SDimitry Andric   m_next_event_action_up.reset();
5320b57cec5SDimitry Andric   // Clear the last natural stop ID since it has a strong reference to this
5330b57cec5SDimitry Andric   // process
5340b57cec5SDimitry Andric   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
5350b57cec5SDimitry Andric   //#ifdef LLDB_CONFIGURATION_DEBUG
5360b57cec5SDimitry Andric   //    StreamFile s(stdout, false);
5370b57cec5SDimitry Andric   //    EventSP event_sp;
5380b57cec5SDimitry Andric   //    while (m_private_state_listener_sp->GetNextEvent(event_sp))
5390b57cec5SDimitry Andric   //    {
5400b57cec5SDimitry Andric   //        event_sp->Dump (&s);
5410b57cec5SDimitry Andric   //        s.EOL();
5420b57cec5SDimitry Andric   //    }
5430b57cec5SDimitry Andric   //#endif
5440b57cec5SDimitry Andric   // We have to be very careful here as the m_private_state_listener might
5450b57cec5SDimitry Andric   // contain events that have ProcessSP values in them which can keep this
5460b57cec5SDimitry Andric   // process around forever. These events need to be cleared out.
5470b57cec5SDimitry Andric   m_private_state_listener_sp->Clear();
5480b57cec5SDimitry Andric   m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
5490b57cec5SDimitry Andric   m_public_run_lock.SetStopped();
5500b57cec5SDimitry Andric   m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
5510b57cec5SDimitry Andric   m_private_run_lock.SetStopped();
5520b57cec5SDimitry Andric   m_structured_data_plugin_map.clear();
5530b57cec5SDimitry Andric }
5540b57cec5SDimitry Andric 
RegisterNotificationCallbacks(const Notifications & callbacks)5550b57cec5SDimitry Andric void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
5560b57cec5SDimitry Andric   m_notifications.push_back(callbacks);
5570b57cec5SDimitry Andric   if (callbacks.initialize != nullptr)
5580b57cec5SDimitry Andric     callbacks.initialize(callbacks.baton, this);
5590b57cec5SDimitry Andric }
5600b57cec5SDimitry Andric 
UnregisterNotificationCallbacks(const Notifications & callbacks)5610b57cec5SDimitry Andric bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
5620b57cec5SDimitry Andric   std::vector<Notifications>::iterator pos, end = m_notifications.end();
5630b57cec5SDimitry Andric   for (pos = m_notifications.begin(); pos != end; ++pos) {
5640b57cec5SDimitry Andric     if (pos->baton == callbacks.baton &&
5650b57cec5SDimitry Andric         pos->initialize == callbacks.initialize &&
5660b57cec5SDimitry Andric         pos->process_state_changed == callbacks.process_state_changed) {
5670b57cec5SDimitry Andric       m_notifications.erase(pos);
5680b57cec5SDimitry Andric       return true;
5690b57cec5SDimitry Andric     }
5700b57cec5SDimitry Andric   }
5710b57cec5SDimitry Andric   return false;
5720b57cec5SDimitry Andric }
5730b57cec5SDimitry Andric 
SynchronouslyNotifyStateChanged(StateType state)5740b57cec5SDimitry Andric void Process::SynchronouslyNotifyStateChanged(StateType state) {
5750b57cec5SDimitry Andric   std::vector<Notifications>::iterator notification_pos,
5760b57cec5SDimitry Andric       notification_end = m_notifications.end();
5770b57cec5SDimitry Andric   for (notification_pos = m_notifications.begin();
5780b57cec5SDimitry Andric        notification_pos != notification_end; ++notification_pos) {
5790b57cec5SDimitry Andric     if (notification_pos->process_state_changed)
5800b57cec5SDimitry Andric       notification_pos->process_state_changed(notification_pos->baton, this,
5810b57cec5SDimitry Andric                                               state);
5820b57cec5SDimitry Andric   }
5830b57cec5SDimitry Andric }
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric // FIXME: We need to do some work on events before the general Listener sees
5860b57cec5SDimitry Andric // them.
5870b57cec5SDimitry Andric // For instance if we are continuing from a breakpoint, we need to ensure that
5880b57cec5SDimitry Andric // we do the little "insert real insn, step & stop" trick.  But we can't do
5890b57cec5SDimitry Andric // that when the event is delivered by the broadcaster - since that is done on
5900b57cec5SDimitry Andric // the thread that is waiting for new events, so if we needed more than one
5910b57cec5SDimitry Andric // event for our handling, we would stall.  So instead we do it when we fetch
5920b57cec5SDimitry Andric // the event off of the queue.
5930b57cec5SDimitry Andric //
5940b57cec5SDimitry Andric 
GetNextEvent(EventSP & event_sp)5950b57cec5SDimitry Andric StateType Process::GetNextEvent(EventSP &event_sp) {
5960b57cec5SDimitry Andric   StateType state = eStateInvalid;
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
5990b57cec5SDimitry Andric                                             std::chrono::seconds(0)) &&
6000b57cec5SDimitry Andric       event_sp)
6010b57cec5SDimitry Andric     state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric   return state;
6040b57cec5SDimitry Andric }
6050b57cec5SDimitry Andric 
SyncIOHandler(uint32_t iohandler_id,const Timeout<std::micro> & timeout)6060b57cec5SDimitry Andric void Process::SyncIOHandler(uint32_t iohandler_id,
6070b57cec5SDimitry Andric                             const Timeout<std::micro> &timeout) {
6080b57cec5SDimitry Andric   // don't sync (potentially context switch) in case where there is no process
6090b57cec5SDimitry Andric   // IO
6100b57cec5SDimitry Andric   if (!m_process_input_reader)
6110b57cec5SDimitry Andric     return;
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric   auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
6140b57cec5SDimitry Andric 
6150b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
6160b57cec5SDimitry Andric   if (Result) {
6170b57cec5SDimitry Andric     LLDB_LOG(
6180b57cec5SDimitry Andric         log,
6190b57cec5SDimitry Andric         "waited from m_iohandler_sync to change from {0}. New value is {1}.",
6200b57cec5SDimitry Andric         iohandler_id, *Result);
6210b57cec5SDimitry Andric   } else {
6220b57cec5SDimitry Andric     LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
6230b57cec5SDimitry Andric              iohandler_id);
6240b57cec5SDimitry Andric   }
6250b57cec5SDimitry Andric }
6260b57cec5SDimitry Andric 
WaitForProcessToStop(const Timeout<std::micro> & timeout,EventSP * event_sp_ptr,bool wait_always,ListenerSP hijack_listener_sp,Stream * stream,bool use_run_lock)6270b57cec5SDimitry Andric StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
6280b57cec5SDimitry Andric                                         EventSP *event_sp_ptr, bool wait_always,
6290b57cec5SDimitry Andric                                         ListenerSP hijack_listener_sp,
6300b57cec5SDimitry Andric                                         Stream *stream, bool use_run_lock) {
6310b57cec5SDimitry Andric   // We can't just wait for a "stopped" event, because the stopped event may
6320b57cec5SDimitry Andric   // have restarted the target. We have to actually check each event, and in
6330b57cec5SDimitry Andric   // the case of a stopped event check the restarted flag on the event.
6340b57cec5SDimitry Andric   if (event_sp_ptr)
6350b57cec5SDimitry Andric     event_sp_ptr->reset();
6360b57cec5SDimitry Andric   StateType state = GetState();
6370b57cec5SDimitry Andric   // If we are exited or detached, we won't ever get back to any other valid
6380b57cec5SDimitry Andric   // state...
6390b57cec5SDimitry Andric   if (state == eStateDetached || state == eStateExited)
6400b57cec5SDimitry Andric     return state;
6410b57cec5SDimitry Andric 
6420b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
6430b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}", timeout);
6440b57cec5SDimitry Andric 
6450b57cec5SDimitry Andric   if (!wait_always && StateIsStoppedState(state, true) &&
6460b57cec5SDimitry Andric       StateIsStoppedState(GetPrivateState(), true)) {
6479dba64beSDimitry Andric     LLDB_LOGF(log,
6489dba64beSDimitry Andric               "Process::%s returning without waiting for events; process "
6490b57cec5SDimitry Andric               "private and public states are already 'stopped'.",
6500b57cec5SDimitry Andric               __FUNCTION__);
6510b57cec5SDimitry Andric     // We need to toggle the run lock as this won't get done in
6520b57cec5SDimitry Andric     // SetPublicState() if the process is hijacked.
6530b57cec5SDimitry Andric     if (hijack_listener_sp && use_run_lock)
6540b57cec5SDimitry Andric       m_public_run_lock.SetStopped();
6550b57cec5SDimitry Andric     return state;
6560b57cec5SDimitry Andric   }
6570b57cec5SDimitry Andric 
6580b57cec5SDimitry Andric   while (state != eStateInvalid) {
6590b57cec5SDimitry Andric     EventSP event_sp;
6600b57cec5SDimitry Andric     state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
6610b57cec5SDimitry Andric     if (event_sp_ptr && event_sp)
6620b57cec5SDimitry Andric       *event_sp_ptr = event_sp;
6630b57cec5SDimitry Andric 
6640b57cec5SDimitry Andric     bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
6650b57cec5SDimitry Andric     Process::HandleProcessStateChangedEvent(event_sp, stream,
6660b57cec5SDimitry Andric                                             pop_process_io_handler);
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric     switch (state) {
6690b57cec5SDimitry Andric     case eStateCrashed:
6700b57cec5SDimitry Andric     case eStateDetached:
6710b57cec5SDimitry Andric     case eStateExited:
6720b57cec5SDimitry Andric     case eStateUnloaded:
6730b57cec5SDimitry Andric       // We need to toggle the run lock as this won't get done in
6740b57cec5SDimitry Andric       // SetPublicState() if the process is hijacked.
6750b57cec5SDimitry Andric       if (hijack_listener_sp && use_run_lock)
6760b57cec5SDimitry Andric         m_public_run_lock.SetStopped();
6770b57cec5SDimitry Andric       return state;
6780b57cec5SDimitry Andric     case eStateStopped:
6790b57cec5SDimitry Andric       if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
6800b57cec5SDimitry Andric         continue;
6810b57cec5SDimitry Andric       else {
6820b57cec5SDimitry Andric         // We need to toggle the run lock as this won't get done in
6830b57cec5SDimitry Andric         // SetPublicState() if the process is hijacked.
6840b57cec5SDimitry Andric         if (hijack_listener_sp && use_run_lock)
6850b57cec5SDimitry Andric           m_public_run_lock.SetStopped();
6860b57cec5SDimitry Andric         return state;
6870b57cec5SDimitry Andric       }
6880b57cec5SDimitry Andric     default:
6890b57cec5SDimitry Andric       continue;
6900b57cec5SDimitry Andric     }
6910b57cec5SDimitry Andric   }
6920b57cec5SDimitry Andric   return state;
6930b57cec5SDimitry Andric }
6940b57cec5SDimitry Andric 
HandleProcessStateChangedEvent(const EventSP & event_sp,Stream * stream,bool & pop_process_io_handler)6950b57cec5SDimitry Andric bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
6960b57cec5SDimitry Andric                                              Stream *stream,
6970b57cec5SDimitry Andric                                              bool &pop_process_io_handler) {
6980b57cec5SDimitry Andric   const bool handle_pop = pop_process_io_handler;
6990b57cec5SDimitry Andric 
7000b57cec5SDimitry Andric   pop_process_io_handler = false;
7010b57cec5SDimitry Andric   ProcessSP process_sp =
7020b57cec5SDimitry Andric       Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
7030b57cec5SDimitry Andric 
7040b57cec5SDimitry Andric   if (!process_sp)
7050b57cec5SDimitry Andric     return false;
7060b57cec5SDimitry Andric 
7070b57cec5SDimitry Andric   StateType event_state =
7080b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
7090b57cec5SDimitry Andric   if (event_state == eStateInvalid)
7100b57cec5SDimitry Andric     return false;
7110b57cec5SDimitry Andric 
7120b57cec5SDimitry Andric   switch (event_state) {
7130b57cec5SDimitry Andric   case eStateInvalid:
7140b57cec5SDimitry Andric   case eStateUnloaded:
7150b57cec5SDimitry Andric   case eStateAttaching:
7160b57cec5SDimitry Andric   case eStateLaunching:
7170b57cec5SDimitry Andric   case eStateStepping:
7180b57cec5SDimitry Andric   case eStateDetached:
7190b57cec5SDimitry Andric     if (stream)
7200b57cec5SDimitry Andric       stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
7210b57cec5SDimitry Andric                      StateAsCString(event_state));
7220b57cec5SDimitry Andric     if (event_state == eStateDetached)
7230b57cec5SDimitry Andric       pop_process_io_handler = true;
7240b57cec5SDimitry Andric     break;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   case eStateConnected:
7270b57cec5SDimitry Andric   case eStateRunning:
7280b57cec5SDimitry Andric     // Don't be chatty when we run...
7290b57cec5SDimitry Andric     break;
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   case eStateExited:
7320b57cec5SDimitry Andric     if (stream)
7330b57cec5SDimitry Andric       process_sp->GetStatus(*stream);
7340b57cec5SDimitry Andric     pop_process_io_handler = true;
7350b57cec5SDimitry Andric     break;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   case eStateStopped:
7380b57cec5SDimitry Andric   case eStateCrashed:
7390b57cec5SDimitry Andric   case eStateSuspended:
7400b57cec5SDimitry Andric     // Make sure the program hasn't been auto-restarted:
7410b57cec5SDimitry Andric     if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
7420b57cec5SDimitry Andric       if (stream) {
7430b57cec5SDimitry Andric         size_t num_reasons =
7440b57cec5SDimitry Andric             Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
7450b57cec5SDimitry Andric         if (num_reasons > 0) {
7460b57cec5SDimitry Andric           // FIXME: Do we want to report this, or would that just be annoyingly
7470b57cec5SDimitry Andric           // chatty?
7480b57cec5SDimitry Andric           if (num_reasons == 1) {
7490b57cec5SDimitry Andric             const char *reason =
7500b57cec5SDimitry Andric                 Process::ProcessEventData::GetRestartedReasonAtIndex(
7510b57cec5SDimitry Andric                     event_sp.get(), 0);
7520b57cec5SDimitry Andric             stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
7530b57cec5SDimitry Andric                            process_sp->GetID(),
7540b57cec5SDimitry Andric                            reason ? reason : "<UNKNOWN REASON>");
7550b57cec5SDimitry Andric           } else {
7560b57cec5SDimitry Andric             stream->Printf("Process %" PRIu64
7570b57cec5SDimitry Andric                            " stopped and restarted, reasons:\n",
7580b57cec5SDimitry Andric                            process_sp->GetID());
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric             for (size_t i = 0; i < num_reasons; i++) {
7610b57cec5SDimitry Andric               const char *reason =
7620b57cec5SDimitry Andric                   Process::ProcessEventData::GetRestartedReasonAtIndex(
7630b57cec5SDimitry Andric                       event_sp.get(), i);
7640b57cec5SDimitry Andric               stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
7650b57cec5SDimitry Andric             }
7660b57cec5SDimitry Andric           }
7670b57cec5SDimitry Andric         }
7680b57cec5SDimitry Andric       }
7690b57cec5SDimitry Andric     } else {
7700b57cec5SDimitry Andric       StopInfoSP curr_thread_stop_info_sp;
7710b57cec5SDimitry Andric       // Lock the thread list so it doesn't change on us, this is the scope for
7720b57cec5SDimitry Andric       // the locker:
7730b57cec5SDimitry Andric       {
7740b57cec5SDimitry Andric         ThreadList &thread_list = process_sp->GetThreadList();
7750b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
7760b57cec5SDimitry Andric 
7770b57cec5SDimitry Andric         ThreadSP curr_thread(thread_list.GetSelectedThread());
7780b57cec5SDimitry Andric         ThreadSP thread;
7790b57cec5SDimitry Andric         StopReason curr_thread_stop_reason = eStopReasonInvalid;
780*5f7ddb14SDimitry Andric         bool prefer_curr_thread = false;
781*5f7ddb14SDimitry Andric         if (curr_thread && curr_thread->IsValid()) {
7820b57cec5SDimitry Andric           curr_thread_stop_reason = curr_thread->GetStopReason();
783*5f7ddb14SDimitry Andric           switch (curr_thread_stop_reason) {
784*5f7ddb14SDimitry Andric           case eStopReasonNone:
785*5f7ddb14SDimitry Andric           case eStopReasonInvalid:
786*5f7ddb14SDimitry Andric             // Don't prefer the current thread if it didn't stop for a reason.
787*5f7ddb14SDimitry Andric             break;
788*5f7ddb14SDimitry Andric           case eStopReasonSignal: {
789*5f7ddb14SDimitry Andric             // We need to do the same computation we do for other threads
790*5f7ddb14SDimitry Andric             // below in case the current thread happens to be the one that
791*5f7ddb14SDimitry Andric             // stopped for the no-stop signal.
792*5f7ddb14SDimitry Andric             uint64_t signo = curr_thread->GetStopInfo()->GetValue();
793*5f7ddb14SDimitry Andric             if (process_sp->GetUnixSignals()->GetShouldStop(signo))
794*5f7ddb14SDimitry Andric               prefer_curr_thread = true;
795*5f7ddb14SDimitry Andric           } break;
796*5f7ddb14SDimitry Andric           default:
797*5f7ddb14SDimitry Andric             prefer_curr_thread = true;
798*5f7ddb14SDimitry Andric             break;
799*5f7ddb14SDimitry Andric           }
8000b57cec5SDimitry Andric           curr_thread_stop_info_sp = curr_thread->GetStopInfo();
8010b57cec5SDimitry Andric         }
802*5f7ddb14SDimitry Andric 
803*5f7ddb14SDimitry Andric         if (!prefer_curr_thread) {
8040b57cec5SDimitry Andric           // Prefer a thread that has just completed its plan over another
8050b57cec5SDimitry Andric           // thread as current thread.
8060b57cec5SDimitry Andric           ThreadSP plan_thread;
8070b57cec5SDimitry Andric           ThreadSP other_thread;
8080b57cec5SDimitry Andric 
8090b57cec5SDimitry Andric           const size_t num_threads = thread_list.GetSize();
8100b57cec5SDimitry Andric           size_t i;
8110b57cec5SDimitry Andric           for (i = 0; i < num_threads; ++i) {
8120b57cec5SDimitry Andric             thread = thread_list.GetThreadAtIndex(i);
8130b57cec5SDimitry Andric             StopReason thread_stop_reason = thread->GetStopReason();
8140b57cec5SDimitry Andric             switch (thread_stop_reason) {
8150b57cec5SDimitry Andric             case eStopReasonInvalid:
8160b57cec5SDimitry Andric             case eStopReasonNone:
8170b57cec5SDimitry Andric               break;
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric             case eStopReasonSignal: {
8200b57cec5SDimitry Andric               // Don't select a signal thread if we weren't going to stop at
8210b57cec5SDimitry Andric               // that signal.  We have to have had another reason for stopping
8220b57cec5SDimitry Andric               // here, and the user doesn't want to see this thread.
8230b57cec5SDimitry Andric               uint64_t signo = thread->GetStopInfo()->GetValue();
8240b57cec5SDimitry Andric               if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
8250b57cec5SDimitry Andric                 if (!other_thread)
8260b57cec5SDimitry Andric                   other_thread = thread;
8270b57cec5SDimitry Andric               }
8280b57cec5SDimitry Andric               break;
8290b57cec5SDimitry Andric             }
8300b57cec5SDimitry Andric             case eStopReasonTrace:
8310b57cec5SDimitry Andric             case eStopReasonBreakpoint:
8320b57cec5SDimitry Andric             case eStopReasonWatchpoint:
8330b57cec5SDimitry Andric             case eStopReasonException:
8340b57cec5SDimitry Andric             case eStopReasonExec:
835*5f7ddb14SDimitry Andric             case eStopReasonFork:
836*5f7ddb14SDimitry Andric             case eStopReasonVFork:
837*5f7ddb14SDimitry Andric             case eStopReasonVForkDone:
8380b57cec5SDimitry Andric             case eStopReasonThreadExiting:
8390b57cec5SDimitry Andric             case eStopReasonInstrumentation:
840*5f7ddb14SDimitry Andric             case eStopReasonProcessorTrace:
8410b57cec5SDimitry Andric               if (!other_thread)
8420b57cec5SDimitry Andric                 other_thread = thread;
8430b57cec5SDimitry Andric               break;
8440b57cec5SDimitry Andric             case eStopReasonPlanComplete:
8450b57cec5SDimitry Andric               if (!plan_thread)
8460b57cec5SDimitry Andric                 plan_thread = thread;
8470b57cec5SDimitry Andric               break;
8480b57cec5SDimitry Andric             }
8490b57cec5SDimitry Andric           }
8500b57cec5SDimitry Andric           if (plan_thread)
8510b57cec5SDimitry Andric             thread_list.SetSelectedThreadByID(plan_thread->GetID());
8520b57cec5SDimitry Andric           else if (other_thread)
8530b57cec5SDimitry Andric             thread_list.SetSelectedThreadByID(other_thread->GetID());
8540b57cec5SDimitry Andric           else {
8550b57cec5SDimitry Andric             if (curr_thread && curr_thread->IsValid())
8560b57cec5SDimitry Andric               thread = curr_thread;
8570b57cec5SDimitry Andric             else
8580b57cec5SDimitry Andric               thread = thread_list.GetThreadAtIndex(0);
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric             if (thread)
8610b57cec5SDimitry Andric               thread_list.SetSelectedThreadByID(thread->GetID());
8620b57cec5SDimitry Andric           }
8630b57cec5SDimitry Andric         }
8640b57cec5SDimitry Andric       }
8650b57cec5SDimitry Andric       // Drop the ThreadList mutex by here, since GetThreadStatus below might
8660b57cec5SDimitry Andric       // have to run code, e.g. for Data formatters, and if we hold the
8670b57cec5SDimitry Andric       // ThreadList mutex, then the process is going to have a hard time
8680b57cec5SDimitry Andric       // restarting the process.
8690b57cec5SDimitry Andric       if (stream) {
8700b57cec5SDimitry Andric         Debugger &debugger = process_sp->GetTarget().GetDebugger();
8710b57cec5SDimitry Andric         if (debugger.GetTargetList().GetSelectedTarget().get() ==
8720b57cec5SDimitry Andric             &process_sp->GetTarget()) {
8735ffd83dbSDimitry Andric           ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
8745ffd83dbSDimitry Andric 
8755ffd83dbSDimitry Andric           if (!thread_sp || !thread_sp->IsValid())
8765ffd83dbSDimitry Andric             return false;
8775ffd83dbSDimitry Andric 
8780b57cec5SDimitry Andric           const bool only_threads_with_stop_reason = true;
8795ffd83dbSDimitry Andric           const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
8800b57cec5SDimitry Andric           const uint32_t num_frames = 1;
8810b57cec5SDimitry Andric           const uint32_t num_frames_with_source = 1;
8820b57cec5SDimitry Andric           const bool stop_format = true;
8835ffd83dbSDimitry Andric 
8840b57cec5SDimitry Andric           process_sp->GetStatus(*stream);
8850b57cec5SDimitry Andric           process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
8860b57cec5SDimitry Andric                                       start_frame, num_frames,
8870b57cec5SDimitry Andric                                       num_frames_with_source,
8880b57cec5SDimitry Andric                                       stop_format);
8890b57cec5SDimitry Andric           if (curr_thread_stop_info_sp) {
8900b57cec5SDimitry Andric             lldb::addr_t crashing_address;
8910b57cec5SDimitry Andric             ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
8920b57cec5SDimitry Andric                 curr_thread_stop_info_sp, &crashing_address);
8930b57cec5SDimitry Andric             if (valobj_sp) {
8940b57cec5SDimitry Andric               const ValueObject::GetExpressionPathFormat format =
8950b57cec5SDimitry Andric                   ValueObject::GetExpressionPathFormat::
8960b57cec5SDimitry Andric                       eGetExpressionPathFormatHonorPointers;
8970b57cec5SDimitry Andric               stream->PutCString("Likely cause: ");
8985ffd83dbSDimitry Andric               valobj_sp->GetExpressionPath(*stream, format);
8990b57cec5SDimitry Andric               stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
9000b57cec5SDimitry Andric             }
9010b57cec5SDimitry Andric           }
9020b57cec5SDimitry Andric         } else {
9030b57cec5SDimitry Andric           uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
9040b57cec5SDimitry Andric               process_sp->GetTarget().shared_from_this());
9050b57cec5SDimitry Andric           if (target_idx != UINT32_MAX)
9060b57cec5SDimitry Andric             stream->Printf("Target %d: (", target_idx);
9070b57cec5SDimitry Andric           else
9080b57cec5SDimitry Andric             stream->Printf("Target <unknown index>: (");
9090b57cec5SDimitry Andric           process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
9100b57cec5SDimitry Andric           stream->Printf(") stopped.\n");
9110b57cec5SDimitry Andric         }
9120b57cec5SDimitry Andric       }
9130b57cec5SDimitry Andric 
9140b57cec5SDimitry Andric       // Pop the process IO handler
9150b57cec5SDimitry Andric       pop_process_io_handler = true;
9160b57cec5SDimitry Andric     }
9170b57cec5SDimitry Andric     break;
9180b57cec5SDimitry Andric   }
9190b57cec5SDimitry Andric 
9200b57cec5SDimitry Andric   if (handle_pop && pop_process_io_handler)
9210b57cec5SDimitry Andric     process_sp->PopProcessIOHandler();
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric   return true;
9240b57cec5SDimitry Andric }
9250b57cec5SDimitry Andric 
HijackProcessEvents(ListenerSP listener_sp)9260b57cec5SDimitry Andric bool Process::HijackProcessEvents(ListenerSP listener_sp) {
9270b57cec5SDimitry Andric   if (listener_sp) {
9280b57cec5SDimitry Andric     return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
9290b57cec5SDimitry Andric                                               eBroadcastBitInterrupt);
9300b57cec5SDimitry Andric   } else
9310b57cec5SDimitry Andric     return false;
9320b57cec5SDimitry Andric }
9330b57cec5SDimitry Andric 
RestoreProcessEvents()9340b57cec5SDimitry Andric void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
9350b57cec5SDimitry Andric 
GetStateChangedEvents(EventSP & event_sp,const Timeout<std::micro> & timeout,ListenerSP hijack_listener_sp)9360b57cec5SDimitry Andric StateType Process::GetStateChangedEvents(EventSP &event_sp,
9370b57cec5SDimitry Andric                                          const Timeout<std::micro> &timeout,
9380b57cec5SDimitry Andric                                          ListenerSP hijack_listener_sp) {
9390b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
9400b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
9410b57cec5SDimitry Andric 
9420b57cec5SDimitry Andric   ListenerSP listener_sp = hijack_listener_sp;
9430b57cec5SDimitry Andric   if (!listener_sp)
9440b57cec5SDimitry Andric     listener_sp = m_listener_sp;
9450b57cec5SDimitry Andric 
9460b57cec5SDimitry Andric   StateType state = eStateInvalid;
9470b57cec5SDimitry Andric   if (listener_sp->GetEventForBroadcasterWithType(
9480b57cec5SDimitry Andric           this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
9490b57cec5SDimitry Andric           timeout)) {
9500b57cec5SDimitry Andric     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
9510b57cec5SDimitry Andric       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
9520b57cec5SDimitry Andric     else
9530b57cec5SDimitry Andric       LLDB_LOG(log, "got no event or was interrupted.");
9540b57cec5SDimitry Andric   }
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
9570b57cec5SDimitry Andric   return state;
9580b57cec5SDimitry Andric }
9590b57cec5SDimitry Andric 
PeekAtStateChangedEvents()9600b57cec5SDimitry Andric Event *Process::PeekAtStateChangedEvents() {
9610b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
9620b57cec5SDimitry Andric 
9639dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
9640b57cec5SDimitry Andric 
9650b57cec5SDimitry Andric   Event *event_ptr;
9660b57cec5SDimitry Andric   event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
9670b57cec5SDimitry Andric       this, eBroadcastBitStateChanged);
9680b57cec5SDimitry Andric   if (log) {
9690b57cec5SDimitry Andric     if (event_ptr) {
9709dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
9710b57cec5SDimitry Andric                 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
9720b57cec5SDimitry Andric     } else {
9739dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
9740b57cec5SDimitry Andric     }
9750b57cec5SDimitry Andric   }
9760b57cec5SDimitry Andric   return event_ptr;
9770b57cec5SDimitry Andric }
9780b57cec5SDimitry Andric 
9790b57cec5SDimitry Andric StateType
GetStateChangedEventsPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout)9800b57cec5SDimitry Andric Process::GetStateChangedEventsPrivate(EventSP &event_sp,
9810b57cec5SDimitry Andric                                       const Timeout<std::micro> &timeout) {
9820b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
9830b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
9840b57cec5SDimitry Andric 
9850b57cec5SDimitry Andric   StateType state = eStateInvalid;
9860b57cec5SDimitry Andric   if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
9870b57cec5SDimitry Andric           &m_private_state_broadcaster,
9880b57cec5SDimitry Andric           eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
9890b57cec5SDimitry Andric           timeout))
9900b57cec5SDimitry Andric     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
9910b57cec5SDimitry Andric       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
9920b57cec5SDimitry Andric 
9930b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
9940b57cec5SDimitry Andric            state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
9950b57cec5SDimitry Andric   return state;
9960b57cec5SDimitry Andric }
9970b57cec5SDimitry Andric 
GetEventsPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout,bool control_only)9980b57cec5SDimitry Andric bool Process::GetEventsPrivate(EventSP &event_sp,
9990b57cec5SDimitry Andric                                const Timeout<std::micro> &timeout,
10000b57cec5SDimitry Andric                                bool control_only) {
10010b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
10020b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   if (control_only)
10050b57cec5SDimitry Andric     return m_private_state_listener_sp->GetEventForBroadcaster(
10060b57cec5SDimitry Andric         &m_private_state_control_broadcaster, event_sp, timeout);
10070b57cec5SDimitry Andric   else
10080b57cec5SDimitry Andric     return m_private_state_listener_sp->GetEvent(event_sp, timeout);
10090b57cec5SDimitry Andric }
10100b57cec5SDimitry Andric 
IsRunning() const10110b57cec5SDimitry Andric bool Process::IsRunning() const {
10120b57cec5SDimitry Andric   return StateIsRunningState(m_public_state.GetValue());
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
GetExitStatus()10150b57cec5SDimitry Andric int Process::GetExitStatus() {
10160b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateExited)
10190b57cec5SDimitry Andric     return m_exit_status;
10200b57cec5SDimitry Andric   return -1;
10210b57cec5SDimitry Andric }
10220b57cec5SDimitry Andric 
GetExitDescription()10230b57cec5SDimitry Andric const char *Process::GetExitDescription() {
10240b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10250b57cec5SDimitry Andric 
10260b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
10270b57cec5SDimitry Andric     return m_exit_string.c_str();
10280b57cec5SDimitry Andric   return nullptr;
10290b57cec5SDimitry Andric }
10300b57cec5SDimitry Andric 
SetExitStatus(int status,const char * cstr)10310b57cec5SDimitry Andric bool Process::SetExitStatus(int status, const char *cstr) {
10320b57cec5SDimitry Andric   // Use a mutex to protect setting the exit status.
10330b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10340b57cec5SDimitry Andric 
10350b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
10360b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
10379dba64beSDimitry Andric   LLDB_LOGF(
10389dba64beSDimitry Andric       log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
10399dba64beSDimitry Andric       status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
10400b57cec5SDimitry Andric 
10410b57cec5SDimitry Andric   // We were already in the exited state
10420b57cec5SDimitry Andric   if (m_private_state.GetValue() == eStateExited) {
10439dba64beSDimitry Andric     LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
10440b57cec5SDimitry Andric                    "state was already set to eStateExited");
10450b57cec5SDimitry Andric     return false;
10460b57cec5SDimitry Andric   }
10470b57cec5SDimitry Andric 
10480b57cec5SDimitry Andric   m_exit_status = status;
10490b57cec5SDimitry Andric   if (cstr)
10500b57cec5SDimitry Andric     m_exit_string = cstr;
10510b57cec5SDimitry Andric   else
10520b57cec5SDimitry Andric     m_exit_string.clear();
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   // Clear the last natural stop ID since it has a strong reference to this
10550b57cec5SDimitry Andric   // process
10560b57cec5SDimitry Andric   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
10570b57cec5SDimitry Andric 
10580b57cec5SDimitry Andric   SetPrivateState(eStateExited);
10590b57cec5SDimitry Andric 
10600b57cec5SDimitry Andric   // Allow subclasses to do some cleanup
10610b57cec5SDimitry Andric   DidExit();
10620b57cec5SDimitry Andric 
10630b57cec5SDimitry Andric   return true;
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric 
IsAlive()10660b57cec5SDimitry Andric bool Process::IsAlive() {
10670b57cec5SDimitry Andric   switch (m_private_state.GetValue()) {
10680b57cec5SDimitry Andric   case eStateConnected:
10690b57cec5SDimitry Andric   case eStateAttaching:
10700b57cec5SDimitry Andric   case eStateLaunching:
10710b57cec5SDimitry Andric   case eStateStopped:
10720b57cec5SDimitry Andric   case eStateRunning:
10730b57cec5SDimitry Andric   case eStateStepping:
10740b57cec5SDimitry Andric   case eStateCrashed:
10750b57cec5SDimitry Andric   case eStateSuspended:
10760b57cec5SDimitry Andric     return true;
10770b57cec5SDimitry Andric   default:
10780b57cec5SDimitry Andric     return false;
10790b57cec5SDimitry Andric   }
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric // This static callback can be used to watch for local child processes on the
10830b57cec5SDimitry Andric // current host. The child process exits, the process will be found in the
10840b57cec5SDimitry Andric // global target list (we want to be completely sure that the
10850b57cec5SDimitry Andric // lldb_private::Process doesn't go away before we can deliver the signal.
SetProcessExitStatus(lldb::pid_t pid,bool exited,int signo,int exit_status)10860b57cec5SDimitry Andric bool Process::SetProcessExitStatus(
10870b57cec5SDimitry Andric     lldb::pid_t pid, bool exited,
10880b57cec5SDimitry Andric     int signo,      // Zero for no signal
10890b57cec5SDimitry Andric     int exit_status // Exit value of process if signal is zero
10900b57cec5SDimitry Andric     ) {
10910b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
10929dba64beSDimitry Andric   LLDB_LOGF(log,
10939dba64beSDimitry Andric             "Process::SetProcessExitStatus (pid=%" PRIu64
10940b57cec5SDimitry Andric             ", exited=%i, signal=%i, exit_status=%i)\n",
10950b57cec5SDimitry Andric             pid, exited, signo, exit_status);
10960b57cec5SDimitry Andric 
10970b57cec5SDimitry Andric   if (exited) {
10980b57cec5SDimitry Andric     TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
10990b57cec5SDimitry Andric     if (target_sp) {
11000b57cec5SDimitry Andric       ProcessSP process_sp(target_sp->GetProcessSP());
11010b57cec5SDimitry Andric       if (process_sp) {
11020b57cec5SDimitry Andric         const char *signal_cstr = nullptr;
11030b57cec5SDimitry Andric         if (signo)
11040b57cec5SDimitry Andric           signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric         process_sp->SetExitStatus(exit_status, signal_cstr);
11070b57cec5SDimitry Andric       }
11080b57cec5SDimitry Andric     }
11090b57cec5SDimitry Andric     return true;
11100b57cec5SDimitry Andric   }
11110b57cec5SDimitry Andric   return false;
11120b57cec5SDimitry Andric }
11130b57cec5SDimitry Andric 
UpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)1114af732203SDimitry Andric bool Process::UpdateThreadList(ThreadList &old_thread_list,
1115af732203SDimitry Andric                                ThreadList &new_thread_list) {
1116af732203SDimitry Andric   m_thread_plans.ClearThreadCache();
1117af732203SDimitry Andric   return DoUpdateThreadList(old_thread_list, new_thread_list);
1118af732203SDimitry Andric }
1119af732203SDimitry Andric 
UpdateThreadListIfNeeded()11200b57cec5SDimitry Andric void Process::UpdateThreadListIfNeeded() {
11210b57cec5SDimitry Andric   const uint32_t stop_id = GetStopID();
11220b57cec5SDimitry Andric   if (m_thread_list.GetSize(false) == 0 ||
11230b57cec5SDimitry Andric       stop_id != m_thread_list.GetStopID()) {
11245ffd83dbSDimitry Andric     bool clear_unused_threads = true;
11250b57cec5SDimitry Andric     const StateType state = GetPrivateState();
11260b57cec5SDimitry Andric     if (StateIsStoppedState(state, true)) {
11270b57cec5SDimitry Andric       std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
11285ffd83dbSDimitry Andric       m_thread_list.SetStopID(stop_id);
11295ffd83dbSDimitry Andric 
11300b57cec5SDimitry Andric       // m_thread_list does have its own mutex, but we need to hold onto the
11310b57cec5SDimitry Andric       // mutex between the call to UpdateThreadList(...) and the
11320b57cec5SDimitry Andric       // os->UpdateThreadList(...) so it doesn't change on us
11330b57cec5SDimitry Andric       ThreadList &old_thread_list = m_thread_list;
11340b57cec5SDimitry Andric       ThreadList real_thread_list(this);
11350b57cec5SDimitry Andric       ThreadList new_thread_list(this);
11360b57cec5SDimitry Andric       // Always update the thread list with the protocol specific thread list,
11370b57cec5SDimitry Andric       // but only update if "true" is returned
11380b57cec5SDimitry Andric       if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
11390b57cec5SDimitry Andric         // Don't call into the OperatingSystem to update the thread list if we
11400b57cec5SDimitry Andric         // are shutting down, since that may call back into the SBAPI's,
11410b57cec5SDimitry Andric         // requiring the API lock which is already held by whoever is shutting
11420b57cec5SDimitry Andric         // us down, causing a deadlock.
11430b57cec5SDimitry Andric         OperatingSystem *os = GetOperatingSystem();
11440b57cec5SDimitry Andric         if (os && !m_destroy_in_process) {
11450b57cec5SDimitry Andric           // Clear any old backing threads where memory threads might have been
11460b57cec5SDimitry Andric           // backed by actual threads from the lldb_private::Process subclass
11470b57cec5SDimitry Andric           size_t num_old_threads = old_thread_list.GetSize(false);
11480b57cec5SDimitry Andric           for (size_t i = 0; i < num_old_threads; ++i)
11490b57cec5SDimitry Andric             old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
11505ffd83dbSDimitry Andric           // See if the OS plugin reports all threads.  If it does, then
11515ffd83dbSDimitry Andric           // it is safe to clear unseen thread's plans here.  Otherwise we
11525ffd83dbSDimitry Andric           // should preserve them in case they show up again:
11535ffd83dbSDimitry Andric           clear_unused_threads = GetOSPluginReportsAllThreads();
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric           // Turn off dynamic types to ensure we don't run any expressions.
11560b57cec5SDimitry Andric           // Objective-C can run an expression to determine if a SBValue is a
11570b57cec5SDimitry Andric           // dynamic type or not and we need to avoid this. OperatingSystem
11580b57cec5SDimitry Andric           // plug-ins can't run expressions that require running code...
11590b57cec5SDimitry Andric 
11600b57cec5SDimitry Andric           Target &target = GetTarget();
11610b57cec5SDimitry Andric           const lldb::DynamicValueType saved_prefer_dynamic =
11620b57cec5SDimitry Andric               target.GetPreferDynamicValue();
11630b57cec5SDimitry Andric           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
11640b57cec5SDimitry Andric             target.SetPreferDynamicValue(lldb::eNoDynamicValues);
11650b57cec5SDimitry Andric 
11660b57cec5SDimitry Andric           // Now let the OperatingSystem plug-in update the thread list
11670b57cec5SDimitry Andric 
11680b57cec5SDimitry Andric           os->UpdateThreadList(
11690b57cec5SDimitry Andric               old_thread_list, // Old list full of threads created by OS plug-in
11700b57cec5SDimitry Andric               real_thread_list, // The actual thread list full of threads
11710b57cec5SDimitry Andric                                 // created by each lldb_private::Process
11720b57cec5SDimitry Andric                                 // subclass
11730b57cec5SDimitry Andric               new_thread_list); // The new thread list that we will show to the
11740b57cec5SDimitry Andric                                 // user that gets filled in
11750b57cec5SDimitry Andric 
11760b57cec5SDimitry Andric           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
11770b57cec5SDimitry Andric             target.SetPreferDynamicValue(saved_prefer_dynamic);
11780b57cec5SDimitry Andric         } else {
11790b57cec5SDimitry Andric           // No OS plug-in, the new thread list is the same as the real thread
11805ffd83dbSDimitry Andric           // list.
11810b57cec5SDimitry Andric           new_thread_list = real_thread_list;
11820b57cec5SDimitry Andric         }
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric         m_thread_list_real.Update(real_thread_list);
11850b57cec5SDimitry Andric         m_thread_list.Update(new_thread_list);
11860b57cec5SDimitry Andric         m_thread_list.SetStopID(stop_id);
11870b57cec5SDimitry Andric 
11880b57cec5SDimitry Andric         if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
11890b57cec5SDimitry Andric           // Clear any extended threads that we may have accumulated previously
11900b57cec5SDimitry Andric           m_extended_thread_list.Clear();
11910b57cec5SDimitry Andric           m_extended_thread_stop_id = GetLastNaturalStopID();
11920b57cec5SDimitry Andric 
11930b57cec5SDimitry Andric           m_queue_list.Clear();
11940b57cec5SDimitry Andric           m_queue_list_stop_id = GetLastNaturalStopID();
11950b57cec5SDimitry Andric         }
11960b57cec5SDimitry Andric       }
11975ffd83dbSDimitry Andric       // Now update the plan stack map.
11985ffd83dbSDimitry Andric       // If we do have an OS plugin, any absent real threads in the
11995ffd83dbSDimitry Andric       // m_thread_list have already been removed from the ThreadPlanStackMap.
12005ffd83dbSDimitry Andric       // So any remaining threads are OS Plugin threads, and those we want to
12015ffd83dbSDimitry Andric       // preserve in case they show up again.
12025ffd83dbSDimitry Andric       m_thread_plans.Update(m_thread_list, clear_unused_threads);
12030b57cec5SDimitry Andric     }
12040b57cec5SDimitry Andric   }
12050b57cec5SDimitry Andric }
12060b57cec5SDimitry Andric 
FindThreadPlans(lldb::tid_t tid)12075ffd83dbSDimitry Andric ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
12085ffd83dbSDimitry Andric   return m_thread_plans.Find(tid);
12095ffd83dbSDimitry Andric }
12105ffd83dbSDimitry Andric 
PruneThreadPlansForTID(lldb::tid_t tid)12115ffd83dbSDimitry Andric bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
12125ffd83dbSDimitry Andric   return m_thread_plans.PrunePlansForTID(tid);
12135ffd83dbSDimitry Andric }
12145ffd83dbSDimitry Andric 
PruneThreadPlans()12155ffd83dbSDimitry Andric void Process::PruneThreadPlans() {
12165ffd83dbSDimitry Andric   m_thread_plans.Update(GetThreadList(), true, false);
12175ffd83dbSDimitry Andric }
12185ffd83dbSDimitry Andric 
DumpThreadPlansForTID(Stream & strm,lldb::tid_t tid,lldb::DescriptionLevel desc_level,bool internal,bool condense_trivial,bool skip_unreported_plans)12195ffd83dbSDimitry Andric bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
12205ffd83dbSDimitry Andric                                     lldb::DescriptionLevel desc_level,
12215ffd83dbSDimitry Andric                                     bool internal, bool condense_trivial,
12225ffd83dbSDimitry Andric                                     bool skip_unreported_plans) {
12235ffd83dbSDimitry Andric   return m_thread_plans.DumpPlansForTID(
12245ffd83dbSDimitry Andric       strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
12255ffd83dbSDimitry Andric }
DumpThreadPlans(Stream & strm,lldb::DescriptionLevel desc_level,bool internal,bool condense_trivial,bool skip_unreported_plans)12265ffd83dbSDimitry Andric void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
12275ffd83dbSDimitry Andric                               bool internal, bool condense_trivial,
12285ffd83dbSDimitry Andric                               bool skip_unreported_plans) {
12295ffd83dbSDimitry Andric   m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
12305ffd83dbSDimitry Andric                            skip_unreported_plans);
12315ffd83dbSDimitry Andric }
12325ffd83dbSDimitry Andric 
UpdateQueueListIfNeeded()12330b57cec5SDimitry Andric void Process::UpdateQueueListIfNeeded() {
12340b57cec5SDimitry Andric   if (m_system_runtime_up) {
12350b57cec5SDimitry Andric     if (m_queue_list.GetSize() == 0 ||
12360b57cec5SDimitry Andric         m_queue_list_stop_id != GetLastNaturalStopID()) {
12370b57cec5SDimitry Andric       const StateType state = GetPrivateState();
12380b57cec5SDimitry Andric       if (StateIsStoppedState(state, true)) {
12390b57cec5SDimitry Andric         m_system_runtime_up->PopulateQueueList(m_queue_list);
12400b57cec5SDimitry Andric         m_queue_list_stop_id = GetLastNaturalStopID();
12410b57cec5SDimitry Andric       }
12420b57cec5SDimitry Andric     }
12430b57cec5SDimitry Andric   }
12440b57cec5SDimitry Andric }
12450b57cec5SDimitry Andric 
CreateOSPluginThread(lldb::tid_t tid,lldb::addr_t context)12460b57cec5SDimitry Andric ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
12470b57cec5SDimitry Andric   OperatingSystem *os = GetOperatingSystem();
12480b57cec5SDimitry Andric   if (os)
12490b57cec5SDimitry Andric     return os->CreateThread(tid, context);
12500b57cec5SDimitry Andric   return ThreadSP();
12510b57cec5SDimitry Andric }
12520b57cec5SDimitry Andric 
GetNextThreadIndexID(uint64_t thread_id)12530b57cec5SDimitry Andric uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
12540b57cec5SDimitry Andric   return AssignIndexIDToThread(thread_id);
12550b57cec5SDimitry Andric }
12560b57cec5SDimitry Andric 
HasAssignedIndexIDToThread(uint64_t thread_id)12570b57cec5SDimitry Andric bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
12580b57cec5SDimitry Andric   return (m_thread_id_to_index_id_map.find(thread_id) !=
12590b57cec5SDimitry Andric           m_thread_id_to_index_id_map.end());
12600b57cec5SDimitry Andric }
12610b57cec5SDimitry Andric 
AssignIndexIDToThread(uint64_t thread_id)12620b57cec5SDimitry Andric uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
12630b57cec5SDimitry Andric   uint32_t result = 0;
12640b57cec5SDimitry Andric   std::map<uint64_t, uint32_t>::iterator iterator =
12650b57cec5SDimitry Andric       m_thread_id_to_index_id_map.find(thread_id);
12660b57cec5SDimitry Andric   if (iterator == m_thread_id_to_index_id_map.end()) {
12670b57cec5SDimitry Andric     result = ++m_thread_index_id;
12680b57cec5SDimitry Andric     m_thread_id_to_index_id_map[thread_id] = result;
12690b57cec5SDimitry Andric   } else {
12700b57cec5SDimitry Andric     result = iterator->second;
12710b57cec5SDimitry Andric   }
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric   return result;
12740b57cec5SDimitry Andric }
12750b57cec5SDimitry Andric 
GetState()12760b57cec5SDimitry Andric StateType Process::GetState() {
12770b57cec5SDimitry Andric   return m_public_state.GetValue();
12780b57cec5SDimitry Andric }
12790b57cec5SDimitry Andric 
SetPublicState(StateType new_state,bool restarted)12800b57cec5SDimitry Andric void Process::SetPublicState(StateType new_state, bool restarted) {
12810b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
12820b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
12839dba64beSDimitry Andric   LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
12840b57cec5SDimitry Andric             StateAsCString(new_state), restarted);
12850b57cec5SDimitry Andric   const StateType old_state = m_public_state.GetValue();
12860b57cec5SDimitry Andric   m_public_state.SetValue(new_state);
12870b57cec5SDimitry Andric 
12880b57cec5SDimitry Andric   // On the transition from Run to Stopped, we unlock the writer end of the run
12890b57cec5SDimitry Andric   // lock.  The lock gets locked in Resume, which is the public API to tell the
12900b57cec5SDimitry Andric   // program to run.
12910b57cec5SDimitry Andric   if (!StateChangedIsExternallyHijacked()) {
12920b57cec5SDimitry Andric     if (new_state == eStateDetached) {
12939dba64beSDimitry Andric       LLDB_LOGF(log,
12940b57cec5SDimitry Andric                 "Process::SetPublicState (%s) -- unlocking run lock for detach",
12950b57cec5SDimitry Andric                 StateAsCString(new_state));
12960b57cec5SDimitry Andric       m_public_run_lock.SetStopped();
12970b57cec5SDimitry Andric     } else {
12980b57cec5SDimitry Andric       const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
12990b57cec5SDimitry Andric       const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
13000b57cec5SDimitry Andric       if ((old_state_is_stopped != new_state_is_stopped)) {
13010b57cec5SDimitry Andric         if (new_state_is_stopped && !restarted) {
13029dba64beSDimitry Andric           LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
13030b57cec5SDimitry Andric                     StateAsCString(new_state));
13040b57cec5SDimitry Andric           m_public_run_lock.SetStopped();
13050b57cec5SDimitry Andric         }
13060b57cec5SDimitry Andric       }
13070b57cec5SDimitry Andric     }
13080b57cec5SDimitry Andric   }
13090b57cec5SDimitry Andric }
13100b57cec5SDimitry Andric 
Resume()13110b57cec5SDimitry Andric Status Process::Resume() {
13120b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
13130b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
13149dba64beSDimitry Andric   LLDB_LOGF(log, "Process::Resume -- locking run lock");
13150b57cec5SDimitry Andric   if (!m_public_run_lock.TrySetRunning()) {
13160b57cec5SDimitry Andric     Status error("Resume request failed - process still running.");
13179dba64beSDimitry Andric     LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
13180b57cec5SDimitry Andric     return error;
13190b57cec5SDimitry Andric   }
13200b57cec5SDimitry Andric   Status error = PrivateResume();
13210b57cec5SDimitry Andric   if (!error.Success()) {
13220b57cec5SDimitry Andric     // Undo running state change
13230b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
13240b57cec5SDimitry Andric   }
13250b57cec5SDimitry Andric   return error;
13260b57cec5SDimitry Andric }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
13290b57cec5SDimitry Andric 
ResumeSynchronous(Stream * stream)13300b57cec5SDimitry Andric Status Process::ResumeSynchronous(Stream *stream) {
13310b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
13320b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
13339dba64beSDimitry Andric   LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
13340b57cec5SDimitry Andric   if (!m_public_run_lock.TrySetRunning()) {
13350b57cec5SDimitry Andric     Status error("Resume request failed - process still running.");
13369dba64beSDimitry Andric     LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
13370b57cec5SDimitry Andric     return error;
13380b57cec5SDimitry Andric   }
13390b57cec5SDimitry Andric 
13400b57cec5SDimitry Andric   ListenerSP listener_sp(
13410b57cec5SDimitry Andric       Listener::MakeListener(g_resume_sync_name));
13420b57cec5SDimitry Andric   HijackProcessEvents(listener_sp);
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric   Status error = PrivateResume();
13450b57cec5SDimitry Andric   if (error.Success()) {
1346*5f7ddb14SDimitry Andric     StateType state = WaitForProcessToStop(llvm::None, nullptr, true,
1347*5f7ddb14SDimitry Andric                                            listener_sp, stream);
13480b57cec5SDimitry Andric     const bool must_be_alive =
13490b57cec5SDimitry Andric         false; // eStateExited is ok, so this must be false
13500b57cec5SDimitry Andric     if (!StateIsStoppedState(state, must_be_alive))
13510b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
13520b57cec5SDimitry Andric           "process not in stopped state after synchronous resume: %s",
13530b57cec5SDimitry Andric           StateAsCString(state));
13540b57cec5SDimitry Andric   } else {
13550b57cec5SDimitry Andric     // Undo running state change
13560b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
13570b57cec5SDimitry Andric   }
13580b57cec5SDimitry Andric 
13590b57cec5SDimitry Andric   // Undo the hijacking of process events...
13600b57cec5SDimitry Andric   RestoreProcessEvents();
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   return error;
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
StateChangedIsExternallyHijacked()13650b57cec5SDimitry Andric bool Process::StateChangedIsExternallyHijacked() {
13660b57cec5SDimitry Andric   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
13670b57cec5SDimitry Andric     const char *hijacking_name = GetHijackingListenerName();
13680b57cec5SDimitry Andric     if (hijacking_name &&
13690b57cec5SDimitry Andric         strcmp(hijacking_name, g_resume_sync_name))
13700b57cec5SDimitry Andric       return true;
13710b57cec5SDimitry Andric   }
13720b57cec5SDimitry Andric   return false;
13730b57cec5SDimitry Andric }
13740b57cec5SDimitry Andric 
StateChangedIsHijackedForSynchronousResume()13750b57cec5SDimitry Andric bool Process::StateChangedIsHijackedForSynchronousResume() {
13760b57cec5SDimitry Andric   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
13770b57cec5SDimitry Andric     const char *hijacking_name = GetHijackingListenerName();
13780b57cec5SDimitry Andric     if (hijacking_name &&
13790b57cec5SDimitry Andric         strcmp(hijacking_name, g_resume_sync_name) == 0)
13800b57cec5SDimitry Andric       return true;
13810b57cec5SDimitry Andric   }
13820b57cec5SDimitry Andric   return false;
13830b57cec5SDimitry Andric }
13840b57cec5SDimitry Andric 
GetPrivateState()13850b57cec5SDimitry Andric StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
13860b57cec5SDimitry Andric 
SetPrivateState(StateType new_state)13870b57cec5SDimitry Andric void Process::SetPrivateState(StateType new_state) {
1388af732203SDimitry Andric   if (m_finalizing)
13890b57cec5SDimitry Andric     return;
13900b57cec5SDimitry Andric 
1391*5f7ddb14SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(
1392*5f7ddb14SDimitry Andric       LIBLLDB_LOG_STATE | LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_UNWIND));
13930b57cec5SDimitry Andric   bool state_changed = false;
13940b57cec5SDimitry Andric 
13959dba64beSDimitry Andric   LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
13960b57cec5SDimitry Andric 
13970b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
13980b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
13990b57cec5SDimitry Andric 
14000b57cec5SDimitry Andric   const StateType old_state = m_private_state.GetValueNoLock();
14010b57cec5SDimitry Andric   state_changed = old_state != new_state;
14020b57cec5SDimitry Andric 
14030b57cec5SDimitry Andric   const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
14040b57cec5SDimitry Andric   const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
14050b57cec5SDimitry Andric   if (old_state_is_stopped != new_state_is_stopped) {
14060b57cec5SDimitry Andric     if (new_state_is_stopped)
14070b57cec5SDimitry Andric       m_private_run_lock.SetStopped();
14080b57cec5SDimitry Andric     else
14090b57cec5SDimitry Andric       m_private_run_lock.SetRunning();
14100b57cec5SDimitry Andric   }
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric   if (state_changed) {
14130b57cec5SDimitry Andric     m_private_state.SetValueNoLock(new_state);
14140b57cec5SDimitry Andric     EventSP event_sp(
14150b57cec5SDimitry Andric         new Event(eBroadcastBitStateChanged,
14160b57cec5SDimitry Andric                   new ProcessEventData(shared_from_this(), new_state)));
14170b57cec5SDimitry Andric     if (StateIsStoppedState(new_state, false)) {
14180b57cec5SDimitry Andric       // Note, this currently assumes that all threads in the list stop when
14190b57cec5SDimitry Andric       // the process stops.  In the future we will want to support a debugging
14200b57cec5SDimitry Andric       // model where some threads continue to run while others are stopped.
14210b57cec5SDimitry Andric       // When that happens we will either need a way for the thread list to
14220b57cec5SDimitry Andric       // identify which threads are stopping or create a special thread list
14230b57cec5SDimitry Andric       // containing only threads which actually stopped.
14240b57cec5SDimitry Andric       //
14250b57cec5SDimitry Andric       // The process plugin is responsible for managing the actual behavior of
14260b57cec5SDimitry Andric       // the threads and should have stopped any threads that are going to stop
14270b57cec5SDimitry Andric       // before we get here.
14280b57cec5SDimitry Andric       m_thread_list.DidStop();
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric       m_mod_id.BumpStopID();
14310b57cec5SDimitry Andric       if (!m_mod_id.IsLastResumeForUserExpression())
14320b57cec5SDimitry Andric         m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
14330b57cec5SDimitry Andric       m_memory_cache.Clear();
14349dba64beSDimitry Andric       LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
14350b57cec5SDimitry Andric                 StateAsCString(new_state), m_mod_id.GetStopID());
14360b57cec5SDimitry Andric     }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric     m_private_state_broadcaster.BroadcastEvent(event_sp);
14390b57cec5SDimitry Andric   } else {
14409dba64beSDimitry Andric     LLDB_LOGF(log,
14410b57cec5SDimitry Andric               "Process::SetPrivateState (%s) state didn't change. Ignoring...",
14420b57cec5SDimitry Andric               StateAsCString(new_state));
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric }
14450b57cec5SDimitry Andric 
SetRunningUserExpression(bool on)14460b57cec5SDimitry Andric void Process::SetRunningUserExpression(bool on) {
14470b57cec5SDimitry Andric   m_mod_id.SetRunningUserExpression(on);
14480b57cec5SDimitry Andric }
14490b57cec5SDimitry Andric 
SetRunningUtilityFunction(bool on)14500b57cec5SDimitry Andric void Process::SetRunningUtilityFunction(bool on) {
14510b57cec5SDimitry Andric   m_mod_id.SetRunningUtilityFunction(on);
14520b57cec5SDimitry Andric }
14530b57cec5SDimitry Andric 
GetImageInfoAddress()14540b57cec5SDimitry Andric addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
14550b57cec5SDimitry Andric 
GetABI()14560b57cec5SDimitry Andric const lldb::ABISP &Process::GetABI() {
14570b57cec5SDimitry Andric   if (!m_abi_sp)
14580b57cec5SDimitry Andric     m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
14590b57cec5SDimitry Andric   return m_abi_sp;
14600b57cec5SDimitry Andric }
14610b57cec5SDimitry Andric 
GetLanguageRuntimes()1462480093f4SDimitry Andric std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
14630b57cec5SDimitry Andric   std::vector<LanguageRuntime *> language_runtimes;
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric   if (m_finalizing)
14660b57cec5SDimitry Andric     return language_runtimes;
14670b57cec5SDimitry Andric 
14680b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
14690b57cec5SDimitry Andric   // Before we pass off a copy of the language runtimes, we must make sure that
14700b57cec5SDimitry Andric   // our collection is properly populated. It's possible that some of the
14710b57cec5SDimitry Andric   // language runtimes were not loaded yet, either because nobody requested it
14720b57cec5SDimitry Andric   // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
14730b57cec5SDimitry Andric   // hadn't been loaded).
14740b57cec5SDimitry Andric   for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1475480093f4SDimitry Andric     if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
14760b57cec5SDimitry Andric       language_runtimes.emplace_back(runtime);
14770b57cec5SDimitry Andric   }
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   return language_runtimes;
14800b57cec5SDimitry Andric }
14810b57cec5SDimitry Andric 
GetLanguageRuntime(lldb::LanguageType language)1482480093f4SDimitry Andric LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
14830b57cec5SDimitry Andric   if (m_finalizing)
14840b57cec5SDimitry Andric     return nullptr;
14850b57cec5SDimitry Andric 
14860b57cec5SDimitry Andric   LanguageRuntime *runtime = nullptr;
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
14890b57cec5SDimitry Andric   LanguageRuntimeCollection::iterator pos;
14900b57cec5SDimitry Andric   pos = m_language_runtimes.find(language);
1491480093f4SDimitry Andric   if (pos == m_language_runtimes.end() || !pos->second) {
14920b57cec5SDimitry Andric     lldb::LanguageRuntimeSP runtime_sp(
14930b57cec5SDimitry Andric         LanguageRuntime::FindPlugin(this, language));
14940b57cec5SDimitry Andric 
14950b57cec5SDimitry Andric     m_language_runtimes[language] = runtime_sp;
14960b57cec5SDimitry Andric     runtime = runtime_sp.get();
14970b57cec5SDimitry Andric   } else
14980b57cec5SDimitry Andric     runtime = pos->second.get();
14990b57cec5SDimitry Andric 
15000b57cec5SDimitry Andric   if (runtime)
15010b57cec5SDimitry Andric     // It's possible that a language runtime can support multiple LanguageTypes,
15020b57cec5SDimitry Andric     // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
15030b57cec5SDimitry Andric     // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
15040b57cec5SDimitry Andric     // primary language type and make sure that our runtime supports it.
15050b57cec5SDimitry Andric     assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   return runtime;
15080b57cec5SDimitry Andric }
15090b57cec5SDimitry Andric 
IsPossibleDynamicValue(ValueObject & in_value)15100b57cec5SDimitry Andric bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
15110b57cec5SDimitry Andric   if (m_finalizing)
15120b57cec5SDimitry Andric     return false;
15130b57cec5SDimitry Andric 
15140b57cec5SDimitry Andric   if (in_value.IsDynamic())
15150b57cec5SDimitry Andric     return false;
15160b57cec5SDimitry Andric   LanguageType known_type = in_value.GetObjectRuntimeLanguage();
15170b57cec5SDimitry Andric 
15180b57cec5SDimitry Andric   if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
15190b57cec5SDimitry Andric     LanguageRuntime *runtime = GetLanguageRuntime(known_type);
15200b57cec5SDimitry Andric     return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
15210b57cec5SDimitry Andric   }
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric   for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
15240b57cec5SDimitry Andric     if (runtime->CouldHaveDynamicValue(in_value))
15250b57cec5SDimitry Andric       return true;
15260b57cec5SDimitry Andric   }
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric   return false;
15290b57cec5SDimitry Andric }
15300b57cec5SDimitry Andric 
SetDynamicCheckers(DynamicCheckerFunctions * dynamic_checkers)15310b57cec5SDimitry Andric void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
15320b57cec5SDimitry Andric   m_dynamic_checkers_up.reset(dynamic_checkers);
15330b57cec5SDimitry Andric }
15340b57cec5SDimitry Andric 
GetBreakpointSiteList()15350b57cec5SDimitry Andric BreakpointSiteList &Process::GetBreakpointSiteList() {
15360b57cec5SDimitry Andric   return m_breakpoint_site_list;
15370b57cec5SDimitry Andric }
15380b57cec5SDimitry Andric 
GetBreakpointSiteList() const15390b57cec5SDimitry Andric const BreakpointSiteList &Process::GetBreakpointSiteList() const {
15400b57cec5SDimitry Andric   return m_breakpoint_site_list;
15410b57cec5SDimitry Andric }
15420b57cec5SDimitry Andric 
DisableAllBreakpointSites()15430b57cec5SDimitry Andric void Process::DisableAllBreakpointSites() {
15440b57cec5SDimitry Andric   m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
15450b57cec5SDimitry Andric     //        bp_site->SetEnabled(true);
15460b57cec5SDimitry Andric     DisableBreakpointSite(bp_site);
15470b57cec5SDimitry Andric   });
15480b57cec5SDimitry Andric }
15490b57cec5SDimitry Andric 
ClearBreakpointSiteByID(lldb::user_id_t break_id)15500b57cec5SDimitry Andric Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
15510b57cec5SDimitry Andric   Status error(DisableBreakpointSiteByID(break_id));
15520b57cec5SDimitry Andric 
15530b57cec5SDimitry Andric   if (error.Success())
15540b57cec5SDimitry Andric     m_breakpoint_site_list.Remove(break_id);
15550b57cec5SDimitry Andric 
15560b57cec5SDimitry Andric   return error;
15570b57cec5SDimitry Andric }
15580b57cec5SDimitry Andric 
DisableBreakpointSiteByID(lldb::user_id_t break_id)15590b57cec5SDimitry Andric Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
15600b57cec5SDimitry Andric   Status error;
15610b57cec5SDimitry Andric   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
15620b57cec5SDimitry Andric   if (bp_site_sp) {
15630b57cec5SDimitry Andric     if (bp_site_sp->IsEnabled())
15640b57cec5SDimitry Andric       error = DisableBreakpointSite(bp_site_sp.get());
15650b57cec5SDimitry Andric   } else {
15660b57cec5SDimitry Andric     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
15670b57cec5SDimitry Andric                                    break_id);
15680b57cec5SDimitry Andric   }
15690b57cec5SDimitry Andric 
15700b57cec5SDimitry Andric   return error;
15710b57cec5SDimitry Andric }
15720b57cec5SDimitry Andric 
EnableBreakpointSiteByID(lldb::user_id_t break_id)15730b57cec5SDimitry Andric Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
15740b57cec5SDimitry Andric   Status error;
15750b57cec5SDimitry Andric   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
15760b57cec5SDimitry Andric   if (bp_site_sp) {
15770b57cec5SDimitry Andric     if (!bp_site_sp->IsEnabled())
15780b57cec5SDimitry Andric       error = EnableBreakpointSite(bp_site_sp.get());
15790b57cec5SDimitry Andric   } else {
15800b57cec5SDimitry Andric     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
15810b57cec5SDimitry Andric                                    break_id);
15820b57cec5SDimitry Andric   }
15830b57cec5SDimitry Andric   return error;
15840b57cec5SDimitry Andric }
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric lldb::break_id_t
CreateBreakpointSite(const BreakpointLocationSP & owner,bool use_hardware)15870b57cec5SDimitry Andric Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
15880b57cec5SDimitry Andric                               bool use_hardware) {
15890b57cec5SDimitry Andric   addr_t load_addr = LLDB_INVALID_ADDRESS;
15900b57cec5SDimitry Andric 
15910b57cec5SDimitry Andric   bool show_error = true;
15920b57cec5SDimitry Andric   switch (GetState()) {
15930b57cec5SDimitry Andric   case eStateInvalid:
15940b57cec5SDimitry Andric   case eStateUnloaded:
15950b57cec5SDimitry Andric   case eStateConnected:
15960b57cec5SDimitry Andric   case eStateAttaching:
15970b57cec5SDimitry Andric   case eStateLaunching:
15980b57cec5SDimitry Andric   case eStateDetached:
15990b57cec5SDimitry Andric   case eStateExited:
16000b57cec5SDimitry Andric     show_error = false;
16010b57cec5SDimitry Andric     break;
16020b57cec5SDimitry Andric 
16030b57cec5SDimitry Andric   case eStateStopped:
16040b57cec5SDimitry Andric   case eStateRunning:
16050b57cec5SDimitry Andric   case eStateStepping:
16060b57cec5SDimitry Andric   case eStateCrashed:
16070b57cec5SDimitry Andric   case eStateSuspended:
16080b57cec5SDimitry Andric     show_error = IsAlive();
16090b57cec5SDimitry Andric     break;
16100b57cec5SDimitry Andric   }
16110b57cec5SDimitry Andric 
16120b57cec5SDimitry Andric   // Reset the IsIndirect flag here, in case the location changes from pointing
16130b57cec5SDimitry Andric   // to a indirect symbol to a regular symbol.
16140b57cec5SDimitry Andric   owner->SetIsIndirect(false);
16150b57cec5SDimitry Andric 
16160b57cec5SDimitry Andric   if (owner->ShouldResolveIndirectFunctions()) {
16170b57cec5SDimitry Andric     Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
16180b57cec5SDimitry Andric     if (symbol && symbol->IsIndirect()) {
16190b57cec5SDimitry Andric       Status error;
16200b57cec5SDimitry Andric       Address symbol_address = symbol->GetAddress();
16210b57cec5SDimitry Andric       load_addr = ResolveIndirectFunction(&symbol_address, error);
16220b57cec5SDimitry Andric       if (!error.Success() && show_error) {
16239dba64beSDimitry Andric         GetTarget().GetDebugger().GetErrorStream().Printf(
16240b57cec5SDimitry Andric             "warning: failed to resolve indirect function at 0x%" PRIx64
16250b57cec5SDimitry Andric             " for breakpoint %i.%i: %s\n",
16260b57cec5SDimitry Andric             symbol->GetLoadAddress(&GetTarget()),
16270b57cec5SDimitry Andric             owner->GetBreakpoint().GetID(), owner->GetID(),
16280b57cec5SDimitry Andric             error.AsCString() ? error.AsCString() : "unknown error");
16290b57cec5SDimitry Andric         return LLDB_INVALID_BREAK_ID;
16300b57cec5SDimitry Andric       }
16310b57cec5SDimitry Andric       Address resolved_address(load_addr);
16320b57cec5SDimitry Andric       load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
16330b57cec5SDimitry Andric       owner->SetIsIndirect(true);
16340b57cec5SDimitry Andric     } else
16350b57cec5SDimitry Andric       load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
16360b57cec5SDimitry Andric   } else
16370b57cec5SDimitry Andric     load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
16380b57cec5SDimitry Andric 
16390b57cec5SDimitry Andric   if (load_addr != LLDB_INVALID_ADDRESS) {
16400b57cec5SDimitry Andric     BreakpointSiteSP bp_site_sp;
16410b57cec5SDimitry Andric 
16420b57cec5SDimitry Andric     // Look up this breakpoint site.  If it exists, then add this new owner,
16430b57cec5SDimitry Andric     // otherwise create a new breakpoint site and add it.
16440b57cec5SDimitry Andric 
16450b57cec5SDimitry Andric     bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
16460b57cec5SDimitry Andric 
16470b57cec5SDimitry Andric     if (bp_site_sp) {
16480b57cec5SDimitry Andric       bp_site_sp->AddOwner(owner);
16490b57cec5SDimitry Andric       owner->SetBreakpointSite(bp_site_sp);
16500b57cec5SDimitry Andric       return bp_site_sp->GetID();
16510b57cec5SDimitry Andric     } else {
16520b57cec5SDimitry Andric       bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
16530b57cec5SDimitry Andric                                           load_addr, use_hardware));
16540b57cec5SDimitry Andric       if (bp_site_sp) {
16550b57cec5SDimitry Andric         Status error = EnableBreakpointSite(bp_site_sp.get());
16560b57cec5SDimitry Andric         if (error.Success()) {
16570b57cec5SDimitry Andric           owner->SetBreakpointSite(bp_site_sp);
16580b57cec5SDimitry Andric           return m_breakpoint_site_list.Add(bp_site_sp);
16590b57cec5SDimitry Andric         } else {
16600b57cec5SDimitry Andric           if (show_error || use_hardware) {
16610b57cec5SDimitry Andric             // Report error for setting breakpoint...
16629dba64beSDimitry Andric             GetTarget().GetDebugger().GetErrorStream().Printf(
16630b57cec5SDimitry Andric                 "warning: failed to set breakpoint site at 0x%" PRIx64
16640b57cec5SDimitry Andric                 " for breakpoint %i.%i: %s\n",
16650b57cec5SDimitry Andric                 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
16660b57cec5SDimitry Andric                 error.AsCString() ? error.AsCString() : "unknown error");
16670b57cec5SDimitry Andric           }
16680b57cec5SDimitry Andric         }
16690b57cec5SDimitry Andric       }
16700b57cec5SDimitry Andric     }
16710b57cec5SDimitry Andric   }
16720b57cec5SDimitry Andric   // We failed to enable the breakpoint
16730b57cec5SDimitry Andric   return LLDB_INVALID_BREAK_ID;
16740b57cec5SDimitry Andric }
16750b57cec5SDimitry Andric 
RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,lldb::user_id_t owner_loc_id,BreakpointSiteSP & bp_site_sp)16760b57cec5SDimitry Andric void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
16770b57cec5SDimitry Andric                                             lldb::user_id_t owner_loc_id,
16780b57cec5SDimitry Andric                                             BreakpointSiteSP &bp_site_sp) {
16790b57cec5SDimitry Andric   uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
16800b57cec5SDimitry Andric   if (num_owners == 0) {
16810b57cec5SDimitry Andric     // Don't try to disable the site if we don't have a live process anymore.
16820b57cec5SDimitry Andric     if (IsAlive())
16830b57cec5SDimitry Andric       DisableBreakpointSite(bp_site_sp.get());
16840b57cec5SDimitry Andric     m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
16850b57cec5SDimitry Andric   }
16860b57cec5SDimitry Andric }
16870b57cec5SDimitry Andric 
RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr,size_t size,uint8_t * buf) const16880b57cec5SDimitry Andric size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
16890b57cec5SDimitry Andric                                                   uint8_t *buf) const {
16900b57cec5SDimitry Andric   size_t bytes_removed = 0;
16910b57cec5SDimitry Andric   BreakpointSiteList bp_sites_in_range;
16920b57cec5SDimitry Andric 
16930b57cec5SDimitry Andric   if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
16940b57cec5SDimitry Andric                                          bp_sites_in_range)) {
16950b57cec5SDimitry Andric     bp_sites_in_range.ForEach([bp_addr, size,
16960b57cec5SDimitry Andric                                buf](BreakpointSite *bp_site) -> void {
16970b57cec5SDimitry Andric       if (bp_site->GetType() == BreakpointSite::eSoftware) {
16980b57cec5SDimitry Andric         addr_t intersect_addr;
16990b57cec5SDimitry Andric         size_t intersect_size;
17000b57cec5SDimitry Andric         size_t opcode_offset;
17010b57cec5SDimitry Andric         if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
17020b57cec5SDimitry Andric                                      &intersect_size, &opcode_offset)) {
17030b57cec5SDimitry Andric           assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
17040b57cec5SDimitry Andric           assert(bp_addr < intersect_addr + intersect_size &&
17050b57cec5SDimitry Andric                  intersect_addr + intersect_size <= bp_addr + size);
17060b57cec5SDimitry Andric           assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
17070b57cec5SDimitry Andric           size_t buf_offset = intersect_addr - bp_addr;
17080b57cec5SDimitry Andric           ::memcpy(buf + buf_offset,
17090b57cec5SDimitry Andric                    bp_site->GetSavedOpcodeBytes() + opcode_offset,
17100b57cec5SDimitry Andric                    intersect_size);
17110b57cec5SDimitry Andric         }
17120b57cec5SDimitry Andric       }
17130b57cec5SDimitry Andric     });
17140b57cec5SDimitry Andric   }
17150b57cec5SDimitry Andric   return bytes_removed;
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric 
GetSoftwareBreakpointTrapOpcode(BreakpointSite * bp_site)17180b57cec5SDimitry Andric size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
17190b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
17200b57cec5SDimitry Andric   if (platform_sp)
17210b57cec5SDimitry Andric     return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
17220b57cec5SDimitry Andric   return 0;
17230b57cec5SDimitry Andric }
17240b57cec5SDimitry Andric 
EnableSoftwareBreakpoint(BreakpointSite * bp_site)17250b57cec5SDimitry Andric Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
17260b57cec5SDimitry Andric   Status error;
17270b57cec5SDimitry Andric   assert(bp_site != nullptr);
17280b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
17290b57cec5SDimitry Andric   const addr_t bp_addr = bp_site->GetLoadAddress();
17309dba64beSDimitry Andric   LLDB_LOGF(
17319dba64beSDimitry Andric       log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
17320b57cec5SDimitry Andric       bp_site->GetID(), (uint64_t)bp_addr);
17330b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
17349dba64beSDimitry Andric     LLDB_LOGF(
17359dba64beSDimitry Andric         log,
17360b57cec5SDimitry Andric         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
17370b57cec5SDimitry Andric         " -- already enabled",
17380b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr);
17390b57cec5SDimitry Andric     return error;
17400b57cec5SDimitry Andric   }
17410b57cec5SDimitry Andric 
17420b57cec5SDimitry Andric   if (bp_addr == LLDB_INVALID_ADDRESS) {
17430b57cec5SDimitry Andric     error.SetErrorString("BreakpointSite contains an invalid load address.");
17440b57cec5SDimitry Andric     return error;
17450b57cec5SDimitry Andric   }
17460b57cec5SDimitry Andric   // Ask the lldb::Process subclass to fill in the correct software breakpoint
17470b57cec5SDimitry Andric   // trap for the breakpoint site
17480b57cec5SDimitry Andric   const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
17490b57cec5SDimitry Andric 
17500b57cec5SDimitry Andric   if (bp_opcode_size == 0) {
17510b57cec5SDimitry Andric     error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
17520b57cec5SDimitry Andric                                    "returned zero, unable to get breakpoint "
17530b57cec5SDimitry Andric                                    "trap for address 0x%" PRIx64,
17540b57cec5SDimitry Andric                                    bp_addr);
17550b57cec5SDimitry Andric   } else {
17560b57cec5SDimitry Andric     const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
17570b57cec5SDimitry Andric 
17580b57cec5SDimitry Andric     if (bp_opcode_bytes == nullptr) {
17590b57cec5SDimitry Andric       error.SetErrorString(
17600b57cec5SDimitry Andric           "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
17610b57cec5SDimitry Andric       return error;
17620b57cec5SDimitry Andric     }
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric     // Save the original opcode by reading it
17650b57cec5SDimitry Andric     if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
17660b57cec5SDimitry Andric                      error) == bp_opcode_size) {
17670b57cec5SDimitry Andric       // Write a software breakpoint in place of the original opcode
17680b57cec5SDimitry Andric       if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
17690b57cec5SDimitry Andric           bp_opcode_size) {
17700b57cec5SDimitry Andric         uint8_t verify_bp_opcode_bytes[64];
17710b57cec5SDimitry Andric         if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
17720b57cec5SDimitry Andric                          error) == bp_opcode_size) {
17730b57cec5SDimitry Andric           if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
17740b57cec5SDimitry Andric                        bp_opcode_size) == 0) {
17750b57cec5SDimitry Andric             bp_site->SetEnabled(true);
17760b57cec5SDimitry Andric             bp_site->SetType(BreakpointSite::eSoftware);
17779dba64beSDimitry Andric             LLDB_LOGF(log,
17789dba64beSDimitry Andric                       "Process::EnableSoftwareBreakpoint (site_id = %d) "
17790b57cec5SDimitry Andric                       "addr = 0x%" PRIx64 " -- SUCCESS",
17800b57cec5SDimitry Andric                       bp_site->GetID(), (uint64_t)bp_addr);
17810b57cec5SDimitry Andric           } else
17820b57cec5SDimitry Andric             error.SetErrorString(
17830b57cec5SDimitry Andric                 "failed to verify the breakpoint trap in memory.");
17840b57cec5SDimitry Andric         } else
17850b57cec5SDimitry Andric           error.SetErrorString(
17860b57cec5SDimitry Andric               "Unable to read memory to verify breakpoint trap.");
17870b57cec5SDimitry Andric       } else
17880b57cec5SDimitry Andric         error.SetErrorString("Unable to write breakpoint trap to memory.");
17890b57cec5SDimitry Andric     } else
17900b57cec5SDimitry Andric       error.SetErrorString("Unable to read memory at breakpoint address.");
17910b57cec5SDimitry Andric   }
17920b57cec5SDimitry Andric   if (log && error.Fail())
17939dba64beSDimitry Andric     LLDB_LOGF(
17949dba64beSDimitry Andric         log,
17950b57cec5SDimitry Andric         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
17960b57cec5SDimitry Andric         " -- FAILED: %s",
17970b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
17980b57cec5SDimitry Andric   return error;
17990b57cec5SDimitry Andric }
18000b57cec5SDimitry Andric 
DisableSoftwareBreakpoint(BreakpointSite * bp_site)18010b57cec5SDimitry Andric Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
18020b57cec5SDimitry Andric   Status error;
18030b57cec5SDimitry Andric   assert(bp_site != nullptr);
18040b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
18050b57cec5SDimitry Andric   addr_t bp_addr = bp_site->GetLoadAddress();
18060b57cec5SDimitry Andric   lldb::user_id_t breakID = bp_site->GetID();
18079dba64beSDimitry Andric   LLDB_LOGF(log,
18089dba64beSDimitry Andric             "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
18090b57cec5SDimitry Andric             ") addr = 0x%" PRIx64,
18100b57cec5SDimitry Andric             breakID, (uint64_t)bp_addr);
18110b57cec5SDimitry Andric 
18120b57cec5SDimitry Andric   if (bp_site->IsHardware()) {
18130b57cec5SDimitry Andric     error.SetErrorString("Breakpoint site is a hardware breakpoint.");
18140b57cec5SDimitry Andric   } else if (bp_site->IsEnabled()) {
18150b57cec5SDimitry Andric     const size_t break_op_size = bp_site->GetByteSize();
18160b57cec5SDimitry Andric     const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
18170b57cec5SDimitry Andric     if (break_op_size > 0) {
18180b57cec5SDimitry Andric       // Clear a software breakpoint instruction
18190b57cec5SDimitry Andric       uint8_t curr_break_op[8];
18200b57cec5SDimitry Andric       assert(break_op_size <= sizeof(curr_break_op));
18210b57cec5SDimitry Andric       bool break_op_found = false;
18220b57cec5SDimitry Andric 
18230b57cec5SDimitry Andric       // Read the breakpoint opcode
18240b57cec5SDimitry Andric       if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
18250b57cec5SDimitry Andric           break_op_size) {
18260b57cec5SDimitry Andric         bool verify = false;
18270b57cec5SDimitry Andric         // Make sure the breakpoint opcode exists at this address
18280b57cec5SDimitry Andric         if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
18290b57cec5SDimitry Andric           break_op_found = true;
18300b57cec5SDimitry Andric           // We found a valid breakpoint opcode at this address, now restore
18310b57cec5SDimitry Andric           // the saved opcode.
18320b57cec5SDimitry Andric           if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
18330b57cec5SDimitry Andric                             break_op_size, error) == break_op_size) {
18340b57cec5SDimitry Andric             verify = true;
18350b57cec5SDimitry Andric           } else
18360b57cec5SDimitry Andric             error.SetErrorString(
18370b57cec5SDimitry Andric                 "Memory write failed when restoring original opcode.");
18380b57cec5SDimitry Andric         } else {
18390b57cec5SDimitry Andric           error.SetErrorString(
18400b57cec5SDimitry Andric               "Original breakpoint trap is no longer in memory.");
18410b57cec5SDimitry Andric           // Set verify to true and so we can check if the original opcode has
18420b57cec5SDimitry Andric           // already been restored
18430b57cec5SDimitry Andric           verify = true;
18440b57cec5SDimitry Andric         }
18450b57cec5SDimitry Andric 
18460b57cec5SDimitry Andric         if (verify) {
18470b57cec5SDimitry Andric           uint8_t verify_opcode[8];
18480b57cec5SDimitry Andric           assert(break_op_size < sizeof(verify_opcode));
18490b57cec5SDimitry Andric           // Verify that our original opcode made it back to the inferior
18500b57cec5SDimitry Andric           if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
18510b57cec5SDimitry Andric               break_op_size) {
18520b57cec5SDimitry Andric             // compare the memory we just read with the original opcode
18530b57cec5SDimitry Andric             if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
18540b57cec5SDimitry Andric                          break_op_size) == 0) {
18550b57cec5SDimitry Andric               // SUCCESS
18560b57cec5SDimitry Andric               bp_site->SetEnabled(false);
18579dba64beSDimitry Andric               LLDB_LOGF(log,
18589dba64beSDimitry Andric                         "Process::DisableSoftwareBreakpoint (site_id = %d) "
18590b57cec5SDimitry Andric                         "addr = 0x%" PRIx64 " -- SUCCESS",
18600b57cec5SDimitry Andric                         bp_site->GetID(), (uint64_t)bp_addr);
18610b57cec5SDimitry Andric               return error;
18620b57cec5SDimitry Andric             } else {
18630b57cec5SDimitry Andric               if (break_op_found)
18640b57cec5SDimitry Andric                 error.SetErrorString("Failed to restore original opcode.");
18650b57cec5SDimitry Andric             }
18660b57cec5SDimitry Andric           } else
18670b57cec5SDimitry Andric             error.SetErrorString("Failed to read memory to verify that "
18680b57cec5SDimitry Andric                                  "breakpoint trap was restored.");
18690b57cec5SDimitry Andric         }
18700b57cec5SDimitry Andric       } else
18710b57cec5SDimitry Andric         error.SetErrorString(
18720b57cec5SDimitry Andric             "Unable to read memory that should contain the breakpoint trap.");
18730b57cec5SDimitry Andric     }
18740b57cec5SDimitry Andric   } else {
18759dba64beSDimitry Andric     LLDB_LOGF(
18769dba64beSDimitry Andric         log,
18770b57cec5SDimitry Andric         "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
18780b57cec5SDimitry Andric         " -- already disabled",
18790b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr);
18800b57cec5SDimitry Andric     return error;
18810b57cec5SDimitry Andric   }
18820b57cec5SDimitry Andric 
18839dba64beSDimitry Andric   LLDB_LOGF(
18849dba64beSDimitry Andric       log,
18850b57cec5SDimitry Andric       "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
18860b57cec5SDimitry Andric       " -- FAILED: %s",
18870b57cec5SDimitry Andric       bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
18880b57cec5SDimitry Andric   return error;
18890b57cec5SDimitry Andric }
18900b57cec5SDimitry Andric 
18910b57cec5SDimitry Andric // Uncomment to verify memory caching works after making changes to caching
18920b57cec5SDimitry Andric // code
18930b57cec5SDimitry Andric //#define VERIFY_MEMORY_READS
18940b57cec5SDimitry Andric 
ReadMemory(addr_t addr,void * buf,size_t size,Status & error)18950b57cec5SDimitry Andric size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
18960b57cec5SDimitry Andric   error.Clear();
18970b57cec5SDimitry Andric   if (!GetDisableMemoryCache()) {
18980b57cec5SDimitry Andric #if defined(VERIFY_MEMORY_READS)
18990b57cec5SDimitry Andric     // Memory caching is enabled, with debug verification
19000b57cec5SDimitry Andric 
19010b57cec5SDimitry Andric     if (buf && size) {
19020b57cec5SDimitry Andric       // Uncomment the line below to make sure memory caching is working.
19030b57cec5SDimitry Andric       // I ran this through the test suite and got no assertions, so I am
19040b57cec5SDimitry Andric       // pretty confident this is working well. If any changes are made to
19050b57cec5SDimitry Andric       // memory caching, uncomment the line below and test your changes!
19060b57cec5SDimitry Andric 
19070b57cec5SDimitry Andric       // Verify all memory reads by using the cache first, then redundantly
19080b57cec5SDimitry Andric       // reading the same memory from the inferior and comparing to make sure
19090b57cec5SDimitry Andric       // everything is exactly the same.
19100b57cec5SDimitry Andric       std::string verify_buf(size, '\0');
19110b57cec5SDimitry Andric       assert(verify_buf.size() == size);
19120b57cec5SDimitry Andric       const size_t cache_bytes_read =
19130b57cec5SDimitry Andric           m_memory_cache.Read(this, addr, buf, size, error);
19140b57cec5SDimitry Andric       Status verify_error;
19150b57cec5SDimitry Andric       const size_t verify_bytes_read =
19160b57cec5SDimitry Andric           ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
19170b57cec5SDimitry Andric                                  verify_buf.size(), verify_error);
19180b57cec5SDimitry Andric       assert(cache_bytes_read == verify_bytes_read);
19190b57cec5SDimitry Andric       assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
19200b57cec5SDimitry Andric       assert(verify_error.Success() == error.Success());
19210b57cec5SDimitry Andric       return cache_bytes_read;
19220b57cec5SDimitry Andric     }
19230b57cec5SDimitry Andric     return 0;
19240b57cec5SDimitry Andric #else  // !defined(VERIFY_MEMORY_READS)
19250b57cec5SDimitry Andric     // Memory caching is enabled, without debug verification
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric     return m_memory_cache.Read(addr, buf, size, error);
19280b57cec5SDimitry Andric #endif // defined (VERIFY_MEMORY_READS)
19290b57cec5SDimitry Andric   } else {
19300b57cec5SDimitry Andric     // Memory caching is disabled
19310b57cec5SDimitry Andric 
19320b57cec5SDimitry Andric     return ReadMemoryFromInferior(addr, buf, size, error);
19330b57cec5SDimitry Andric   }
19340b57cec5SDimitry Andric }
19350b57cec5SDimitry Andric 
ReadCStringFromMemory(addr_t addr,std::string & out_str,Status & error)19360b57cec5SDimitry Andric size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
19370b57cec5SDimitry Andric                                       Status &error) {
19380b57cec5SDimitry Andric   char buf[256];
19390b57cec5SDimitry Andric   out_str.clear();
19400b57cec5SDimitry Andric   addr_t curr_addr = addr;
19410b57cec5SDimitry Andric   while (true) {
19420b57cec5SDimitry Andric     size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
19430b57cec5SDimitry Andric     if (length == 0)
19440b57cec5SDimitry Andric       break;
19450b57cec5SDimitry Andric     out_str.append(buf, length);
19460b57cec5SDimitry Andric     // If we got "length - 1" bytes, we didn't get the whole C string, we need
19470b57cec5SDimitry Andric     // to read some more characters
19480b57cec5SDimitry Andric     if (length == sizeof(buf) - 1)
19490b57cec5SDimitry Andric       curr_addr += length;
19500b57cec5SDimitry Andric     else
19510b57cec5SDimitry Andric       break;
19520b57cec5SDimitry Andric   }
19530b57cec5SDimitry Andric   return out_str.size();
19540b57cec5SDimitry Andric }
19550b57cec5SDimitry Andric 
ReadStringFromMemory(addr_t addr,char * dst,size_t max_bytes,Status & error,size_t type_width)19560b57cec5SDimitry Andric size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
19570b57cec5SDimitry Andric                                      Status &error, size_t type_width) {
19580b57cec5SDimitry Andric   size_t total_bytes_read = 0;
19590b57cec5SDimitry Andric   if (dst && max_bytes && type_width && max_bytes >= type_width) {
19600b57cec5SDimitry Andric     // Ensure a null terminator independent of the number of bytes that is
19610b57cec5SDimitry Andric     // read.
19620b57cec5SDimitry Andric     memset(dst, 0, max_bytes);
19630b57cec5SDimitry Andric     size_t bytes_left = max_bytes - type_width;
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric     const char terminator[4] = {'\0', '\0', '\0', '\0'};
19660b57cec5SDimitry Andric     assert(sizeof(terminator) >= type_width && "Attempting to validate a "
19670b57cec5SDimitry Andric                                                "string with more than 4 bytes "
19680b57cec5SDimitry Andric                                                "per character!");
19690b57cec5SDimitry Andric 
19700b57cec5SDimitry Andric     addr_t curr_addr = addr;
19710b57cec5SDimitry Andric     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
19720b57cec5SDimitry Andric     char *curr_dst = dst;
19730b57cec5SDimitry Andric 
19740b57cec5SDimitry Andric     error.Clear();
19750b57cec5SDimitry Andric     while (bytes_left > 0 && error.Success()) {
19760b57cec5SDimitry Andric       addr_t cache_line_bytes_left =
19770b57cec5SDimitry Andric           cache_line_size - (curr_addr % cache_line_size);
19780b57cec5SDimitry Andric       addr_t bytes_to_read =
19790b57cec5SDimitry Andric           std::min<addr_t>(bytes_left, cache_line_bytes_left);
19800b57cec5SDimitry Andric       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
19810b57cec5SDimitry Andric 
19820b57cec5SDimitry Andric       if (bytes_read == 0)
19830b57cec5SDimitry Andric         break;
19840b57cec5SDimitry Andric 
19850b57cec5SDimitry Andric       // Search for a null terminator of correct size and alignment in
19860b57cec5SDimitry Andric       // bytes_read
19870b57cec5SDimitry Andric       size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
19880b57cec5SDimitry Andric       for (size_t i = aligned_start;
19890b57cec5SDimitry Andric            i + type_width <= total_bytes_read + bytes_read; i += type_width)
19900b57cec5SDimitry Andric         if (::memcmp(&dst[i], terminator, type_width) == 0) {
19910b57cec5SDimitry Andric           error.Clear();
19920b57cec5SDimitry Andric           return i;
19930b57cec5SDimitry Andric         }
19940b57cec5SDimitry Andric 
19950b57cec5SDimitry Andric       total_bytes_read += bytes_read;
19960b57cec5SDimitry Andric       curr_dst += bytes_read;
19970b57cec5SDimitry Andric       curr_addr += bytes_read;
19980b57cec5SDimitry Andric       bytes_left -= bytes_read;
19990b57cec5SDimitry Andric     }
20000b57cec5SDimitry Andric   } else {
20010b57cec5SDimitry Andric     if (max_bytes)
20020b57cec5SDimitry Andric       error.SetErrorString("invalid arguments");
20030b57cec5SDimitry Andric   }
20040b57cec5SDimitry Andric   return total_bytes_read;
20050b57cec5SDimitry Andric }
20060b57cec5SDimitry Andric 
20070b57cec5SDimitry Andric // Deprecated in favor of ReadStringFromMemory which has wchar support and
20080b57cec5SDimitry Andric // correct code to find null terminators.
ReadCStringFromMemory(addr_t addr,char * dst,size_t dst_max_len,Status & result_error)20090b57cec5SDimitry Andric size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
20100b57cec5SDimitry Andric                                       size_t dst_max_len,
20110b57cec5SDimitry Andric                                       Status &result_error) {
20120b57cec5SDimitry Andric   size_t total_cstr_len = 0;
20130b57cec5SDimitry Andric   if (dst && dst_max_len) {
20140b57cec5SDimitry Andric     result_error.Clear();
20150b57cec5SDimitry Andric     // NULL out everything just to be safe
20160b57cec5SDimitry Andric     memset(dst, 0, dst_max_len);
20170b57cec5SDimitry Andric     Status error;
20180b57cec5SDimitry Andric     addr_t curr_addr = addr;
20190b57cec5SDimitry Andric     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
20200b57cec5SDimitry Andric     size_t bytes_left = dst_max_len - 1;
20210b57cec5SDimitry Andric     char *curr_dst = dst;
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric     while (bytes_left > 0) {
20240b57cec5SDimitry Andric       addr_t cache_line_bytes_left =
20250b57cec5SDimitry Andric           cache_line_size - (curr_addr % cache_line_size);
20260b57cec5SDimitry Andric       addr_t bytes_to_read =
20270b57cec5SDimitry Andric           std::min<addr_t>(bytes_left, cache_line_bytes_left);
20280b57cec5SDimitry Andric       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
20290b57cec5SDimitry Andric 
20300b57cec5SDimitry Andric       if (bytes_read == 0) {
20310b57cec5SDimitry Andric         result_error = error;
20320b57cec5SDimitry Andric         dst[total_cstr_len] = '\0';
20330b57cec5SDimitry Andric         break;
20340b57cec5SDimitry Andric       }
20350b57cec5SDimitry Andric       const size_t len = strlen(curr_dst);
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric       total_cstr_len += len;
20380b57cec5SDimitry Andric 
20390b57cec5SDimitry Andric       if (len < bytes_to_read)
20400b57cec5SDimitry Andric         break;
20410b57cec5SDimitry Andric 
20420b57cec5SDimitry Andric       curr_dst += bytes_read;
20430b57cec5SDimitry Andric       curr_addr += bytes_read;
20440b57cec5SDimitry Andric       bytes_left -= bytes_read;
20450b57cec5SDimitry Andric     }
20460b57cec5SDimitry Andric   } else {
20470b57cec5SDimitry Andric     if (dst == nullptr)
20480b57cec5SDimitry Andric       result_error.SetErrorString("invalid arguments");
20490b57cec5SDimitry Andric     else
20500b57cec5SDimitry Andric       result_error.Clear();
20510b57cec5SDimitry Andric   }
20520b57cec5SDimitry Andric   return total_cstr_len;
20530b57cec5SDimitry Andric }
20540b57cec5SDimitry Andric 
ReadMemoryFromInferior(addr_t addr,void * buf,size_t size,Status & error)20550b57cec5SDimitry Andric size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
20560b57cec5SDimitry Andric                                        Status &error) {
2057*5f7ddb14SDimitry Andric   LLDB_SCOPED_TIMER();
2058*5f7ddb14SDimitry Andric 
20590b57cec5SDimitry Andric   if (buf == nullptr || size == 0)
20600b57cec5SDimitry Andric     return 0;
20610b57cec5SDimitry Andric 
20620b57cec5SDimitry Andric   size_t bytes_read = 0;
20630b57cec5SDimitry Andric   uint8_t *bytes = (uint8_t *)buf;
20640b57cec5SDimitry Andric 
20650b57cec5SDimitry Andric   while (bytes_read < size) {
20660b57cec5SDimitry Andric     const size_t curr_size = size - bytes_read;
20670b57cec5SDimitry Andric     const size_t curr_bytes_read =
20680b57cec5SDimitry Andric         DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
20690b57cec5SDimitry Andric     bytes_read += curr_bytes_read;
20700b57cec5SDimitry Andric     if (curr_bytes_read == curr_size || curr_bytes_read == 0)
20710b57cec5SDimitry Andric       break;
20720b57cec5SDimitry Andric   }
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric   // Replace any software breakpoint opcodes that fall into this range back
20750b57cec5SDimitry Andric   // into "buf" before we return
20760b57cec5SDimitry Andric   if (bytes_read > 0)
20770b57cec5SDimitry Andric     RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
20780b57cec5SDimitry Andric   return bytes_read;
20790b57cec5SDimitry Andric }
20800b57cec5SDimitry Andric 
ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,size_t integer_byte_size,uint64_t fail_value,Status & error)20810b57cec5SDimitry Andric uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
20820b57cec5SDimitry Andric                                                 size_t integer_byte_size,
20830b57cec5SDimitry Andric                                                 uint64_t fail_value,
20840b57cec5SDimitry Andric                                                 Status &error) {
20850b57cec5SDimitry Andric   Scalar scalar;
20860b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
20870b57cec5SDimitry Andric                                   error))
20880b57cec5SDimitry Andric     return scalar.ULongLong(fail_value);
20890b57cec5SDimitry Andric   return fail_value;
20900b57cec5SDimitry Andric }
20910b57cec5SDimitry Andric 
ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,size_t integer_byte_size,int64_t fail_value,Status & error)20920b57cec5SDimitry Andric int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
20930b57cec5SDimitry Andric                                              size_t integer_byte_size,
20940b57cec5SDimitry Andric                                              int64_t fail_value,
20950b57cec5SDimitry Andric                                              Status &error) {
20960b57cec5SDimitry Andric   Scalar scalar;
20970b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
20980b57cec5SDimitry Andric                                   error))
20990b57cec5SDimitry Andric     return scalar.SLongLong(fail_value);
21000b57cec5SDimitry Andric   return fail_value;
21010b57cec5SDimitry Andric }
21020b57cec5SDimitry Andric 
ReadPointerFromMemory(lldb::addr_t vm_addr,Status & error)21030b57cec5SDimitry Andric addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
21040b57cec5SDimitry Andric   Scalar scalar;
21050b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
21060b57cec5SDimitry Andric                                   error))
21070b57cec5SDimitry Andric     return scalar.ULongLong(LLDB_INVALID_ADDRESS);
21080b57cec5SDimitry Andric   return LLDB_INVALID_ADDRESS;
21090b57cec5SDimitry Andric }
21100b57cec5SDimitry Andric 
WritePointerToMemory(lldb::addr_t vm_addr,lldb::addr_t ptr_value,Status & error)21110b57cec5SDimitry Andric bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
21120b57cec5SDimitry Andric                                    Status &error) {
21130b57cec5SDimitry Andric   Scalar scalar;
21140b57cec5SDimitry Andric   const uint32_t addr_byte_size = GetAddressByteSize();
21150b57cec5SDimitry Andric   if (addr_byte_size <= 4)
21160b57cec5SDimitry Andric     scalar = (uint32_t)ptr_value;
21170b57cec5SDimitry Andric   else
21180b57cec5SDimitry Andric     scalar = ptr_value;
21190b57cec5SDimitry Andric   return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
21200b57cec5SDimitry Andric          addr_byte_size;
21210b57cec5SDimitry Andric }
21220b57cec5SDimitry Andric 
WriteMemoryPrivate(addr_t addr,const void * buf,size_t size,Status & error)21230b57cec5SDimitry Andric size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
21240b57cec5SDimitry Andric                                    Status &error) {
21250b57cec5SDimitry Andric   size_t bytes_written = 0;
21260b57cec5SDimitry Andric   const uint8_t *bytes = (const uint8_t *)buf;
21270b57cec5SDimitry Andric 
21280b57cec5SDimitry Andric   while (bytes_written < size) {
21290b57cec5SDimitry Andric     const size_t curr_size = size - bytes_written;
21300b57cec5SDimitry Andric     const size_t curr_bytes_written = DoWriteMemory(
21310b57cec5SDimitry Andric         addr + bytes_written, bytes + bytes_written, curr_size, error);
21320b57cec5SDimitry Andric     bytes_written += curr_bytes_written;
21330b57cec5SDimitry Andric     if (curr_bytes_written == curr_size || curr_bytes_written == 0)
21340b57cec5SDimitry Andric       break;
21350b57cec5SDimitry Andric   }
21360b57cec5SDimitry Andric   return bytes_written;
21370b57cec5SDimitry Andric }
21380b57cec5SDimitry Andric 
WriteMemory(addr_t addr,const void * buf,size_t size,Status & error)21390b57cec5SDimitry Andric size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
21400b57cec5SDimitry Andric                             Status &error) {
21410b57cec5SDimitry Andric #if defined(ENABLE_MEMORY_CACHING)
21420b57cec5SDimitry Andric   m_memory_cache.Flush(addr, size);
21430b57cec5SDimitry Andric #endif
21440b57cec5SDimitry Andric 
21450b57cec5SDimitry Andric   if (buf == nullptr || size == 0)
21460b57cec5SDimitry Andric     return 0;
21470b57cec5SDimitry Andric 
21480b57cec5SDimitry Andric   m_mod_id.BumpMemoryID();
21490b57cec5SDimitry Andric 
21500b57cec5SDimitry Andric   // We need to write any data that would go where any current software traps
21510b57cec5SDimitry Andric   // (enabled software breakpoints) any software traps (breakpoints) that we
21520b57cec5SDimitry Andric   // may have placed in our tasks memory.
21530b57cec5SDimitry Andric 
21540b57cec5SDimitry Andric   BreakpointSiteList bp_sites_in_range;
21550b57cec5SDimitry Andric   if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
21560b57cec5SDimitry Andric     return WriteMemoryPrivate(addr, buf, size, error);
21570b57cec5SDimitry Andric 
21580b57cec5SDimitry Andric   // No breakpoint sites overlap
21590b57cec5SDimitry Andric   if (bp_sites_in_range.IsEmpty())
21600b57cec5SDimitry Andric     return WriteMemoryPrivate(addr, buf, size, error);
21610b57cec5SDimitry Andric 
21620b57cec5SDimitry Andric   const uint8_t *ubuf = (const uint8_t *)buf;
21630b57cec5SDimitry Andric   uint64_t bytes_written = 0;
21640b57cec5SDimitry Andric 
21650b57cec5SDimitry Andric   bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
21660b57cec5SDimitry Andric                              &error](BreakpointSite *bp) -> void {
21670b57cec5SDimitry Andric     if (error.Fail())
21680b57cec5SDimitry Andric       return;
21690b57cec5SDimitry Andric 
2170af732203SDimitry Andric     if (bp->GetType() != BreakpointSite::eSoftware)
2171af732203SDimitry Andric       return;
2172af732203SDimitry Andric 
21730b57cec5SDimitry Andric     addr_t intersect_addr;
21740b57cec5SDimitry Andric     size_t intersect_size;
21750b57cec5SDimitry Andric     size_t opcode_offset;
21760b57cec5SDimitry Andric     const bool intersects = bp->IntersectsRange(
21770b57cec5SDimitry Andric         addr, size, &intersect_addr, &intersect_size, &opcode_offset);
21780b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(intersects);
21790b57cec5SDimitry Andric     assert(intersects);
21800b57cec5SDimitry Andric     assert(addr <= intersect_addr && intersect_addr < addr + size);
21810b57cec5SDimitry Andric     assert(addr < intersect_addr + intersect_size &&
21820b57cec5SDimitry Andric            intersect_addr + intersect_size <= addr + size);
21830b57cec5SDimitry Andric     assert(opcode_offset + intersect_size <= bp->GetByteSize());
21840b57cec5SDimitry Andric 
21850b57cec5SDimitry Andric     // Check for bytes before this breakpoint
21860b57cec5SDimitry Andric     const addr_t curr_addr = addr + bytes_written;
21870b57cec5SDimitry Andric     if (intersect_addr > curr_addr) {
21880b57cec5SDimitry Andric       // There are some bytes before this breakpoint that we need to just
21890b57cec5SDimitry Andric       // write to memory
21900b57cec5SDimitry Andric       size_t curr_size = intersect_addr - curr_addr;
21910b57cec5SDimitry Andric       size_t curr_bytes_written =
21920b57cec5SDimitry Andric           WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
21930b57cec5SDimitry Andric       bytes_written += curr_bytes_written;
21940b57cec5SDimitry Andric       if (curr_bytes_written != curr_size) {
21950b57cec5SDimitry Andric         // We weren't able to write all of the requested bytes, we are
21960b57cec5SDimitry Andric         // done looping and will return the number of bytes that we have
21970b57cec5SDimitry Andric         // written so far.
21980b57cec5SDimitry Andric         if (error.Success())
21990b57cec5SDimitry Andric           error.SetErrorToGenericError();
22000b57cec5SDimitry Andric       }
22010b57cec5SDimitry Andric     }
22020b57cec5SDimitry Andric     // Now write any bytes that would cover up any software breakpoints
22030b57cec5SDimitry Andric     // directly into the breakpoint opcode buffer
22040b57cec5SDimitry Andric     ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
22050b57cec5SDimitry Andric              intersect_size);
22060b57cec5SDimitry Andric     bytes_written += intersect_size;
22070b57cec5SDimitry Andric   });
22080b57cec5SDimitry Andric 
22090b57cec5SDimitry Andric   // Write any remaining bytes after the last breakpoint if we have any left
22100b57cec5SDimitry Andric   if (bytes_written < size)
22110b57cec5SDimitry Andric     bytes_written +=
22120b57cec5SDimitry Andric         WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
22130b57cec5SDimitry Andric                            size - bytes_written, error);
22140b57cec5SDimitry Andric 
22150b57cec5SDimitry Andric   return bytes_written;
22160b57cec5SDimitry Andric }
22170b57cec5SDimitry Andric 
WriteScalarToMemory(addr_t addr,const Scalar & scalar,size_t byte_size,Status & error)22180b57cec5SDimitry Andric size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
22190b57cec5SDimitry Andric                                     size_t byte_size, Status &error) {
22200b57cec5SDimitry Andric   if (byte_size == UINT32_MAX)
22210b57cec5SDimitry Andric     byte_size = scalar.GetByteSize();
22220b57cec5SDimitry Andric   if (byte_size > 0) {
22230b57cec5SDimitry Andric     uint8_t buf[32];
22240b57cec5SDimitry Andric     const size_t mem_size =
22250b57cec5SDimitry Andric         scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
22260b57cec5SDimitry Andric     if (mem_size > 0)
22270b57cec5SDimitry Andric       return WriteMemory(addr, buf, mem_size, error);
22280b57cec5SDimitry Andric     else
22290b57cec5SDimitry Andric       error.SetErrorString("failed to get scalar as memory data");
22300b57cec5SDimitry Andric   } else {
22310b57cec5SDimitry Andric     error.SetErrorString("invalid scalar value");
22320b57cec5SDimitry Andric   }
22330b57cec5SDimitry Andric   return 0;
22340b57cec5SDimitry Andric }
22350b57cec5SDimitry Andric 
ReadScalarIntegerFromMemory(addr_t addr,uint32_t byte_size,bool is_signed,Scalar & scalar,Status & error)22360b57cec5SDimitry Andric size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
22370b57cec5SDimitry Andric                                             bool is_signed, Scalar &scalar,
22380b57cec5SDimitry Andric                                             Status &error) {
22390b57cec5SDimitry Andric   uint64_t uval = 0;
22400b57cec5SDimitry Andric   if (byte_size == 0) {
22410b57cec5SDimitry Andric     error.SetErrorString("byte size is zero");
22420b57cec5SDimitry Andric   } else if (byte_size & (byte_size - 1)) {
22430b57cec5SDimitry Andric     error.SetErrorStringWithFormat("byte size %u is not a power of 2",
22440b57cec5SDimitry Andric                                    byte_size);
22450b57cec5SDimitry Andric   } else if (byte_size <= sizeof(uval)) {
22460b57cec5SDimitry Andric     const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
22470b57cec5SDimitry Andric     if (bytes_read == byte_size) {
22480b57cec5SDimitry Andric       DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
22490b57cec5SDimitry Andric                          GetAddressByteSize());
22500b57cec5SDimitry Andric       lldb::offset_t offset = 0;
22510b57cec5SDimitry Andric       if (byte_size <= 4)
22520b57cec5SDimitry Andric         scalar = data.GetMaxU32(&offset, byte_size);
22530b57cec5SDimitry Andric       else
22540b57cec5SDimitry Andric         scalar = data.GetMaxU64(&offset, byte_size);
22550b57cec5SDimitry Andric       if (is_signed)
22560b57cec5SDimitry Andric         scalar.SignExtend(byte_size * 8);
22570b57cec5SDimitry Andric       return bytes_read;
22580b57cec5SDimitry Andric     }
22590b57cec5SDimitry Andric   } else {
22600b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
22610b57cec5SDimitry Andric         "byte size of %u is too large for integer scalar type", byte_size);
22620b57cec5SDimitry Andric   }
22630b57cec5SDimitry Andric   return 0;
22640b57cec5SDimitry Andric }
22650b57cec5SDimitry Andric 
WriteObjectFile(std::vector<ObjectFile::LoadableData> entries)22660b57cec5SDimitry Andric Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
22670b57cec5SDimitry Andric   Status error;
22680b57cec5SDimitry Andric   for (const auto &Entry : entries) {
22690b57cec5SDimitry Andric     WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
22700b57cec5SDimitry Andric                 error);
22710b57cec5SDimitry Andric     if (!error.Success())
22720b57cec5SDimitry Andric       break;
22730b57cec5SDimitry Andric   }
22740b57cec5SDimitry Andric   return error;
22750b57cec5SDimitry Andric }
22760b57cec5SDimitry Andric 
22770b57cec5SDimitry Andric #define USE_ALLOCATE_MEMORY_CACHE 1
AllocateMemory(size_t size,uint32_t permissions,Status & error)22780b57cec5SDimitry Andric addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
22790b57cec5SDimitry Andric                                Status &error) {
22800b57cec5SDimitry Andric   if (GetPrivateState() != eStateStopped) {
22810b57cec5SDimitry Andric     error.SetErrorToGenericError();
22820b57cec5SDimitry Andric     return LLDB_INVALID_ADDRESS;
22830b57cec5SDimitry Andric   }
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric #if defined(USE_ALLOCATE_MEMORY_CACHE)
22860b57cec5SDimitry Andric   return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
22870b57cec5SDimitry Andric #else
22880b57cec5SDimitry Andric   addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
22890b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
22909dba64beSDimitry Andric   LLDB_LOGF(log,
22919dba64beSDimitry Andric             "Process::AllocateMemory(size=%" PRIu64
22920b57cec5SDimitry Andric             ", permissions=%s) => 0x%16.16" PRIx64
22930b57cec5SDimitry Andric             " (m_stop_id = %u m_memory_id = %u)",
22940b57cec5SDimitry Andric             (uint64_t)size, GetPermissionsAsCString(permissions),
22950b57cec5SDimitry Andric             (uint64_t)allocated_addr, m_mod_id.GetStopID(),
22960b57cec5SDimitry Andric             m_mod_id.GetMemoryID());
22970b57cec5SDimitry Andric   return allocated_addr;
22980b57cec5SDimitry Andric #endif
22990b57cec5SDimitry Andric }
23000b57cec5SDimitry Andric 
CallocateMemory(size_t size,uint32_t permissions,Status & error)23010b57cec5SDimitry Andric addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
23020b57cec5SDimitry Andric                                 Status &error) {
23030b57cec5SDimitry Andric   addr_t return_addr = AllocateMemory(size, permissions, error);
23040b57cec5SDimitry Andric   if (error.Success()) {
23050b57cec5SDimitry Andric     std::string buffer(size, 0);
23060b57cec5SDimitry Andric     WriteMemory(return_addr, buffer.c_str(), size, error);
23070b57cec5SDimitry Andric   }
23080b57cec5SDimitry Andric   return return_addr;
23090b57cec5SDimitry Andric }
23100b57cec5SDimitry Andric 
CanJIT()23110b57cec5SDimitry Andric bool Process::CanJIT() {
23120b57cec5SDimitry Andric   if (m_can_jit == eCanJITDontKnow) {
23130b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
23140b57cec5SDimitry Andric     Status err;
23150b57cec5SDimitry Andric 
23160b57cec5SDimitry Andric     uint64_t allocated_memory = AllocateMemory(
23170b57cec5SDimitry Andric         8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
23180b57cec5SDimitry Andric         err);
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric     if (err.Success()) {
23210b57cec5SDimitry Andric       m_can_jit = eCanJITYes;
23229dba64beSDimitry Andric       LLDB_LOGF(log,
23239dba64beSDimitry Andric                 "Process::%s pid %" PRIu64
23240b57cec5SDimitry Andric                 " allocation test passed, CanJIT () is true",
23250b57cec5SDimitry Andric                 __FUNCTION__, GetID());
23260b57cec5SDimitry Andric     } else {
23270b57cec5SDimitry Andric       m_can_jit = eCanJITNo;
23289dba64beSDimitry Andric       LLDB_LOGF(log,
23299dba64beSDimitry Andric                 "Process::%s pid %" PRIu64
23300b57cec5SDimitry Andric                 " allocation test failed, CanJIT () is false: %s",
23310b57cec5SDimitry Andric                 __FUNCTION__, GetID(), err.AsCString());
23320b57cec5SDimitry Andric     }
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric     DeallocateMemory(allocated_memory);
23350b57cec5SDimitry Andric   }
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric   return m_can_jit == eCanJITYes;
23380b57cec5SDimitry Andric }
23390b57cec5SDimitry Andric 
SetCanJIT(bool can_jit)23400b57cec5SDimitry Andric void Process::SetCanJIT(bool can_jit) {
23410b57cec5SDimitry Andric   m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
23420b57cec5SDimitry Andric }
23430b57cec5SDimitry Andric 
SetCanRunCode(bool can_run_code)23440b57cec5SDimitry Andric void Process::SetCanRunCode(bool can_run_code) {
23450b57cec5SDimitry Andric   SetCanJIT(can_run_code);
23460b57cec5SDimitry Andric   m_can_interpret_function_calls = can_run_code;
23470b57cec5SDimitry Andric }
23480b57cec5SDimitry Andric 
DeallocateMemory(addr_t ptr)23490b57cec5SDimitry Andric Status Process::DeallocateMemory(addr_t ptr) {
23500b57cec5SDimitry Andric   Status error;
23510b57cec5SDimitry Andric #if defined(USE_ALLOCATE_MEMORY_CACHE)
23520b57cec5SDimitry Andric   if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
23530b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
23540b57cec5SDimitry Andric         "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
23550b57cec5SDimitry Andric   }
23560b57cec5SDimitry Andric #else
23570b57cec5SDimitry Andric   error = DoDeallocateMemory(ptr);
23580b57cec5SDimitry Andric 
23590b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
23609dba64beSDimitry Andric   LLDB_LOGF(log,
23619dba64beSDimitry Andric             "Process::DeallocateMemory(addr=0x%16.16" PRIx64
23620b57cec5SDimitry Andric             ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
23630b57cec5SDimitry Andric             ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
23640b57cec5SDimitry Andric             m_mod_id.GetMemoryID());
23650b57cec5SDimitry Andric #endif
23660b57cec5SDimitry Andric   return error;
23670b57cec5SDimitry Andric }
23680b57cec5SDimitry Andric 
ReadModuleFromMemory(const FileSpec & file_spec,lldb::addr_t header_addr,size_t size_to_read)23690b57cec5SDimitry Andric ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
23700b57cec5SDimitry Andric                                        lldb::addr_t header_addr,
23710b57cec5SDimitry Andric                                        size_t size_to_read) {
23720b57cec5SDimitry Andric   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
23730b57cec5SDimitry Andric   if (log) {
23749dba64beSDimitry Andric     LLDB_LOGF(log,
23759dba64beSDimitry Andric               "Process::ReadModuleFromMemory reading %s binary from memory",
23760b57cec5SDimitry Andric               file_spec.GetPath().c_str());
23770b57cec5SDimitry Andric   }
23780b57cec5SDimitry Andric   ModuleSP module_sp(new Module(file_spec, ArchSpec()));
23790b57cec5SDimitry Andric   if (module_sp) {
23800b57cec5SDimitry Andric     Status error;
23810b57cec5SDimitry Andric     ObjectFile *objfile = module_sp->GetMemoryObjectFile(
23820b57cec5SDimitry Andric         shared_from_this(), header_addr, error, size_to_read);
23830b57cec5SDimitry Andric     if (objfile)
23840b57cec5SDimitry Andric       return module_sp;
23850b57cec5SDimitry Andric   }
23860b57cec5SDimitry Andric   return ModuleSP();
23870b57cec5SDimitry Andric }
23880b57cec5SDimitry Andric 
GetLoadAddressPermissions(lldb::addr_t load_addr,uint32_t & permissions)23890b57cec5SDimitry Andric bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
23900b57cec5SDimitry Andric                                         uint32_t &permissions) {
23910b57cec5SDimitry Andric   MemoryRegionInfo range_info;
23920b57cec5SDimitry Andric   permissions = 0;
23930b57cec5SDimitry Andric   Status error(GetMemoryRegionInfo(load_addr, range_info));
23940b57cec5SDimitry Andric   if (!error.Success())
23950b57cec5SDimitry Andric     return false;
23960b57cec5SDimitry Andric   if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
23970b57cec5SDimitry Andric       range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
23980b57cec5SDimitry Andric       range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
23990b57cec5SDimitry Andric     return false;
24000b57cec5SDimitry Andric   }
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   if (range_info.GetReadable() == MemoryRegionInfo::eYes)
24030b57cec5SDimitry Andric     permissions |= lldb::ePermissionsReadable;
24040b57cec5SDimitry Andric 
24050b57cec5SDimitry Andric   if (range_info.GetWritable() == MemoryRegionInfo::eYes)
24060b57cec5SDimitry Andric     permissions |= lldb::ePermissionsWritable;
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric   if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
24090b57cec5SDimitry Andric     permissions |= lldb::ePermissionsExecutable;
24100b57cec5SDimitry Andric 
24110b57cec5SDimitry Andric   return true;
24120b57cec5SDimitry Andric }
24130b57cec5SDimitry Andric 
EnableWatchpoint(Watchpoint * watchpoint,bool notify)24140b57cec5SDimitry Andric Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
24150b57cec5SDimitry Andric   Status error;
24160b57cec5SDimitry Andric   error.SetErrorString("watchpoints are not supported");
24170b57cec5SDimitry Andric   return error;
24180b57cec5SDimitry Andric }
24190b57cec5SDimitry Andric 
DisableWatchpoint(Watchpoint * watchpoint,bool notify)24200b57cec5SDimitry Andric Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
24210b57cec5SDimitry Andric   Status error;
24220b57cec5SDimitry Andric   error.SetErrorString("watchpoints are not supported");
24230b57cec5SDimitry Andric   return error;
24240b57cec5SDimitry Andric }
24250b57cec5SDimitry Andric 
24260b57cec5SDimitry Andric StateType
WaitForProcessStopPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout)24270b57cec5SDimitry Andric Process::WaitForProcessStopPrivate(EventSP &event_sp,
24280b57cec5SDimitry Andric                                    const Timeout<std::micro> &timeout) {
24290b57cec5SDimitry Andric   StateType state;
24300b57cec5SDimitry Andric 
24310b57cec5SDimitry Andric   while (true) {
24320b57cec5SDimitry Andric     event_sp.reset();
24330b57cec5SDimitry Andric     state = GetStateChangedEventsPrivate(event_sp, timeout);
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric     if (StateIsStoppedState(state, false))
24360b57cec5SDimitry Andric       break;
24370b57cec5SDimitry Andric 
24380b57cec5SDimitry Andric     // If state is invalid, then we timed out
24390b57cec5SDimitry Andric     if (state == eStateInvalid)
24400b57cec5SDimitry Andric       break;
24410b57cec5SDimitry Andric 
24420b57cec5SDimitry Andric     if (event_sp)
24430b57cec5SDimitry Andric       HandlePrivateEvent(event_sp);
24440b57cec5SDimitry Andric   }
24450b57cec5SDimitry Andric   return state;
24460b57cec5SDimitry Andric }
24470b57cec5SDimitry Andric 
LoadOperatingSystemPlugin(bool flush)24480b57cec5SDimitry Andric void Process::LoadOperatingSystemPlugin(bool flush) {
24490b57cec5SDimitry Andric   if (flush)
24500b57cec5SDimitry Andric     m_thread_list.Clear();
24510b57cec5SDimitry Andric   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
24520b57cec5SDimitry Andric   if (flush)
24530b57cec5SDimitry Andric     Flush();
24540b57cec5SDimitry Andric }
24550b57cec5SDimitry Andric 
Launch(ProcessLaunchInfo & launch_info)24560b57cec5SDimitry Andric Status Process::Launch(ProcessLaunchInfo &launch_info) {
24570b57cec5SDimitry Andric   Status error;
24580b57cec5SDimitry Andric   m_abi_sp.reset();
24590b57cec5SDimitry Andric   m_dyld_up.reset();
24600b57cec5SDimitry Andric   m_jit_loaders_up.reset();
24610b57cec5SDimitry Andric   m_system_runtime_up.reset();
24620b57cec5SDimitry Andric   m_os_up.reset();
24630b57cec5SDimitry Andric   m_process_input_reader.reset();
24640b57cec5SDimitry Andric 
24650b57cec5SDimitry Andric   Module *exe_module = GetTarget().GetExecutableModulePointer();
24660b57cec5SDimitry Andric   if (!exe_module) {
24670b57cec5SDimitry Andric     error.SetErrorString("executable module does not exist");
24680b57cec5SDimitry Andric     return error;
24690b57cec5SDimitry Andric   }
24700b57cec5SDimitry Andric 
24710b57cec5SDimitry Andric   char local_exec_file_path[PATH_MAX];
24720b57cec5SDimitry Andric   char platform_exec_file_path[PATH_MAX];
24730b57cec5SDimitry Andric   exe_module->GetFileSpec().GetPath(local_exec_file_path,
24740b57cec5SDimitry Andric                                     sizeof(local_exec_file_path));
24750b57cec5SDimitry Andric   exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
24760b57cec5SDimitry Andric                                             sizeof(platform_exec_file_path));
24770b57cec5SDimitry Andric   if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
24780b57cec5SDimitry Andric     // Install anything that might need to be installed prior to launching.
24790b57cec5SDimitry Andric     // For host systems, this will do nothing, but if we are connected to a
24800b57cec5SDimitry Andric     // remote platform it will install any needed binaries
24810b57cec5SDimitry Andric     error = GetTarget().Install(&launch_info);
24820b57cec5SDimitry Andric     if (error.Fail())
24830b57cec5SDimitry Andric       return error;
24840b57cec5SDimitry Andric 
2485*5f7ddb14SDimitry Andric     // Listen and queue events that are broadcasted during the process launch.
2486*5f7ddb14SDimitry Andric     ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2487*5f7ddb14SDimitry Andric     HijackProcessEvents(listener_sp);
2488*5f7ddb14SDimitry Andric     auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2489*5f7ddb14SDimitry Andric 
24900b57cec5SDimitry Andric     if (PrivateStateThreadIsValid())
24910b57cec5SDimitry Andric       PausePrivateStateThread();
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric     error = WillLaunch(exe_module);
24940b57cec5SDimitry Andric     if (error.Success()) {
24950b57cec5SDimitry Andric       const bool restarted = false;
24960b57cec5SDimitry Andric       SetPublicState(eStateLaunching, restarted);
24970b57cec5SDimitry Andric       m_should_detach = false;
24980b57cec5SDimitry Andric 
24990b57cec5SDimitry Andric       if (m_public_run_lock.TrySetRunning()) {
25000b57cec5SDimitry Andric         // Now launch using these arguments.
25010b57cec5SDimitry Andric         error = DoLaunch(exe_module, launch_info);
25020b57cec5SDimitry Andric       } else {
25030b57cec5SDimitry Andric         // This shouldn't happen
25040b57cec5SDimitry Andric         error.SetErrorString("failed to acquire process run lock");
25050b57cec5SDimitry Andric       }
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric       if (error.Fail()) {
25080b57cec5SDimitry Andric         if (GetID() != LLDB_INVALID_PROCESS_ID) {
25090b57cec5SDimitry Andric           SetID(LLDB_INVALID_PROCESS_ID);
25100b57cec5SDimitry Andric           const char *error_string = error.AsCString();
25110b57cec5SDimitry Andric           if (error_string == nullptr)
25120b57cec5SDimitry Andric             error_string = "launch failed";
25130b57cec5SDimitry Andric           SetExitStatus(-1, error_string);
25140b57cec5SDimitry Andric         }
25150b57cec5SDimitry Andric       } else {
25160b57cec5SDimitry Andric         EventSP event_sp;
25170b57cec5SDimitry Andric 
25180b57cec5SDimitry Andric         // Now wait for the process to launch and return control to us, and then
25190b57cec5SDimitry Andric         // call DidLaunch:
25200b57cec5SDimitry Andric         StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
25210b57cec5SDimitry Andric 
25220b57cec5SDimitry Andric         if (state == eStateInvalid || !event_sp) {
25230b57cec5SDimitry Andric           // We were able to launch the process, but we failed to catch the
25240b57cec5SDimitry Andric           // initial stop.
25250b57cec5SDimitry Andric           error.SetErrorString("failed to catch stop after launch");
25260b57cec5SDimitry Andric           SetExitStatus(0, "failed to catch stop after launch");
25270b57cec5SDimitry Andric           Destroy(false);
25280b57cec5SDimitry Andric         } else if (state == eStateStopped || state == eStateCrashed) {
25290b57cec5SDimitry Andric           DidLaunch();
25300b57cec5SDimitry Andric 
25310b57cec5SDimitry Andric           DynamicLoader *dyld = GetDynamicLoader();
25320b57cec5SDimitry Andric           if (dyld)
25330b57cec5SDimitry Andric             dyld->DidLaunch();
25340b57cec5SDimitry Andric 
25350b57cec5SDimitry Andric           GetJITLoaders().DidLaunch();
25360b57cec5SDimitry Andric 
25370b57cec5SDimitry Andric           SystemRuntime *system_runtime = GetSystemRuntime();
25380b57cec5SDimitry Andric           if (system_runtime)
25390b57cec5SDimitry Andric             system_runtime->DidLaunch();
25400b57cec5SDimitry Andric 
25410b57cec5SDimitry Andric           if (!m_os_up)
25420b57cec5SDimitry Andric             LoadOperatingSystemPlugin(false);
25430b57cec5SDimitry Andric 
25440b57cec5SDimitry Andric           // We successfully launched the process and stopped, now it the
25450b57cec5SDimitry Andric           // right time to set up signal filters before resuming.
25460b57cec5SDimitry Andric           UpdateAutomaticSignalFiltering();
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric           // Note, the stop event was consumed above, but not handled. This
25490b57cec5SDimitry Andric           // was done to give DidLaunch a chance to run. The target is either
25500b57cec5SDimitry Andric           // stopped or crashed. Directly set the state.  This is done to
25510b57cec5SDimitry Andric           // prevent a stop message with a bunch of spurious output on thread
25520b57cec5SDimitry Andric           // status, as well as not pop a ProcessIOHandler.
25530b57cec5SDimitry Andric           SetPublicState(state, false);
25540b57cec5SDimitry Andric 
25550b57cec5SDimitry Andric           if (PrivateStateThreadIsValid())
25560b57cec5SDimitry Andric             ResumePrivateStateThread();
25570b57cec5SDimitry Andric           else
25580b57cec5SDimitry Andric             StartPrivateStateThread();
25590b57cec5SDimitry Andric 
25600b57cec5SDimitry Andric           // Target was stopped at entry as was intended. Need to notify the
25610b57cec5SDimitry Andric           // listeners about it.
25620b57cec5SDimitry Andric           if (state == eStateStopped &&
25630b57cec5SDimitry Andric               launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
25640b57cec5SDimitry Andric             HandlePrivateEvent(event_sp);
25650b57cec5SDimitry Andric         } else if (state == eStateExited) {
25660b57cec5SDimitry Andric           // We exited while trying to launch somehow.  Don't call DidLaunch
25670b57cec5SDimitry Andric           // as that's not likely to work, and return an invalid pid.
25680b57cec5SDimitry Andric           HandlePrivateEvent(event_sp);
25690b57cec5SDimitry Andric         }
25700b57cec5SDimitry Andric       }
25710b57cec5SDimitry Andric     }
25720b57cec5SDimitry Andric   } else {
25730b57cec5SDimitry Andric     error.SetErrorStringWithFormat("file doesn't exist: '%s'",
25740b57cec5SDimitry Andric                                    local_exec_file_path);
25750b57cec5SDimitry Andric   }
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   return error;
25780b57cec5SDimitry Andric }
25790b57cec5SDimitry Andric 
LoadCore()25800b57cec5SDimitry Andric Status Process::LoadCore() {
25810b57cec5SDimitry Andric   Status error = DoLoadCore();
25820b57cec5SDimitry Andric   if (error.Success()) {
25830b57cec5SDimitry Andric     ListenerSP listener_sp(
25840b57cec5SDimitry Andric         Listener::MakeListener("lldb.process.load_core_listener"));
25850b57cec5SDimitry Andric     HijackProcessEvents(listener_sp);
25860b57cec5SDimitry Andric 
25870b57cec5SDimitry Andric     if (PrivateStateThreadIsValid())
25880b57cec5SDimitry Andric       ResumePrivateStateThread();
25890b57cec5SDimitry Andric     else
25900b57cec5SDimitry Andric       StartPrivateStateThread();
25910b57cec5SDimitry Andric 
25920b57cec5SDimitry Andric     DynamicLoader *dyld = GetDynamicLoader();
25930b57cec5SDimitry Andric     if (dyld)
25940b57cec5SDimitry Andric       dyld->DidAttach();
25950b57cec5SDimitry Andric 
25960b57cec5SDimitry Andric     GetJITLoaders().DidAttach();
25970b57cec5SDimitry Andric 
25980b57cec5SDimitry Andric     SystemRuntime *system_runtime = GetSystemRuntime();
25990b57cec5SDimitry Andric     if (system_runtime)
26000b57cec5SDimitry Andric       system_runtime->DidAttach();
26010b57cec5SDimitry Andric 
26020b57cec5SDimitry Andric     if (!m_os_up)
26030b57cec5SDimitry Andric       LoadOperatingSystemPlugin(false);
26040b57cec5SDimitry Andric 
26050b57cec5SDimitry Andric     // We successfully loaded a core file, now pretend we stopped so we can
26060b57cec5SDimitry Andric     // show all of the threads in the core file and explore the crashed state.
26070b57cec5SDimitry Andric     SetPrivateState(eStateStopped);
26080b57cec5SDimitry Andric 
26090b57cec5SDimitry Andric     // Wait for a stopped event since we just posted one above...
26100b57cec5SDimitry Andric     lldb::EventSP event_sp;
26110b57cec5SDimitry Andric     StateType state =
26120b57cec5SDimitry Andric         WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
26130b57cec5SDimitry Andric 
26140b57cec5SDimitry Andric     if (!StateIsStoppedState(state, false)) {
26150b57cec5SDimitry Andric       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
26169dba64beSDimitry Andric       LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
26170b57cec5SDimitry Andric                 StateAsCString(state));
26180b57cec5SDimitry Andric       error.SetErrorString(
26190b57cec5SDimitry Andric           "Did not get stopped event after loading the core file.");
26200b57cec5SDimitry Andric     }
26210b57cec5SDimitry Andric     RestoreProcessEvents();
26220b57cec5SDimitry Andric   }
26230b57cec5SDimitry Andric   return error;
26240b57cec5SDimitry Andric }
26250b57cec5SDimitry Andric 
GetDynamicLoader()26260b57cec5SDimitry Andric DynamicLoader *Process::GetDynamicLoader() {
26270b57cec5SDimitry Andric   if (!m_dyld_up)
26280b57cec5SDimitry Andric     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
26290b57cec5SDimitry Andric   return m_dyld_up.get();
26300b57cec5SDimitry Andric }
26310b57cec5SDimitry Andric 
GetAuxvData()26320b57cec5SDimitry Andric DataExtractor Process::GetAuxvData() { return DataExtractor(); }
26330b57cec5SDimitry Andric 
GetJITLoaders()26340b57cec5SDimitry Andric JITLoaderList &Process::GetJITLoaders() {
26350b57cec5SDimitry Andric   if (!m_jit_loaders_up) {
26365ffd83dbSDimitry Andric     m_jit_loaders_up = std::make_unique<JITLoaderList>();
26370b57cec5SDimitry Andric     JITLoader::LoadPlugins(this, *m_jit_loaders_up);
26380b57cec5SDimitry Andric   }
26390b57cec5SDimitry Andric   return *m_jit_loaders_up;
26400b57cec5SDimitry Andric }
26410b57cec5SDimitry Andric 
GetSystemRuntime()26420b57cec5SDimitry Andric SystemRuntime *Process::GetSystemRuntime() {
26430b57cec5SDimitry Andric   if (!m_system_runtime_up)
26440b57cec5SDimitry Andric     m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
26450b57cec5SDimitry Andric   return m_system_runtime_up.get();
26460b57cec5SDimitry Andric }
26470b57cec5SDimitry Andric 
AttachCompletionHandler(Process * process,uint32_t exec_count)26480b57cec5SDimitry Andric Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
26490b57cec5SDimitry Andric                                                           uint32_t exec_count)
26500b57cec5SDimitry Andric     : NextEventAction(process), m_exec_count(exec_count) {
26510b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
26529dba64beSDimitry Andric   LLDB_LOGF(
26539dba64beSDimitry Andric       log,
26540b57cec5SDimitry Andric       "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
26550b57cec5SDimitry Andric       __FUNCTION__, static_cast<void *>(process), exec_count);
26560b57cec5SDimitry Andric }
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric Process::NextEventAction::EventActionResult
PerformAction(lldb::EventSP & event_sp)26590b57cec5SDimitry Andric Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
26600b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric   StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
26639dba64beSDimitry Andric   LLDB_LOGF(log,
26640b57cec5SDimitry Andric             "Process::AttachCompletionHandler::%s called with state %s (%d)",
26650b57cec5SDimitry Andric             __FUNCTION__, StateAsCString(state), static_cast<int>(state));
26660b57cec5SDimitry Andric 
26670b57cec5SDimitry Andric   switch (state) {
26680b57cec5SDimitry Andric   case eStateAttaching:
26690b57cec5SDimitry Andric     return eEventActionSuccess;
26700b57cec5SDimitry Andric 
26710b57cec5SDimitry Andric   case eStateRunning:
26720b57cec5SDimitry Andric   case eStateConnected:
26730b57cec5SDimitry Andric     return eEventActionRetry;
26740b57cec5SDimitry Andric 
26750b57cec5SDimitry Andric   case eStateStopped:
26760b57cec5SDimitry Andric   case eStateCrashed:
26770b57cec5SDimitry Andric     // During attach, prior to sending the eStateStopped event,
26780b57cec5SDimitry Andric     // lldb_private::Process subclasses must set the new process ID.
26790b57cec5SDimitry Andric     assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
26800b57cec5SDimitry Andric     // We don't want these events to be reported, so go set the
26810b57cec5SDimitry Andric     // ShouldReportStop here:
26820b57cec5SDimitry Andric     m_process->GetThreadList().SetShouldReportStop(eVoteNo);
26830b57cec5SDimitry Andric 
26840b57cec5SDimitry Andric     if (m_exec_count > 0) {
26850b57cec5SDimitry Andric       --m_exec_count;
26860b57cec5SDimitry Andric 
26879dba64beSDimitry Andric       LLDB_LOGF(log,
26889dba64beSDimitry Andric                 "Process::AttachCompletionHandler::%s state %s: reduced "
26890b57cec5SDimitry Andric                 "remaining exec count to %" PRIu32 ", requesting resume",
26900b57cec5SDimitry Andric                 __FUNCTION__, StateAsCString(state), m_exec_count);
26910b57cec5SDimitry Andric 
26920b57cec5SDimitry Andric       RequestResume();
26930b57cec5SDimitry Andric       return eEventActionRetry;
26940b57cec5SDimitry Andric     } else {
26959dba64beSDimitry Andric       LLDB_LOGF(log,
26969dba64beSDimitry Andric                 "Process::AttachCompletionHandler::%s state %s: no more "
26970b57cec5SDimitry Andric                 "execs expected to start, continuing with attach",
26980b57cec5SDimitry Andric                 __FUNCTION__, StateAsCString(state));
26990b57cec5SDimitry Andric 
27000b57cec5SDimitry Andric       m_process->CompleteAttach();
27010b57cec5SDimitry Andric       return eEventActionSuccess;
27020b57cec5SDimitry Andric     }
27030b57cec5SDimitry Andric     break;
27040b57cec5SDimitry Andric 
27050b57cec5SDimitry Andric   default:
27060b57cec5SDimitry Andric   case eStateExited:
27070b57cec5SDimitry Andric   case eStateInvalid:
27080b57cec5SDimitry Andric     break;
27090b57cec5SDimitry Andric   }
27100b57cec5SDimitry Andric 
27110b57cec5SDimitry Andric   m_exit_string.assign("No valid Process");
27120b57cec5SDimitry Andric   return eEventActionExit;
27130b57cec5SDimitry Andric }
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric Process::NextEventAction::EventActionResult
HandleBeingInterrupted()27160b57cec5SDimitry Andric Process::AttachCompletionHandler::HandleBeingInterrupted() {
27170b57cec5SDimitry Andric   return eEventActionSuccess;
27180b57cec5SDimitry Andric }
27190b57cec5SDimitry Andric 
GetExitString()27200b57cec5SDimitry Andric const char *Process::AttachCompletionHandler::GetExitString() {
27210b57cec5SDimitry Andric   return m_exit_string.c_str();
27220b57cec5SDimitry Andric }
27230b57cec5SDimitry Andric 
GetListenerForProcess(Debugger & debugger)27240b57cec5SDimitry Andric ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
27250b57cec5SDimitry Andric   if (m_listener_sp)
27260b57cec5SDimitry Andric     return m_listener_sp;
27270b57cec5SDimitry Andric   else
27280b57cec5SDimitry Andric     return debugger.GetListener();
27290b57cec5SDimitry Andric }
27300b57cec5SDimitry Andric 
Attach(ProcessAttachInfo & attach_info)27310b57cec5SDimitry Andric Status Process::Attach(ProcessAttachInfo &attach_info) {
27320b57cec5SDimitry Andric   m_abi_sp.reset();
27330b57cec5SDimitry Andric   m_process_input_reader.reset();
27340b57cec5SDimitry Andric   m_dyld_up.reset();
27350b57cec5SDimitry Andric   m_jit_loaders_up.reset();
27360b57cec5SDimitry Andric   m_system_runtime_up.reset();
27370b57cec5SDimitry Andric   m_os_up.reset();
27380b57cec5SDimitry Andric 
27390b57cec5SDimitry Andric   lldb::pid_t attach_pid = attach_info.GetProcessID();
27400b57cec5SDimitry Andric   Status error;
27410b57cec5SDimitry Andric   if (attach_pid == LLDB_INVALID_PROCESS_ID) {
27420b57cec5SDimitry Andric     char process_name[PATH_MAX];
27430b57cec5SDimitry Andric 
27440b57cec5SDimitry Andric     if (attach_info.GetExecutableFile().GetPath(process_name,
27450b57cec5SDimitry Andric                                                 sizeof(process_name))) {
27460b57cec5SDimitry Andric       const bool wait_for_launch = attach_info.GetWaitForLaunch();
27470b57cec5SDimitry Andric 
27480b57cec5SDimitry Andric       if (wait_for_launch) {
27490b57cec5SDimitry Andric         error = WillAttachToProcessWithName(process_name, wait_for_launch);
27500b57cec5SDimitry Andric         if (error.Success()) {
27510b57cec5SDimitry Andric           if (m_public_run_lock.TrySetRunning()) {
27520b57cec5SDimitry Andric             m_should_detach = true;
27530b57cec5SDimitry Andric             const bool restarted = false;
27540b57cec5SDimitry Andric             SetPublicState(eStateAttaching, restarted);
27550b57cec5SDimitry Andric             // Now attach using these arguments.
27560b57cec5SDimitry Andric             error = DoAttachToProcessWithName(process_name, attach_info);
27570b57cec5SDimitry Andric           } else {
27580b57cec5SDimitry Andric             // This shouldn't happen
27590b57cec5SDimitry Andric             error.SetErrorString("failed to acquire process run lock");
27600b57cec5SDimitry Andric           }
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric           if (error.Fail()) {
27630b57cec5SDimitry Andric             if (GetID() != LLDB_INVALID_PROCESS_ID) {
27640b57cec5SDimitry Andric               SetID(LLDB_INVALID_PROCESS_ID);
27650b57cec5SDimitry Andric               if (error.AsCString() == nullptr)
27660b57cec5SDimitry Andric                 error.SetErrorString("attach failed");
27670b57cec5SDimitry Andric 
27680b57cec5SDimitry Andric               SetExitStatus(-1, error.AsCString());
27690b57cec5SDimitry Andric             }
27700b57cec5SDimitry Andric           } else {
27710b57cec5SDimitry Andric             SetNextEventAction(new Process::AttachCompletionHandler(
27720b57cec5SDimitry Andric                 this, attach_info.GetResumeCount()));
27730b57cec5SDimitry Andric             StartPrivateStateThread();
27740b57cec5SDimitry Andric           }
27750b57cec5SDimitry Andric           return error;
27760b57cec5SDimitry Andric         }
27770b57cec5SDimitry Andric       } else {
27780b57cec5SDimitry Andric         ProcessInstanceInfoList process_infos;
27790b57cec5SDimitry Andric         PlatformSP platform_sp(GetTarget().GetPlatform());
27800b57cec5SDimitry Andric 
27810b57cec5SDimitry Andric         if (platform_sp) {
27820b57cec5SDimitry Andric           ProcessInstanceInfoMatch match_info;
27830b57cec5SDimitry Andric           match_info.GetProcessInfo() = attach_info;
27840b57cec5SDimitry Andric           match_info.SetNameMatchType(NameMatch::Equals);
27850b57cec5SDimitry Andric           platform_sp->FindProcesses(match_info, process_infos);
27865ffd83dbSDimitry Andric           const uint32_t num_matches = process_infos.size();
27870b57cec5SDimitry Andric           if (num_matches == 1) {
27885ffd83dbSDimitry Andric             attach_pid = process_infos[0].GetProcessID();
27890b57cec5SDimitry Andric             // Fall through and attach using the above process ID
27900b57cec5SDimitry Andric           } else {
27910b57cec5SDimitry Andric             match_info.GetProcessInfo().GetExecutableFile().GetPath(
27920b57cec5SDimitry Andric                 process_name, sizeof(process_name));
27930b57cec5SDimitry Andric             if (num_matches > 1) {
27940b57cec5SDimitry Andric               StreamString s;
27950b57cec5SDimitry Andric               ProcessInstanceInfo::DumpTableHeader(s, true, false);
27960b57cec5SDimitry Andric               for (size_t i = 0; i < num_matches; i++) {
27975ffd83dbSDimitry Andric                 process_infos[i].DumpAsTableRow(
27980b57cec5SDimitry Andric                     s, platform_sp->GetUserIDResolver(), true, false);
27990b57cec5SDimitry Andric               }
28000b57cec5SDimitry Andric               error.SetErrorStringWithFormat(
28010b57cec5SDimitry Andric                   "more than one process named %s:\n%s", process_name,
28020b57cec5SDimitry Andric                   s.GetData());
28030b57cec5SDimitry Andric             } else
28040b57cec5SDimitry Andric               error.SetErrorStringWithFormat(
28050b57cec5SDimitry Andric                   "could not find a process named %s", process_name);
28060b57cec5SDimitry Andric           }
28070b57cec5SDimitry Andric         } else {
28080b57cec5SDimitry Andric           error.SetErrorString(
28090b57cec5SDimitry Andric               "invalid platform, can't find processes by name");
28100b57cec5SDimitry Andric           return error;
28110b57cec5SDimitry Andric         }
28120b57cec5SDimitry Andric       }
28130b57cec5SDimitry Andric     } else {
28140b57cec5SDimitry Andric       error.SetErrorString("invalid process name");
28150b57cec5SDimitry Andric     }
28160b57cec5SDimitry Andric   }
28170b57cec5SDimitry Andric 
28180b57cec5SDimitry Andric   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
28190b57cec5SDimitry Andric     error = WillAttachToProcessWithID(attach_pid);
28200b57cec5SDimitry Andric     if (error.Success()) {
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric       if (m_public_run_lock.TrySetRunning()) {
28230b57cec5SDimitry Andric         // Now attach using these arguments.
28240b57cec5SDimitry Andric         m_should_detach = true;
28250b57cec5SDimitry Andric         const bool restarted = false;
28260b57cec5SDimitry Andric         SetPublicState(eStateAttaching, restarted);
28270b57cec5SDimitry Andric         error = DoAttachToProcessWithID(attach_pid, attach_info);
28280b57cec5SDimitry Andric       } else {
28290b57cec5SDimitry Andric         // This shouldn't happen
28300b57cec5SDimitry Andric         error.SetErrorString("failed to acquire process run lock");
28310b57cec5SDimitry Andric       }
28320b57cec5SDimitry Andric 
28330b57cec5SDimitry Andric       if (error.Success()) {
28340b57cec5SDimitry Andric         SetNextEventAction(new Process::AttachCompletionHandler(
28350b57cec5SDimitry Andric             this, attach_info.GetResumeCount()));
28360b57cec5SDimitry Andric         StartPrivateStateThread();
28370b57cec5SDimitry Andric       } else {
28380b57cec5SDimitry Andric         if (GetID() != LLDB_INVALID_PROCESS_ID)
28390b57cec5SDimitry Andric           SetID(LLDB_INVALID_PROCESS_ID);
28400b57cec5SDimitry Andric 
28410b57cec5SDimitry Andric         const char *error_string = error.AsCString();
28420b57cec5SDimitry Andric         if (error_string == nullptr)
28430b57cec5SDimitry Andric           error_string = "attach failed";
28440b57cec5SDimitry Andric 
28450b57cec5SDimitry Andric         SetExitStatus(-1, error_string);
28460b57cec5SDimitry Andric       }
28470b57cec5SDimitry Andric     }
28480b57cec5SDimitry Andric   }
28490b57cec5SDimitry Andric   return error;
28500b57cec5SDimitry Andric }
28510b57cec5SDimitry Andric 
CompleteAttach()28520b57cec5SDimitry Andric void Process::CompleteAttach() {
28530b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
28540b57cec5SDimitry Andric                                                   LIBLLDB_LOG_TARGET));
28559dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
28560b57cec5SDimitry Andric 
28570b57cec5SDimitry Andric   // Let the process subclass figure out at much as it can about the process
28580b57cec5SDimitry Andric   // before we go looking for a dynamic loader plug-in.
28590b57cec5SDimitry Andric   ArchSpec process_arch;
28600b57cec5SDimitry Andric   DidAttach(process_arch);
28610b57cec5SDimitry Andric 
28620b57cec5SDimitry Andric   if (process_arch.IsValid()) {
28630b57cec5SDimitry Andric     GetTarget().SetArchitecture(process_arch);
28640b57cec5SDimitry Andric     if (log) {
28650b57cec5SDimitry Andric       const char *triple_str = process_arch.GetTriple().getTriple().c_str();
28669dba64beSDimitry Andric       LLDB_LOGF(log,
28679dba64beSDimitry Andric                 "Process::%s replacing process architecture with DidAttach() "
28680b57cec5SDimitry Andric                 "architecture: %s",
28690b57cec5SDimitry Andric                 __FUNCTION__, triple_str ? triple_str : "<null>");
28700b57cec5SDimitry Andric     }
28710b57cec5SDimitry Andric   }
28720b57cec5SDimitry Andric 
28730b57cec5SDimitry Andric   // We just attached.  If we have a platform, ask it for the process
28740b57cec5SDimitry Andric   // architecture, and if it isn't the same as the one we've already set,
28750b57cec5SDimitry Andric   // switch architectures.
28760b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
28770b57cec5SDimitry Andric   assert(platform_sp);
28780b57cec5SDimitry Andric   if (platform_sp) {
28790b57cec5SDimitry Andric     const ArchSpec &target_arch = GetTarget().GetArchitecture();
28800b57cec5SDimitry Andric     if (target_arch.IsValid() &&
28810b57cec5SDimitry Andric         !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
28820b57cec5SDimitry Andric       ArchSpec platform_arch;
28830b57cec5SDimitry Andric       platform_sp =
28840b57cec5SDimitry Andric           platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
28850b57cec5SDimitry Andric       if (platform_sp) {
28860b57cec5SDimitry Andric         GetTarget().SetPlatform(platform_sp);
28870b57cec5SDimitry Andric         GetTarget().SetArchitecture(platform_arch);
28889dba64beSDimitry Andric         LLDB_LOGF(log,
28899dba64beSDimitry Andric                   "Process::%s switching platform to %s and architecture "
28900b57cec5SDimitry Andric                   "to %s based on info from attach",
28910b57cec5SDimitry Andric                   __FUNCTION__, platform_sp->GetName().AsCString(""),
28920b57cec5SDimitry Andric                   platform_arch.GetTriple().getTriple().c_str());
28930b57cec5SDimitry Andric       }
28940b57cec5SDimitry Andric     } else if (!process_arch.IsValid()) {
28950b57cec5SDimitry Andric       ProcessInstanceInfo process_info;
28960b57cec5SDimitry Andric       GetProcessInfo(process_info);
28970b57cec5SDimitry Andric       const ArchSpec &process_arch = process_info.GetArchitecture();
2898*5f7ddb14SDimitry Andric       const ArchSpec &target_arch = GetTarget().GetArchitecture();
28990b57cec5SDimitry Andric       if (process_arch.IsValid() &&
2900*5f7ddb14SDimitry Andric           target_arch.IsCompatibleMatch(process_arch) &&
2901*5f7ddb14SDimitry Andric           !target_arch.IsExactMatch(process_arch)) {
29020b57cec5SDimitry Andric         GetTarget().SetArchitecture(process_arch);
29039dba64beSDimitry Andric         LLDB_LOGF(log,
29049dba64beSDimitry Andric                   "Process::%s switching architecture to %s based on info "
29050b57cec5SDimitry Andric                   "the platform retrieved for pid %" PRIu64,
29069dba64beSDimitry Andric                   __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
29079dba64beSDimitry Andric                   GetID());
29080b57cec5SDimitry Andric       }
29090b57cec5SDimitry Andric     }
29100b57cec5SDimitry Andric   }
29110b57cec5SDimitry Andric 
29120b57cec5SDimitry Andric   // We have completed the attach, now it is time to find the dynamic loader
29130b57cec5SDimitry Andric   // plug-in
29140b57cec5SDimitry Andric   DynamicLoader *dyld = GetDynamicLoader();
29150b57cec5SDimitry Andric   if (dyld) {
29160b57cec5SDimitry Andric     dyld->DidAttach();
29170b57cec5SDimitry Andric     if (log) {
29180b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
29199dba64beSDimitry Andric       LLDB_LOGF(log,
29209dba64beSDimitry Andric                 "Process::%s after DynamicLoader::DidAttach(), target "
29210b57cec5SDimitry Andric                 "executable is %s (using %s plugin)",
29220b57cec5SDimitry Andric                 __FUNCTION__,
29230b57cec5SDimitry Andric                 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
29240b57cec5SDimitry Andric                               : "<none>",
29250b57cec5SDimitry Andric                 dyld->GetPluginName().AsCString("<unnamed>"));
29260b57cec5SDimitry Andric     }
29270b57cec5SDimitry Andric   }
29280b57cec5SDimitry Andric 
29290b57cec5SDimitry Andric   GetJITLoaders().DidAttach();
29300b57cec5SDimitry Andric 
29310b57cec5SDimitry Andric   SystemRuntime *system_runtime = GetSystemRuntime();
29320b57cec5SDimitry Andric   if (system_runtime) {
29330b57cec5SDimitry Andric     system_runtime->DidAttach();
29340b57cec5SDimitry Andric     if (log) {
29350b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
29369dba64beSDimitry Andric       LLDB_LOGF(log,
29379dba64beSDimitry Andric                 "Process::%s after SystemRuntime::DidAttach(), target "
29380b57cec5SDimitry Andric                 "executable is %s (using %s plugin)",
29390b57cec5SDimitry Andric                 __FUNCTION__,
29400b57cec5SDimitry Andric                 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
29410b57cec5SDimitry Andric                               : "<none>",
29420b57cec5SDimitry Andric                 system_runtime->GetPluginName().AsCString("<unnamed>"));
29430b57cec5SDimitry Andric     }
29440b57cec5SDimitry Andric   }
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric   if (!m_os_up) {
29470b57cec5SDimitry Andric     LoadOperatingSystemPlugin(false);
29480b57cec5SDimitry Andric     if (m_os_up) {
29490b57cec5SDimitry Andric       // Somebody might have gotten threads before now, but we need to force the
29500b57cec5SDimitry Andric       // update after we've loaded the OperatingSystem plugin or it won't get a
29510b57cec5SDimitry Andric       // chance to process the threads.
29520b57cec5SDimitry Andric       m_thread_list.Clear();
29530b57cec5SDimitry Andric       UpdateThreadListIfNeeded();
29540b57cec5SDimitry Andric     }
29550b57cec5SDimitry Andric   }
29560b57cec5SDimitry Andric   // Figure out which one is the executable, and set that in our target:
29570b57cec5SDimitry Andric   ModuleSP new_executable_module_sp;
2958af732203SDimitry Andric   for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
29590b57cec5SDimitry Andric     if (module_sp && module_sp->IsExecutable()) {
29600b57cec5SDimitry Andric       if (GetTarget().GetExecutableModulePointer() != module_sp.get())
29610b57cec5SDimitry Andric         new_executable_module_sp = module_sp;
29620b57cec5SDimitry Andric       break;
29630b57cec5SDimitry Andric     }
29640b57cec5SDimitry Andric   }
29650b57cec5SDimitry Andric   if (new_executable_module_sp) {
29660b57cec5SDimitry Andric     GetTarget().SetExecutableModule(new_executable_module_sp,
29670b57cec5SDimitry Andric                                     eLoadDependentsNo);
29680b57cec5SDimitry Andric     if (log) {
29690b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
29709dba64beSDimitry Andric       LLDB_LOGF(
29719dba64beSDimitry Andric           log,
29720b57cec5SDimitry Andric           "Process::%s after looping through modules, target executable is %s",
29730b57cec5SDimitry Andric           __FUNCTION__,
29740b57cec5SDimitry Andric           exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
29750b57cec5SDimitry Andric                         : "<none>");
29760b57cec5SDimitry Andric     }
29770b57cec5SDimitry Andric   }
29780b57cec5SDimitry Andric }
29790b57cec5SDimitry Andric 
ConnectRemote(llvm::StringRef remote_url)29805ffd83dbSDimitry Andric Status Process::ConnectRemote(llvm::StringRef remote_url) {
29810b57cec5SDimitry Andric   m_abi_sp.reset();
29820b57cec5SDimitry Andric   m_process_input_reader.reset();
29830b57cec5SDimitry Andric 
29840b57cec5SDimitry Andric   // Find the process and its architecture.  Make sure it matches the
29850b57cec5SDimitry Andric   // architecture of the current Target, and if not adjust it.
29860b57cec5SDimitry Andric 
29875ffd83dbSDimitry Andric   Status error(DoConnectRemote(remote_url));
29880b57cec5SDimitry Andric   if (error.Success()) {
29890b57cec5SDimitry Andric     if (GetID() != LLDB_INVALID_PROCESS_ID) {
29900b57cec5SDimitry Andric       EventSP event_sp;
29910b57cec5SDimitry Andric       StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
29920b57cec5SDimitry Andric 
29930b57cec5SDimitry Andric       if (state == eStateStopped || state == eStateCrashed) {
29940b57cec5SDimitry Andric         // If we attached and actually have a process on the other end, then
29950b57cec5SDimitry Andric         // this ended up being the equivalent of an attach.
29960b57cec5SDimitry Andric         CompleteAttach();
29970b57cec5SDimitry Andric 
29980b57cec5SDimitry Andric         // This delays passing the stopped event to listeners till
29990b57cec5SDimitry Andric         // CompleteAttach gets a chance to complete...
30000b57cec5SDimitry Andric         HandlePrivateEvent(event_sp);
30010b57cec5SDimitry Andric       }
30020b57cec5SDimitry Andric     }
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric     if (PrivateStateThreadIsValid())
30050b57cec5SDimitry Andric       ResumePrivateStateThread();
30060b57cec5SDimitry Andric     else
30070b57cec5SDimitry Andric       StartPrivateStateThread();
30080b57cec5SDimitry Andric   }
30090b57cec5SDimitry Andric   return error;
30100b57cec5SDimitry Andric }
30110b57cec5SDimitry Andric 
PrivateResume()30120b57cec5SDimitry Andric Status Process::PrivateResume() {
30130b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
30140b57cec5SDimitry Andric                                                   LIBLLDB_LOG_STEP));
30159dba64beSDimitry Andric   LLDB_LOGF(log,
30169dba64beSDimitry Andric             "Process::PrivateResume() m_stop_id = %u, public state: %s "
30170b57cec5SDimitry Andric             "private state: %s",
30180b57cec5SDimitry Andric             m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
30190b57cec5SDimitry Andric             StateAsCString(m_private_state.GetValue()));
30200b57cec5SDimitry Andric 
30210b57cec5SDimitry Andric   // If signals handing status changed we might want to update our signal
30220b57cec5SDimitry Andric   // filters before resuming.
30230b57cec5SDimitry Andric   UpdateAutomaticSignalFiltering();
30240b57cec5SDimitry Andric 
30250b57cec5SDimitry Andric   Status error(WillResume());
30260b57cec5SDimitry Andric   // Tell the process it is about to resume before the thread list
30270b57cec5SDimitry Andric   if (error.Success()) {
30280b57cec5SDimitry Andric     // Now let the thread list know we are about to resume so it can let all of
30290b57cec5SDimitry Andric     // our threads know that they are about to be resumed. Threads will each be
30300b57cec5SDimitry Andric     // called with Thread::WillResume(StateType) where StateType contains the
30310b57cec5SDimitry Andric     // state that they are supposed to have when the process is resumed
30320b57cec5SDimitry Andric     // (suspended/running/stepping). Threads should also check their resume
30330b57cec5SDimitry Andric     // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
30340b57cec5SDimitry Andric     // start back up with a signal.
30350b57cec5SDimitry Andric     if (m_thread_list.WillResume()) {
30360b57cec5SDimitry Andric       // Last thing, do the PreResumeActions.
30370b57cec5SDimitry Andric       if (!RunPreResumeActions()) {
3038af732203SDimitry Andric         error.SetErrorString(
30390b57cec5SDimitry Andric             "Process::PrivateResume PreResumeActions failed, not resuming.");
30400b57cec5SDimitry Andric       } else {
30410b57cec5SDimitry Andric         m_mod_id.BumpResumeID();
30420b57cec5SDimitry Andric         error = DoResume();
30430b57cec5SDimitry Andric         if (error.Success()) {
30440b57cec5SDimitry Andric           DidResume();
30450b57cec5SDimitry Andric           m_thread_list.DidResume();
30469dba64beSDimitry Andric           LLDB_LOGF(log, "Process thinks the process has resumed.");
30470b57cec5SDimitry Andric         } else {
30489dba64beSDimitry Andric           LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
30490b57cec5SDimitry Andric           return error;
30500b57cec5SDimitry Andric         }
30510b57cec5SDimitry Andric       }
30520b57cec5SDimitry Andric     } else {
30530b57cec5SDimitry Andric       // Somebody wanted to run without running (e.g. we were faking a step
30540b57cec5SDimitry Andric       // from one frame of a set of inlined frames that share the same PC to
30550b57cec5SDimitry Andric       // another.)  So generate a continue & a stopped event, and let the world
30560b57cec5SDimitry Andric       // handle them.
30579dba64beSDimitry Andric       LLDB_LOGF(log,
30580b57cec5SDimitry Andric                 "Process::PrivateResume() asked to simulate a start & stop.");
30590b57cec5SDimitry Andric 
30600b57cec5SDimitry Andric       SetPrivateState(eStateRunning);
30610b57cec5SDimitry Andric       SetPrivateState(eStateStopped);
30620b57cec5SDimitry Andric     }
30639dba64beSDimitry Andric   } else
30649dba64beSDimitry Andric     LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
30650b57cec5SDimitry Andric               error.AsCString("<unknown error>"));
30660b57cec5SDimitry Andric   return error;
30670b57cec5SDimitry Andric }
30680b57cec5SDimitry Andric 
Halt(bool clear_thread_plans,bool use_run_lock)30690b57cec5SDimitry Andric Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
30700b57cec5SDimitry Andric   if (!StateIsRunningState(m_public_state.GetValue()))
30710b57cec5SDimitry Andric     return Status("Process is not running.");
30720b57cec5SDimitry Andric 
30730b57cec5SDimitry Andric   // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
30740b57cec5SDimitry Andric   // case it was already set and some thread plan logic calls halt on its own.
30750b57cec5SDimitry Andric   m_clear_thread_plans_on_stop |= clear_thread_plans;
30760b57cec5SDimitry Andric 
30770b57cec5SDimitry Andric   ListenerSP halt_listener_sp(
30780b57cec5SDimitry Andric       Listener::MakeListener("lldb.process.halt_listener"));
30790b57cec5SDimitry Andric   HijackProcessEvents(halt_listener_sp);
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric   EventSP event_sp;
30820b57cec5SDimitry Andric 
30830b57cec5SDimitry Andric   SendAsyncInterrupt();
30840b57cec5SDimitry Andric 
30850b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateAttaching) {
30860b57cec5SDimitry Andric     // Don't hijack and eat the eStateExited as the code that was doing the
30870b57cec5SDimitry Andric     // attach will be waiting for this event...
30880b57cec5SDimitry Andric     RestoreProcessEvents();
30890b57cec5SDimitry Andric     SetExitStatus(SIGKILL, "Cancelled async attach.");
30900b57cec5SDimitry Andric     Destroy(false);
30910b57cec5SDimitry Andric     return Status();
30920b57cec5SDimitry Andric   }
30930b57cec5SDimitry Andric 
3094*5f7ddb14SDimitry Andric   // Wait for the process halt timeout seconds for the process to stop.
3095*5f7ddb14SDimitry Andric   StateType state =
3096*5f7ddb14SDimitry Andric       WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3097*5f7ddb14SDimitry Andric                            halt_listener_sp, nullptr, use_run_lock);
30980b57cec5SDimitry Andric   RestoreProcessEvents();
30990b57cec5SDimitry Andric 
31000b57cec5SDimitry Andric   if (state == eStateInvalid || !event_sp) {
31010b57cec5SDimitry Andric     // We timed out and didn't get a stop event...
31020b57cec5SDimitry Andric     return Status("Halt timed out. State = %s", StateAsCString(GetState()));
31030b57cec5SDimitry Andric   }
31040b57cec5SDimitry Andric 
31050b57cec5SDimitry Andric   BroadcastEvent(event_sp);
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric   return Status();
31080b57cec5SDimitry Andric }
31090b57cec5SDimitry Andric 
StopForDestroyOrDetach(lldb::EventSP & exit_event_sp)31100b57cec5SDimitry Andric Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
31110b57cec5SDimitry Andric   Status error;
31120b57cec5SDimitry Andric 
31130b57cec5SDimitry Andric   // Check both the public & private states here.  If we're hung evaluating an
31140b57cec5SDimitry Andric   // expression, for instance, then the public state will be stopped, but we
31150b57cec5SDimitry Andric   // still need to interrupt.
31160b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateRunning ||
31170b57cec5SDimitry Andric       m_private_state.GetValue() == eStateRunning) {
31180b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
31199dba64beSDimitry Andric     LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
31200b57cec5SDimitry Andric 
31210b57cec5SDimitry Andric     ListenerSP listener_sp(
31220b57cec5SDimitry Andric         Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
31230b57cec5SDimitry Andric     HijackProcessEvents(listener_sp);
31240b57cec5SDimitry Andric 
31250b57cec5SDimitry Andric     SendAsyncInterrupt();
31260b57cec5SDimitry Andric 
31270b57cec5SDimitry Andric     // Consume the interrupt event.
3128*5f7ddb14SDimitry Andric     StateType state = WaitForProcessToStop(GetInterruptTimeout(),
3129*5f7ddb14SDimitry Andric                                            &exit_event_sp, true, listener_sp);
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric     RestoreProcessEvents();
31320b57cec5SDimitry Andric 
31330b57cec5SDimitry Andric     // If the process exited while we were waiting for it to stop, put the
31340b57cec5SDimitry Andric     // exited event into the shared pointer passed in and return.  Our caller
31350b57cec5SDimitry Andric     // doesn't need to do anything else, since they don't have a process
31360b57cec5SDimitry Andric     // anymore...
31370b57cec5SDimitry Andric 
31380b57cec5SDimitry Andric     if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
31399dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
31400b57cec5SDimitry Andric                 __FUNCTION__);
31410b57cec5SDimitry Andric       return error;
31420b57cec5SDimitry Andric     } else
31430b57cec5SDimitry Andric       exit_event_sp.reset(); // It is ok to consume any non-exit stop events
31440b57cec5SDimitry Andric 
31450b57cec5SDimitry Andric     if (state != eStateStopped) {
31469dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
31470b57cec5SDimitry Andric                 StateAsCString(state));
31480b57cec5SDimitry Andric       // If we really couldn't stop the process then we should just error out
31490b57cec5SDimitry Andric       // here, but if the lower levels just bobbled sending the event and we
31500b57cec5SDimitry Andric       // really are stopped, then continue on.
31510b57cec5SDimitry Andric       StateType private_state = m_private_state.GetValue();
31520b57cec5SDimitry Andric       if (private_state != eStateStopped) {
31530b57cec5SDimitry Andric         return Status(
31540b57cec5SDimitry Andric             "Attempt to stop the target in order to detach timed out. "
31550b57cec5SDimitry Andric             "State = %s",
31560b57cec5SDimitry Andric             StateAsCString(GetState()));
31570b57cec5SDimitry Andric       }
31580b57cec5SDimitry Andric     }
31590b57cec5SDimitry Andric   }
31600b57cec5SDimitry Andric   return error;
31610b57cec5SDimitry Andric }
31620b57cec5SDimitry Andric 
Detach(bool keep_stopped)31630b57cec5SDimitry Andric Status Process::Detach(bool keep_stopped) {
31640b57cec5SDimitry Andric   EventSP exit_event_sp;
31650b57cec5SDimitry Andric   Status error;
31660b57cec5SDimitry Andric   m_destroy_in_process = true;
31670b57cec5SDimitry Andric 
31680b57cec5SDimitry Andric   error = WillDetach();
31690b57cec5SDimitry Andric 
31700b57cec5SDimitry Andric   if (error.Success()) {
31710b57cec5SDimitry Andric     if (DetachRequiresHalt()) {
31720b57cec5SDimitry Andric       error = StopForDestroyOrDetach(exit_event_sp);
31730b57cec5SDimitry Andric       if (!error.Success()) {
31740b57cec5SDimitry Andric         m_destroy_in_process = false;
31750b57cec5SDimitry Andric         return error;
31760b57cec5SDimitry Andric       } else if (exit_event_sp) {
31770b57cec5SDimitry Andric         // We shouldn't need to do anything else here.  There's no process left
31780b57cec5SDimitry Andric         // to detach from...
31790b57cec5SDimitry Andric         StopPrivateStateThread();
31800b57cec5SDimitry Andric         m_destroy_in_process = false;
31810b57cec5SDimitry Andric         return error;
31820b57cec5SDimitry Andric       }
31830b57cec5SDimitry Andric     }
31840b57cec5SDimitry Andric 
31850b57cec5SDimitry Andric     m_thread_list.DiscardThreadPlans();
31860b57cec5SDimitry Andric     DisableAllBreakpointSites();
31870b57cec5SDimitry Andric 
31880b57cec5SDimitry Andric     error = DoDetach(keep_stopped);
31890b57cec5SDimitry Andric     if (error.Success()) {
31900b57cec5SDimitry Andric       DidDetach();
31910b57cec5SDimitry Andric       StopPrivateStateThread();
31920b57cec5SDimitry Andric     } else {
31930b57cec5SDimitry Andric       return error;
31940b57cec5SDimitry Andric     }
31950b57cec5SDimitry Andric   }
31960b57cec5SDimitry Andric   m_destroy_in_process = false;
31970b57cec5SDimitry Andric 
31980b57cec5SDimitry Andric   // If we exited when we were waiting for a process to stop, then forward the
31990b57cec5SDimitry Andric   // event here so we don't lose the event
32000b57cec5SDimitry Andric   if (exit_event_sp) {
32010b57cec5SDimitry Andric     // Directly broadcast our exited event because we shut down our private
32020b57cec5SDimitry Andric     // state thread above
32030b57cec5SDimitry Andric     BroadcastEvent(exit_event_sp);
32040b57cec5SDimitry Andric   }
32050b57cec5SDimitry Andric 
32060b57cec5SDimitry Andric   // If we have been interrupted (to kill us) in the middle of running, we may
32070b57cec5SDimitry Andric   // not end up propagating the last events through the event system, in which
32080b57cec5SDimitry Andric   // case we might strand the write lock.  Unlock it here so when we do to tear
32090b57cec5SDimitry Andric   // down the process we don't get an error destroying the lock.
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric   m_public_run_lock.SetStopped();
32120b57cec5SDimitry Andric   return error;
32130b57cec5SDimitry Andric }
32140b57cec5SDimitry Andric 
Destroy(bool force_kill)32150b57cec5SDimitry Andric Status Process::Destroy(bool force_kill) {
32165ffd83dbSDimitry Andric   // If we've already called Process::Finalize then there's nothing useful to
32175ffd83dbSDimitry Andric   // be done here.  Finalize has actually called Destroy already.
3218af732203SDimitry Andric   if (m_finalizing)
32195ffd83dbSDimitry Andric     return {};
3220af732203SDimitry Andric   return DestroyImpl(force_kill);
3221af732203SDimitry Andric }
32220b57cec5SDimitry Andric 
DestroyImpl(bool force_kill)3223af732203SDimitry Andric Status Process::DestroyImpl(bool force_kill) {
32240b57cec5SDimitry Andric   // Tell ourselves we are in the process of destroying the process, so that we
32250b57cec5SDimitry Andric   // don't do any unnecessary work that might hinder the destruction.  Remember
32260b57cec5SDimitry Andric   // to set this back to false when we are done.  That way if the attempt
32270b57cec5SDimitry Andric   // failed and the process stays around for some reason it won't be in a
32280b57cec5SDimitry Andric   // confused state.
32290b57cec5SDimitry Andric 
32300b57cec5SDimitry Andric   if (force_kill)
32310b57cec5SDimitry Andric     m_should_detach = false;
32320b57cec5SDimitry Andric 
32330b57cec5SDimitry Andric   if (GetShouldDetach()) {
32340b57cec5SDimitry Andric     // FIXME: This will have to be a process setting:
32350b57cec5SDimitry Andric     bool keep_stopped = false;
32360b57cec5SDimitry Andric     Detach(keep_stopped);
32370b57cec5SDimitry Andric   }
32380b57cec5SDimitry Andric 
32390b57cec5SDimitry Andric   m_destroy_in_process = true;
32400b57cec5SDimitry Andric 
32410b57cec5SDimitry Andric   Status error(WillDestroy());
32420b57cec5SDimitry Andric   if (error.Success()) {
32430b57cec5SDimitry Andric     EventSP exit_event_sp;
32440b57cec5SDimitry Andric     if (DestroyRequiresHalt()) {
32450b57cec5SDimitry Andric       error = StopForDestroyOrDetach(exit_event_sp);
32460b57cec5SDimitry Andric     }
32470b57cec5SDimitry Andric 
3248*5f7ddb14SDimitry Andric     if (m_public_state.GetValue() == eStateStopped) {
32490b57cec5SDimitry Andric       // Ditch all thread plans, and remove all our breakpoints: in case we
32500b57cec5SDimitry Andric       // have to restart the target to kill it, we don't want it hitting a
32510b57cec5SDimitry Andric       // breakpoint... Only do this if we've stopped, however, since if we
32520b57cec5SDimitry Andric       // didn't manage to halt it above, then we're not going to have much luck
32530b57cec5SDimitry Andric       // doing this now.
32540b57cec5SDimitry Andric       m_thread_list.DiscardThreadPlans();
32550b57cec5SDimitry Andric       DisableAllBreakpointSites();
32560b57cec5SDimitry Andric     }
32570b57cec5SDimitry Andric 
32580b57cec5SDimitry Andric     error = DoDestroy();
32590b57cec5SDimitry Andric     if (error.Success()) {
32600b57cec5SDimitry Andric       DidDestroy();
32610b57cec5SDimitry Andric       StopPrivateStateThread();
32620b57cec5SDimitry Andric     }
32630b57cec5SDimitry Andric     m_stdio_communication.StopReadThread();
32645ffd83dbSDimitry Andric     m_stdio_communication.Disconnect();
32650b57cec5SDimitry Andric     m_stdin_forward = false;
32660b57cec5SDimitry Andric 
32670b57cec5SDimitry Andric     if (m_process_input_reader) {
32680b57cec5SDimitry Andric       m_process_input_reader->SetIsDone(true);
32690b57cec5SDimitry Andric       m_process_input_reader->Cancel();
32700b57cec5SDimitry Andric       m_process_input_reader.reset();
32710b57cec5SDimitry Andric     }
32720b57cec5SDimitry Andric 
32730b57cec5SDimitry Andric     // If we exited when we were waiting for a process to stop, then forward
32740b57cec5SDimitry Andric     // the event here so we don't lose the event
32750b57cec5SDimitry Andric     if (exit_event_sp) {
32760b57cec5SDimitry Andric       // Directly broadcast our exited event because we shut down our private
32770b57cec5SDimitry Andric       // state thread above
32780b57cec5SDimitry Andric       BroadcastEvent(exit_event_sp);
32790b57cec5SDimitry Andric     }
32800b57cec5SDimitry Andric 
32810b57cec5SDimitry Andric     // If we have been interrupted (to kill us) in the middle of running, we
32820b57cec5SDimitry Andric     // may not end up propagating the last events through the event system, in
32830b57cec5SDimitry Andric     // which case we might strand the write lock.  Unlock it here so when we do
32840b57cec5SDimitry Andric     // to tear down the process we don't get an error destroying the lock.
32850b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
32860b57cec5SDimitry Andric   }
32870b57cec5SDimitry Andric 
32880b57cec5SDimitry Andric   m_destroy_in_process = false;
32890b57cec5SDimitry Andric 
32900b57cec5SDimitry Andric   return error;
32910b57cec5SDimitry Andric }
32920b57cec5SDimitry Andric 
Signal(int signal)32930b57cec5SDimitry Andric Status Process::Signal(int signal) {
32940b57cec5SDimitry Andric   Status error(WillSignal());
32950b57cec5SDimitry Andric   if (error.Success()) {
32960b57cec5SDimitry Andric     error = DoSignal(signal);
32970b57cec5SDimitry Andric     if (error.Success())
32980b57cec5SDimitry Andric       DidSignal();
32990b57cec5SDimitry Andric   }
33000b57cec5SDimitry Andric   return error;
33010b57cec5SDimitry Andric }
33020b57cec5SDimitry Andric 
SetUnixSignals(UnixSignalsSP && signals_sp)33030b57cec5SDimitry Andric void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
33040b57cec5SDimitry Andric   assert(signals_sp && "null signals_sp");
33050b57cec5SDimitry Andric   m_unix_signals_sp = signals_sp;
33060b57cec5SDimitry Andric }
33070b57cec5SDimitry Andric 
GetUnixSignals()33080b57cec5SDimitry Andric const lldb::UnixSignalsSP &Process::GetUnixSignals() {
33090b57cec5SDimitry Andric   assert(m_unix_signals_sp && "null m_unix_signals_sp");
33100b57cec5SDimitry Andric   return m_unix_signals_sp;
33110b57cec5SDimitry Andric }
33120b57cec5SDimitry Andric 
GetByteOrder() const33130b57cec5SDimitry Andric lldb::ByteOrder Process::GetByteOrder() const {
33140b57cec5SDimitry Andric   return GetTarget().GetArchitecture().GetByteOrder();
33150b57cec5SDimitry Andric }
33160b57cec5SDimitry Andric 
GetAddressByteSize() const33170b57cec5SDimitry Andric uint32_t Process::GetAddressByteSize() const {
33180b57cec5SDimitry Andric   return GetTarget().GetArchitecture().GetAddressByteSize();
33190b57cec5SDimitry Andric }
33200b57cec5SDimitry Andric 
ShouldBroadcastEvent(Event * event_ptr)33210b57cec5SDimitry Andric bool Process::ShouldBroadcastEvent(Event *event_ptr) {
33220b57cec5SDimitry Andric   const StateType state =
33230b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_ptr);
33240b57cec5SDimitry Andric   bool return_value = true;
33250b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
33260b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
33270b57cec5SDimitry Andric 
33280b57cec5SDimitry Andric   switch (state) {
33290b57cec5SDimitry Andric   case eStateDetached:
33300b57cec5SDimitry Andric   case eStateExited:
33310b57cec5SDimitry Andric   case eStateUnloaded:
33320b57cec5SDimitry Andric     m_stdio_communication.SynchronizeWithReadThread();
33330b57cec5SDimitry Andric     m_stdio_communication.StopReadThread();
33345ffd83dbSDimitry Andric     m_stdio_communication.Disconnect();
33350b57cec5SDimitry Andric     m_stdin_forward = false;
33360b57cec5SDimitry Andric 
33370b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
33380b57cec5SDimitry Andric   case eStateConnected:
33390b57cec5SDimitry Andric   case eStateAttaching:
33400b57cec5SDimitry Andric   case eStateLaunching:
33410b57cec5SDimitry Andric     // These events indicate changes in the state of the debugging session,
33420b57cec5SDimitry Andric     // always report them.
33430b57cec5SDimitry Andric     return_value = true;
33440b57cec5SDimitry Andric     break;
33450b57cec5SDimitry Andric   case eStateInvalid:
33460b57cec5SDimitry Andric     // We stopped for no apparent reason, don't report it.
33470b57cec5SDimitry Andric     return_value = false;
33480b57cec5SDimitry Andric     break;
33490b57cec5SDimitry Andric   case eStateRunning:
33500b57cec5SDimitry Andric   case eStateStepping:
33510b57cec5SDimitry Andric     // If we've started the target running, we handle the cases where we are
33520b57cec5SDimitry Andric     // already running and where there is a transition from stopped to running
33530b57cec5SDimitry Andric     // differently. running -> running: Automatically suppress extra running
33540b57cec5SDimitry Andric     // events stopped -> running: Report except when there is one or more no
33550b57cec5SDimitry Andric     // votes
33560b57cec5SDimitry Andric     //     and no yes votes.
33570b57cec5SDimitry Andric     SynchronouslyNotifyStateChanged(state);
33580b57cec5SDimitry Andric     if (m_force_next_event_delivery)
33590b57cec5SDimitry Andric       return_value = true;
33600b57cec5SDimitry Andric     else {
33610b57cec5SDimitry Andric       switch (m_last_broadcast_state) {
33620b57cec5SDimitry Andric       case eStateRunning:
33630b57cec5SDimitry Andric       case eStateStepping:
33640b57cec5SDimitry Andric         // We always suppress multiple runnings with no PUBLIC stop in between.
33650b57cec5SDimitry Andric         return_value = false;
33660b57cec5SDimitry Andric         break;
33670b57cec5SDimitry Andric       default:
33680b57cec5SDimitry Andric         // TODO: make this work correctly. For now always report
33690b57cec5SDimitry Andric         // run if we aren't running so we don't miss any running events. If I
33700b57cec5SDimitry Andric         // run the lldb/test/thread/a.out file and break at main.cpp:58, run
33710b57cec5SDimitry Andric         // and hit the breakpoints on multiple threads, then somehow during the
33720b57cec5SDimitry Andric         // stepping over of all breakpoints no run gets reported.
33730b57cec5SDimitry Andric 
33740b57cec5SDimitry Andric         // This is a transition from stop to run.
33750b57cec5SDimitry Andric         switch (m_thread_list.ShouldReportRun(event_ptr)) {
33760b57cec5SDimitry Andric         case eVoteYes:
33770b57cec5SDimitry Andric         case eVoteNoOpinion:
33780b57cec5SDimitry Andric           return_value = true;
33790b57cec5SDimitry Andric           break;
33800b57cec5SDimitry Andric         case eVoteNo:
33810b57cec5SDimitry Andric           return_value = false;
33820b57cec5SDimitry Andric           break;
33830b57cec5SDimitry Andric         }
33840b57cec5SDimitry Andric         break;
33850b57cec5SDimitry Andric       }
33860b57cec5SDimitry Andric     }
33870b57cec5SDimitry Andric     break;
33880b57cec5SDimitry Andric   case eStateStopped:
33890b57cec5SDimitry Andric   case eStateCrashed:
33900b57cec5SDimitry Andric   case eStateSuspended:
33910b57cec5SDimitry Andric     // We've stopped.  First see if we're going to restart the target. If we
33920b57cec5SDimitry Andric     // are going to stop, then we always broadcast the event. If we aren't
33930b57cec5SDimitry Andric     // going to stop, let the thread plans decide if we're going to report this
33940b57cec5SDimitry Andric     // event. If no thread has an opinion, we don't report it.
33950b57cec5SDimitry Andric 
33960b57cec5SDimitry Andric     m_stdio_communication.SynchronizeWithReadThread();
33970b57cec5SDimitry Andric     RefreshStateAfterStop();
33980b57cec5SDimitry Andric     if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
33999dba64beSDimitry Andric       LLDB_LOGF(log,
34009dba64beSDimitry Andric                 "Process::ShouldBroadcastEvent (%p) stopped due to an "
34010b57cec5SDimitry Andric                 "interrupt, state: %s",
34020b57cec5SDimitry Andric                 static_cast<void *>(event_ptr), StateAsCString(state));
34030b57cec5SDimitry Andric       // Even though we know we are going to stop, we should let the threads
34040b57cec5SDimitry Andric       // have a look at the stop, so they can properly set their state.
34050b57cec5SDimitry Andric       m_thread_list.ShouldStop(event_ptr);
34060b57cec5SDimitry Andric       return_value = true;
34070b57cec5SDimitry Andric     } else {
34080b57cec5SDimitry Andric       bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
34090b57cec5SDimitry Andric       bool should_resume = false;
34100b57cec5SDimitry Andric 
34110b57cec5SDimitry Andric       // It makes no sense to ask "ShouldStop" if we've already been
34120b57cec5SDimitry Andric       // restarted... Asking the thread list is also not likely to go well,
34130b57cec5SDimitry Andric       // since we are running again. So in that case just report the event.
34140b57cec5SDimitry Andric 
34150b57cec5SDimitry Andric       if (!was_restarted)
34160b57cec5SDimitry Andric         should_resume = !m_thread_list.ShouldStop(event_ptr);
34170b57cec5SDimitry Andric 
34180b57cec5SDimitry Andric       if (was_restarted || should_resume || m_resume_requested) {
3419*5f7ddb14SDimitry Andric         Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
34209dba64beSDimitry Andric         LLDB_LOGF(log,
34219dba64beSDimitry Andric                   "Process::ShouldBroadcastEvent: should_resume: %i state: "
3422*5f7ddb14SDimitry Andric                   "%s was_restarted: %i report_stop_vote: %d.",
34230b57cec5SDimitry Andric                   should_resume, StateAsCString(state), was_restarted,
3424*5f7ddb14SDimitry Andric                   report_stop_vote);
34250b57cec5SDimitry Andric 
3426*5f7ddb14SDimitry Andric         switch (report_stop_vote) {
34270b57cec5SDimitry Andric         case eVoteYes:
34280b57cec5SDimitry Andric           return_value = true;
34290b57cec5SDimitry Andric           break;
34300b57cec5SDimitry Andric         case eVoteNoOpinion:
34310b57cec5SDimitry Andric         case eVoteNo:
34320b57cec5SDimitry Andric           return_value = false;
34330b57cec5SDimitry Andric           break;
34340b57cec5SDimitry Andric         }
34350b57cec5SDimitry Andric 
34360b57cec5SDimitry Andric         if (!was_restarted) {
34379dba64beSDimitry Andric           LLDB_LOGF(log,
34389dba64beSDimitry Andric                     "Process::ShouldBroadcastEvent (%p) Restarting process "
34390b57cec5SDimitry Andric                     "from state: %s",
34400b57cec5SDimitry Andric                     static_cast<void *>(event_ptr), StateAsCString(state));
34410b57cec5SDimitry Andric           ProcessEventData::SetRestartedInEvent(event_ptr, true);
34420b57cec5SDimitry Andric           PrivateResume();
34430b57cec5SDimitry Andric         }
34440b57cec5SDimitry Andric       } else {
34450b57cec5SDimitry Andric         return_value = true;
34460b57cec5SDimitry Andric         SynchronouslyNotifyStateChanged(state);
34470b57cec5SDimitry Andric       }
34480b57cec5SDimitry Andric     }
34490b57cec5SDimitry Andric     break;
34500b57cec5SDimitry Andric   }
34510b57cec5SDimitry Andric 
34520b57cec5SDimitry Andric   // Forcing the next event delivery is a one shot deal.  So reset it here.
34530b57cec5SDimitry Andric   m_force_next_event_delivery = false;
34540b57cec5SDimitry Andric 
34550b57cec5SDimitry Andric   // We do some coalescing of events (for instance two consecutive running
34560b57cec5SDimitry Andric   // events get coalesced.) But we only coalesce against events we actually
34570b57cec5SDimitry Andric   // broadcast.  So we use m_last_broadcast_state to track that.  NB - you
34580b57cec5SDimitry Andric   // can't use "m_public_state.GetValue()" for that purpose, as was originally
34590b57cec5SDimitry Andric   // done, because the PublicState reflects the last event pulled off the
34600b57cec5SDimitry Andric   // queue, and there may be several events stacked up on the queue unserviced.
34610b57cec5SDimitry Andric   // So the PublicState may not reflect the last broadcasted event yet.
34620b57cec5SDimitry Andric   // m_last_broadcast_state gets updated here.
34630b57cec5SDimitry Andric 
34640b57cec5SDimitry Andric   if (return_value)
34650b57cec5SDimitry Andric     m_last_broadcast_state = state;
34660b57cec5SDimitry Andric 
34679dba64beSDimitry Andric   LLDB_LOGF(log,
34689dba64beSDimitry Andric             "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
34690b57cec5SDimitry Andric             "broadcast state: %s - %s",
34700b57cec5SDimitry Andric             static_cast<void *>(event_ptr), StateAsCString(state),
34710b57cec5SDimitry Andric             StateAsCString(m_last_broadcast_state),
34720b57cec5SDimitry Andric             return_value ? "YES" : "NO");
34730b57cec5SDimitry Andric   return return_value;
34740b57cec5SDimitry Andric }
34750b57cec5SDimitry Andric 
StartPrivateStateThread(bool is_secondary_thread)34760b57cec5SDimitry Andric bool Process::StartPrivateStateThread(bool is_secondary_thread) {
34770b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
34780b57cec5SDimitry Andric 
34790b57cec5SDimitry Andric   bool already_running = PrivateStateThreadIsValid();
34809dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
34810b57cec5SDimitry Andric             already_running ? " already running"
34820b57cec5SDimitry Andric                             : " starting private state thread");
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric   if (!is_secondary_thread && already_running)
34850b57cec5SDimitry Andric     return true;
34860b57cec5SDimitry Andric 
34870b57cec5SDimitry Andric   // Create a thread that watches our internal state and controls which events
34880b57cec5SDimitry Andric   // make it to clients (into the DCProcess event queue).
34890b57cec5SDimitry Andric   char thread_name[1024];
34900b57cec5SDimitry Andric   uint32_t max_len = llvm::get_max_thread_name_length();
34910b57cec5SDimitry Andric   if (max_len > 0 && max_len <= 30) {
34920b57cec5SDimitry Andric     // On platforms with abbreviated thread name lengths, choose thread names
34930b57cec5SDimitry Andric     // that fit within the limit.
34940b57cec5SDimitry Andric     if (already_running)
34950b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
34960b57cec5SDimitry Andric     else
34970b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name), "intern-state");
34980b57cec5SDimitry Andric   } else {
34990b57cec5SDimitry Andric     if (already_running)
35000b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name),
35010b57cec5SDimitry Andric                "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
35020b57cec5SDimitry Andric                GetID());
35030b57cec5SDimitry Andric     else
35040b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name),
35050b57cec5SDimitry Andric                "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
35060b57cec5SDimitry Andric   }
35070b57cec5SDimitry Andric 
35080b57cec5SDimitry Andric   // Create the private state thread, and start it running.
35090b57cec5SDimitry Andric   PrivateStateThreadArgs *args_ptr =
35100b57cec5SDimitry Andric       new PrivateStateThreadArgs(this, is_secondary_thread);
35110b57cec5SDimitry Andric   llvm::Expected<HostThread> private_state_thread =
35120b57cec5SDimitry Andric       ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
35130b57cec5SDimitry Andric                                    (void *)args_ptr, 8 * 1024 * 1024);
35140b57cec5SDimitry Andric   if (!private_state_thread) {
35150b57cec5SDimitry Andric     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
35160b57cec5SDimitry Andric              "failed to launch host thread: {}",
35170b57cec5SDimitry Andric              llvm::toString(private_state_thread.takeError()));
35180b57cec5SDimitry Andric     return false;
35190b57cec5SDimitry Andric   }
35200b57cec5SDimitry Andric 
35210b57cec5SDimitry Andric   assert(private_state_thread->IsJoinable());
35220b57cec5SDimitry Andric   m_private_state_thread = *private_state_thread;
35230b57cec5SDimitry Andric   ResumePrivateStateThread();
35240b57cec5SDimitry Andric   return true;
35250b57cec5SDimitry Andric }
35260b57cec5SDimitry Andric 
PausePrivateStateThread()35270b57cec5SDimitry Andric void Process::PausePrivateStateThread() {
35280b57cec5SDimitry Andric   ControlPrivateStateThread(eBroadcastInternalStateControlPause);
35290b57cec5SDimitry Andric }
35300b57cec5SDimitry Andric 
ResumePrivateStateThread()35310b57cec5SDimitry Andric void Process::ResumePrivateStateThread() {
35320b57cec5SDimitry Andric   ControlPrivateStateThread(eBroadcastInternalStateControlResume);
35330b57cec5SDimitry Andric }
35340b57cec5SDimitry Andric 
StopPrivateStateThread()35350b57cec5SDimitry Andric void Process::StopPrivateStateThread() {
35360b57cec5SDimitry Andric   if (m_private_state_thread.IsJoinable())
35370b57cec5SDimitry Andric     ControlPrivateStateThread(eBroadcastInternalStateControlStop);
35380b57cec5SDimitry Andric   else {
35390b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
35409dba64beSDimitry Andric     LLDB_LOGF(
35419dba64beSDimitry Andric         log,
35420b57cec5SDimitry Andric         "Went to stop the private state thread, but it was already invalid.");
35430b57cec5SDimitry Andric   }
35440b57cec5SDimitry Andric }
35450b57cec5SDimitry Andric 
ControlPrivateStateThread(uint32_t signal)35460b57cec5SDimitry Andric void Process::ControlPrivateStateThread(uint32_t signal) {
35470b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
35480b57cec5SDimitry Andric 
35490b57cec5SDimitry Andric   assert(signal == eBroadcastInternalStateControlStop ||
35500b57cec5SDimitry Andric          signal == eBroadcastInternalStateControlPause ||
35510b57cec5SDimitry Andric          signal == eBroadcastInternalStateControlResume);
35520b57cec5SDimitry Andric 
35539dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
35540b57cec5SDimitry Andric 
35550b57cec5SDimitry Andric   // Signal the private state thread
35560b57cec5SDimitry Andric   if (m_private_state_thread.IsJoinable()) {
35570b57cec5SDimitry Andric     // Broadcast the event.
35580b57cec5SDimitry Andric     // It is important to do this outside of the if below, because it's
35590b57cec5SDimitry Andric     // possible that the thread state is invalid but that the thread is waiting
35600b57cec5SDimitry Andric     // on a control event instead of simply being on its way out (this should
35610b57cec5SDimitry Andric     // not happen, but it apparently can).
35629dba64beSDimitry Andric     LLDB_LOGF(log, "Sending control event of type: %d.", signal);
35630b57cec5SDimitry Andric     std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
35640b57cec5SDimitry Andric     m_private_state_control_broadcaster.BroadcastEvent(signal,
35650b57cec5SDimitry Andric                                                        event_receipt_sp);
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric     // Wait for the event receipt or for the private state thread to exit
35680b57cec5SDimitry Andric     bool receipt_received = false;
35690b57cec5SDimitry Andric     if (PrivateStateThreadIsValid()) {
35700b57cec5SDimitry Andric       while (!receipt_received) {
35710b57cec5SDimitry Andric         // Check for a receipt for n seconds and then check if the private
35720b57cec5SDimitry Andric         // state thread is still around.
35730b57cec5SDimitry Andric         receipt_received =
35740b57cec5SDimitry Andric           event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
35750b57cec5SDimitry Andric         if (!receipt_received) {
35760b57cec5SDimitry Andric           // Check if the private state thread is still around. If it isn't
35770b57cec5SDimitry Andric           // then we are done waiting
35780b57cec5SDimitry Andric           if (!PrivateStateThreadIsValid())
35790b57cec5SDimitry Andric             break; // Private state thread exited or is exiting, we are done
35800b57cec5SDimitry Andric         }
35810b57cec5SDimitry Andric       }
35820b57cec5SDimitry Andric     }
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric     if (signal == eBroadcastInternalStateControlStop) {
35850b57cec5SDimitry Andric       thread_result_t result = {};
35860b57cec5SDimitry Andric       m_private_state_thread.Join(&result);
35870b57cec5SDimitry Andric       m_private_state_thread.Reset();
35880b57cec5SDimitry Andric     }
35890b57cec5SDimitry Andric   } else {
35909dba64beSDimitry Andric     LLDB_LOGF(
35919dba64beSDimitry Andric         log,
35920b57cec5SDimitry Andric         "Private state thread already dead, no need to signal it to stop.");
35930b57cec5SDimitry Andric   }
35940b57cec5SDimitry Andric }
35950b57cec5SDimitry Andric 
SendAsyncInterrupt()35960b57cec5SDimitry Andric void Process::SendAsyncInterrupt() {
35970b57cec5SDimitry Andric   if (PrivateStateThreadIsValid())
35980b57cec5SDimitry Andric     m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
35990b57cec5SDimitry Andric                                                nullptr);
36000b57cec5SDimitry Andric   else
36010b57cec5SDimitry Andric     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
36020b57cec5SDimitry Andric }
36030b57cec5SDimitry Andric 
HandlePrivateEvent(EventSP & event_sp)36040b57cec5SDimitry Andric void Process::HandlePrivateEvent(EventSP &event_sp) {
36050b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
36060b57cec5SDimitry Andric   m_resume_requested = false;
36070b57cec5SDimitry Andric 
36080b57cec5SDimitry Andric   const StateType new_state =
36090b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric   // First check to see if anybody wants a shot at this event:
36120b57cec5SDimitry Andric   if (m_next_event_action_up) {
36130b57cec5SDimitry Andric     NextEventAction::EventActionResult action_result =
36140b57cec5SDimitry Andric         m_next_event_action_up->PerformAction(event_sp);
36159dba64beSDimitry Andric     LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
36160b57cec5SDimitry Andric 
36170b57cec5SDimitry Andric     switch (action_result) {
36180b57cec5SDimitry Andric     case NextEventAction::eEventActionSuccess:
36190b57cec5SDimitry Andric       SetNextEventAction(nullptr);
36200b57cec5SDimitry Andric       break;
36210b57cec5SDimitry Andric 
36220b57cec5SDimitry Andric     case NextEventAction::eEventActionRetry:
36230b57cec5SDimitry Andric       break;
36240b57cec5SDimitry Andric 
36250b57cec5SDimitry Andric     case NextEventAction::eEventActionExit:
36260b57cec5SDimitry Andric       // Handle Exiting Here.  If we already got an exited event, we should
36270b57cec5SDimitry Andric       // just propagate it.  Otherwise, swallow this event, and set our state
36280b57cec5SDimitry Andric       // to exit so the next event will kill us.
36290b57cec5SDimitry Andric       if (new_state != eStateExited) {
36300b57cec5SDimitry Andric         // FIXME: should cons up an exited event, and discard this one.
36310b57cec5SDimitry Andric         SetExitStatus(0, m_next_event_action_up->GetExitString());
36320b57cec5SDimitry Andric         SetNextEventAction(nullptr);
36330b57cec5SDimitry Andric         return;
36340b57cec5SDimitry Andric       }
36350b57cec5SDimitry Andric       SetNextEventAction(nullptr);
36360b57cec5SDimitry Andric       break;
36370b57cec5SDimitry Andric     }
36380b57cec5SDimitry Andric   }
36390b57cec5SDimitry Andric 
36400b57cec5SDimitry Andric   // See if we should broadcast this state to external clients?
36410b57cec5SDimitry Andric   const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   if (should_broadcast) {
36440b57cec5SDimitry Andric     const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
36450b57cec5SDimitry Andric     if (log) {
36469dba64beSDimitry Andric       LLDB_LOGF(log,
36479dba64beSDimitry Andric                 "Process::%s (pid = %" PRIu64
36480b57cec5SDimitry Andric                 ") broadcasting new state %s (old state %s) to %s",
36490b57cec5SDimitry Andric                 __FUNCTION__, GetID(), StateAsCString(new_state),
36500b57cec5SDimitry Andric                 StateAsCString(GetState()),
36510b57cec5SDimitry Andric                 is_hijacked ? "hijacked" : "public");
36520b57cec5SDimitry Andric     }
36530b57cec5SDimitry Andric     Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
36540b57cec5SDimitry Andric     if (StateIsRunningState(new_state)) {
36550b57cec5SDimitry Andric       // Only push the input handler if we aren't fowarding events, as this
36560b57cec5SDimitry Andric       // means the curses GUI is in use... Or don't push it if we are launching
36570b57cec5SDimitry Andric       // since it will come up stopped.
36580b57cec5SDimitry Andric       if (!GetTarget().GetDebugger().IsForwardingEvents() &&
36590b57cec5SDimitry Andric           new_state != eStateLaunching && new_state != eStateAttaching) {
36600b57cec5SDimitry Andric         PushProcessIOHandler();
36610b57cec5SDimitry Andric         m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
36620b57cec5SDimitry Andric                                   eBroadcastAlways);
36639dba64beSDimitry Andric         LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
36640b57cec5SDimitry Andric                   __FUNCTION__, m_iohandler_sync.GetValue());
36650b57cec5SDimitry Andric       }
36660b57cec5SDimitry Andric     } else if (StateIsStoppedState(new_state, false)) {
36670b57cec5SDimitry Andric       if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
36680b57cec5SDimitry Andric         // If the lldb_private::Debugger is handling the events, we don't want
36690b57cec5SDimitry Andric         // to pop the process IOHandler here, we want to do it when we receive
36700b57cec5SDimitry Andric         // the stopped event so we can carefully control when the process
36710b57cec5SDimitry Andric         // IOHandler is popped because when we stop we want to display some
36720b57cec5SDimitry Andric         // text stating how and why we stopped, then maybe some
36730b57cec5SDimitry Andric         // process/thread/frame info, and then we want the "(lldb) " prompt to
36740b57cec5SDimitry Andric         // show up. If we pop the process IOHandler here, then we will cause
36750b57cec5SDimitry Andric         // the command interpreter to become the top IOHandler after the
36760b57cec5SDimitry Andric         // process pops off and it will update its prompt right away... See the
36770b57cec5SDimitry Andric         // Debugger.cpp file where it calls the function as
36780b57cec5SDimitry Andric         // "process_sp->PopProcessIOHandler()" to see where I am talking about.
36790b57cec5SDimitry Andric         // Otherwise we end up getting overlapping "(lldb) " prompts and
36800b57cec5SDimitry Andric         // garbled output.
36810b57cec5SDimitry Andric         //
36820b57cec5SDimitry Andric         // If we aren't handling the events in the debugger (which is indicated
36830b57cec5SDimitry Andric         // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
36840b57cec5SDimitry Andric         // we are hijacked, then we always pop the process IO handler manually.
36850b57cec5SDimitry Andric         // Hijacking happens when the internal process state thread is running
36860b57cec5SDimitry Andric         // thread plans, or when commands want to run in synchronous mode and
36870b57cec5SDimitry Andric         // they call "process->WaitForProcessToStop()". An example of something
36880b57cec5SDimitry Andric         // that will hijack the events is a simple expression:
36890b57cec5SDimitry Andric         //
36900b57cec5SDimitry Andric         //  (lldb) expr (int)puts("hello")
36910b57cec5SDimitry Andric         //
36920b57cec5SDimitry Andric         // This will cause the internal process state thread to resume and halt
36930b57cec5SDimitry Andric         // the process (and _it_ will hijack the eBroadcastBitStateChanged
36940b57cec5SDimitry Andric         // events) and we do need the IO handler to be pushed and popped
36950b57cec5SDimitry Andric         // correctly.
36960b57cec5SDimitry Andric 
36970b57cec5SDimitry Andric         if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
36980b57cec5SDimitry Andric           PopProcessIOHandler();
36990b57cec5SDimitry Andric       }
37000b57cec5SDimitry Andric     }
37010b57cec5SDimitry Andric 
37020b57cec5SDimitry Andric     BroadcastEvent(event_sp);
37030b57cec5SDimitry Andric   } else {
37040b57cec5SDimitry Andric     if (log) {
37059dba64beSDimitry Andric       LLDB_LOGF(
37069dba64beSDimitry Andric           log,
37070b57cec5SDimitry Andric           "Process::%s (pid = %" PRIu64
37080b57cec5SDimitry Andric           ") suppressing state %s (old state %s): should_broadcast == false",
37090b57cec5SDimitry Andric           __FUNCTION__, GetID(), StateAsCString(new_state),
37100b57cec5SDimitry Andric           StateAsCString(GetState()));
37110b57cec5SDimitry Andric     }
37120b57cec5SDimitry Andric   }
37130b57cec5SDimitry Andric }
37140b57cec5SDimitry Andric 
HaltPrivate()37150b57cec5SDimitry Andric Status Process::HaltPrivate() {
37160b57cec5SDimitry Andric   EventSP event_sp;
37170b57cec5SDimitry Andric   Status error(WillHalt());
37180b57cec5SDimitry Andric   if (error.Fail())
37190b57cec5SDimitry Andric     return error;
37200b57cec5SDimitry Andric 
37210b57cec5SDimitry Andric   // Ask the process subclass to actually halt our process
37220b57cec5SDimitry Andric   bool caused_stop;
37230b57cec5SDimitry Andric   error = DoHalt(caused_stop);
37240b57cec5SDimitry Andric 
37250b57cec5SDimitry Andric   DidHalt();
37260b57cec5SDimitry Andric   return error;
37270b57cec5SDimitry Andric }
37280b57cec5SDimitry Andric 
PrivateStateThread(void * arg)37290b57cec5SDimitry Andric thread_result_t Process::PrivateStateThread(void *arg) {
37300b57cec5SDimitry Andric   std::unique_ptr<PrivateStateThreadArgs> args_up(
37310b57cec5SDimitry Andric       static_cast<PrivateStateThreadArgs *>(arg));
37320b57cec5SDimitry Andric   thread_result_t result =
37330b57cec5SDimitry Andric       args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
37340b57cec5SDimitry Andric   return result;
37350b57cec5SDimitry Andric }
37360b57cec5SDimitry Andric 
RunPrivateStateThread(bool is_secondary_thread)37370b57cec5SDimitry Andric thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
37380b57cec5SDimitry Andric   bool control_only = true;
37390b57cec5SDimitry Andric 
37400b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
37419dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
37420b57cec5SDimitry Andric             __FUNCTION__, static_cast<void *>(this), GetID());
37430b57cec5SDimitry Andric 
37440b57cec5SDimitry Andric   bool exit_now = false;
37450b57cec5SDimitry Andric   bool interrupt_requested = false;
37460b57cec5SDimitry Andric   while (!exit_now) {
37470b57cec5SDimitry Andric     EventSP event_sp;
37480b57cec5SDimitry Andric     GetEventsPrivate(event_sp, llvm::None, control_only);
37490b57cec5SDimitry Andric     if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
37509dba64beSDimitry Andric       LLDB_LOGF(log,
37519dba64beSDimitry Andric                 "Process::%s (arg = %p, pid = %" PRIu64
37520b57cec5SDimitry Andric                 ") got a control event: %d",
37530b57cec5SDimitry Andric                 __FUNCTION__, static_cast<void *>(this), GetID(),
37540b57cec5SDimitry Andric                 event_sp->GetType());
37550b57cec5SDimitry Andric 
37560b57cec5SDimitry Andric       switch (event_sp->GetType()) {
37570b57cec5SDimitry Andric       case eBroadcastInternalStateControlStop:
37580b57cec5SDimitry Andric         exit_now = true;
37590b57cec5SDimitry Andric         break; // doing any internal state management below
37600b57cec5SDimitry Andric 
37610b57cec5SDimitry Andric       case eBroadcastInternalStateControlPause:
37620b57cec5SDimitry Andric         control_only = true;
37630b57cec5SDimitry Andric         break;
37640b57cec5SDimitry Andric 
37650b57cec5SDimitry Andric       case eBroadcastInternalStateControlResume:
37660b57cec5SDimitry Andric         control_only = false;
37670b57cec5SDimitry Andric         break;
37680b57cec5SDimitry Andric       }
37690b57cec5SDimitry Andric 
37700b57cec5SDimitry Andric       continue;
37710b57cec5SDimitry Andric     } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
37720b57cec5SDimitry Andric       if (m_public_state.GetValue() == eStateAttaching) {
37739dba64beSDimitry Andric         LLDB_LOGF(log,
37749dba64beSDimitry Andric                   "Process::%s (arg = %p, pid = %" PRIu64
37750b57cec5SDimitry Andric                   ") woke up with an interrupt while attaching - "
37760b57cec5SDimitry Andric                   "forwarding interrupt.",
37770b57cec5SDimitry Andric                   __FUNCTION__, static_cast<void *>(this), GetID());
37780b57cec5SDimitry Andric         BroadcastEvent(eBroadcastBitInterrupt, nullptr);
37790b57cec5SDimitry Andric       } else if (StateIsRunningState(m_last_broadcast_state)) {
37809dba64beSDimitry Andric         LLDB_LOGF(log,
37819dba64beSDimitry Andric                   "Process::%s (arg = %p, pid = %" PRIu64
37820b57cec5SDimitry Andric                   ") woke up with an interrupt - Halting.",
37830b57cec5SDimitry Andric                   __FUNCTION__, static_cast<void *>(this), GetID());
37840b57cec5SDimitry Andric         Status error = HaltPrivate();
37850b57cec5SDimitry Andric         if (error.Fail() && log)
37869dba64beSDimitry Andric           LLDB_LOGF(log,
37879dba64beSDimitry Andric                     "Process::%s (arg = %p, pid = %" PRIu64
37880b57cec5SDimitry Andric                     ") failed to halt the process: %s",
37890b57cec5SDimitry Andric                     __FUNCTION__, static_cast<void *>(this), GetID(),
37900b57cec5SDimitry Andric                     error.AsCString());
37910b57cec5SDimitry Andric         // Halt should generate a stopped event. Make a note of the fact that
37920b57cec5SDimitry Andric         // we were doing the interrupt, so we can set the interrupted flag
37930b57cec5SDimitry Andric         // after we receive the event. We deliberately set this to true even if
37940b57cec5SDimitry Andric         // HaltPrivate failed, so that we can interrupt on the next natural
37950b57cec5SDimitry Andric         // stop.
37960b57cec5SDimitry Andric         interrupt_requested = true;
37970b57cec5SDimitry Andric       } else {
37980b57cec5SDimitry Andric         // This can happen when someone (e.g. Process::Halt) sees that we are
37990b57cec5SDimitry Andric         // running and sends an interrupt request, but the process actually
38000b57cec5SDimitry Andric         // stops before we receive it. In that case, we can just ignore the
38010b57cec5SDimitry Andric         // request. We use m_last_broadcast_state, because the Stopped event
38020b57cec5SDimitry Andric         // may not have been popped of the event queue yet, which is when the
38030b57cec5SDimitry Andric         // public state gets updated.
38049dba64beSDimitry Andric         LLDB_LOGF(log,
38050b57cec5SDimitry Andric                   "Process::%s ignoring interrupt as we have already stopped.",
38060b57cec5SDimitry Andric                   __FUNCTION__);
38070b57cec5SDimitry Andric       }
38080b57cec5SDimitry Andric       continue;
38090b57cec5SDimitry Andric     }
38100b57cec5SDimitry Andric 
38110b57cec5SDimitry Andric     const StateType internal_state =
38120b57cec5SDimitry Andric         Process::ProcessEventData::GetStateFromEvent(event_sp.get());
38130b57cec5SDimitry Andric 
38140b57cec5SDimitry Andric     if (internal_state != eStateInvalid) {
38150b57cec5SDimitry Andric       if (m_clear_thread_plans_on_stop &&
38160b57cec5SDimitry Andric           StateIsStoppedState(internal_state, true)) {
38170b57cec5SDimitry Andric         m_clear_thread_plans_on_stop = false;
38180b57cec5SDimitry Andric         m_thread_list.DiscardThreadPlans();
38190b57cec5SDimitry Andric       }
38200b57cec5SDimitry Andric 
38210b57cec5SDimitry Andric       if (interrupt_requested) {
38220b57cec5SDimitry Andric         if (StateIsStoppedState(internal_state, true)) {
38230b57cec5SDimitry Andric           // We requested the interrupt, so mark this as such in the stop event
38240b57cec5SDimitry Andric           // so clients can tell an interrupted process from a natural stop
38250b57cec5SDimitry Andric           ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
38260b57cec5SDimitry Andric           interrupt_requested = false;
38270b57cec5SDimitry Andric         } else if (log) {
38289dba64beSDimitry Andric           LLDB_LOGF(log,
38299dba64beSDimitry Andric                     "Process::%s interrupt_requested, but a non-stopped "
38300b57cec5SDimitry Andric                     "state '%s' received.",
38310b57cec5SDimitry Andric                     __FUNCTION__, StateAsCString(internal_state));
38320b57cec5SDimitry Andric         }
38330b57cec5SDimitry Andric       }
38340b57cec5SDimitry Andric 
38350b57cec5SDimitry Andric       HandlePrivateEvent(event_sp);
38360b57cec5SDimitry Andric     }
38370b57cec5SDimitry Andric 
38380b57cec5SDimitry Andric     if (internal_state == eStateInvalid || internal_state == eStateExited ||
38390b57cec5SDimitry Andric         internal_state == eStateDetached) {
38409dba64beSDimitry Andric       LLDB_LOGF(log,
38419dba64beSDimitry Andric                 "Process::%s (arg = %p, pid = %" PRIu64
38420b57cec5SDimitry Andric                 ") about to exit with internal state %s...",
38430b57cec5SDimitry Andric                 __FUNCTION__, static_cast<void *>(this), GetID(),
38440b57cec5SDimitry Andric                 StateAsCString(internal_state));
38450b57cec5SDimitry Andric 
38460b57cec5SDimitry Andric       break;
38470b57cec5SDimitry Andric     }
38480b57cec5SDimitry Andric   }
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric   // Verify log is still enabled before attempting to write to it...
38519dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
38520b57cec5SDimitry Andric             __FUNCTION__, static_cast<void *>(this), GetID());
38530b57cec5SDimitry Andric 
38540b57cec5SDimitry Andric   // If we are a secondary thread, then the primary thread we are working for
38550b57cec5SDimitry Andric   // will have already acquired the public_run_lock, and isn't done with what
38560b57cec5SDimitry Andric   // it was doing yet, so don't try to change it on the way out.
38570b57cec5SDimitry Andric   if (!is_secondary_thread)
38580b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
38590b57cec5SDimitry Andric   return {};
38600b57cec5SDimitry Andric }
38610b57cec5SDimitry Andric 
38620b57cec5SDimitry Andric // Process Event Data
38630b57cec5SDimitry Andric 
ProcessEventData()3864*5f7ddb14SDimitry Andric Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp() {}
38650b57cec5SDimitry Andric 
ProcessEventData(const ProcessSP & process_sp,StateType state)38660b57cec5SDimitry Andric Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
38670b57cec5SDimitry Andric                                             StateType state)
38680b57cec5SDimitry Andric     : EventData(), m_process_wp(), m_state(state), m_restarted(false),
38690b57cec5SDimitry Andric       m_update_state(0), m_interrupted(false) {
38700b57cec5SDimitry Andric   if (process_sp)
38710b57cec5SDimitry Andric     m_process_wp = process_sp;
38720b57cec5SDimitry Andric }
38730b57cec5SDimitry Andric 
38740b57cec5SDimitry Andric Process::ProcessEventData::~ProcessEventData() = default;
38750b57cec5SDimitry Andric 
GetFlavorString()38760b57cec5SDimitry Andric ConstString Process::ProcessEventData::GetFlavorString() {
38770b57cec5SDimitry Andric   static ConstString g_flavor("Process::ProcessEventData");
38780b57cec5SDimitry Andric   return g_flavor;
38790b57cec5SDimitry Andric }
38800b57cec5SDimitry Andric 
GetFlavor() const38810b57cec5SDimitry Andric ConstString Process::ProcessEventData::GetFlavor() const {
38820b57cec5SDimitry Andric   return ProcessEventData::GetFlavorString();
38830b57cec5SDimitry Andric }
38840b57cec5SDimitry Andric 
ShouldStop(Event * event_ptr,bool & found_valid_stopinfo)38855ffd83dbSDimitry Andric bool Process::ProcessEventData::ShouldStop(Event *event_ptr,
38865ffd83dbSDimitry Andric                                            bool &found_valid_stopinfo) {
38875ffd83dbSDimitry Andric   found_valid_stopinfo = false;
38885ffd83dbSDimitry Andric 
38895ffd83dbSDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
38905ffd83dbSDimitry Andric   if (!process_sp)
38915ffd83dbSDimitry Andric     return false;
38925ffd83dbSDimitry Andric 
38935ffd83dbSDimitry Andric   ThreadList &curr_thread_list = process_sp->GetThreadList();
38945ffd83dbSDimitry Andric   uint32_t num_threads = curr_thread_list.GetSize();
38955ffd83dbSDimitry Andric   uint32_t idx;
38965ffd83dbSDimitry Andric 
38975ffd83dbSDimitry Andric   // The actions might change one of the thread's stop_info's opinions about
38985ffd83dbSDimitry Andric   // whether we should stop the process, so we need to query that as we go.
38995ffd83dbSDimitry Andric 
39005ffd83dbSDimitry Andric   // One other complication here, is that we try to catch any case where the
39015ffd83dbSDimitry Andric   // target has run (except for expressions) and immediately exit, but if we
39025ffd83dbSDimitry Andric   // get that wrong (which is possible) then the thread list might have
39035ffd83dbSDimitry Andric   // changed, and that would cause our iteration here to crash.  We could
39045ffd83dbSDimitry Andric   // make a copy of the thread list, but we'd really like to also know if it
39055ffd83dbSDimitry Andric   // has changed at all, so we make up a vector of the thread ID's and check
39065ffd83dbSDimitry Andric   // what we get back against this list & bag out if anything differs.
39075ffd83dbSDimitry Andric   ThreadList not_suspended_thread_list(process_sp.get());
39085ffd83dbSDimitry Andric   std::vector<uint32_t> thread_index_array(num_threads);
39095ffd83dbSDimitry Andric   uint32_t not_suspended_idx = 0;
39105ffd83dbSDimitry Andric   for (idx = 0; idx < num_threads; ++idx) {
39115ffd83dbSDimitry Andric     lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
39125ffd83dbSDimitry Andric 
39135ffd83dbSDimitry Andric     /*
39145ffd83dbSDimitry Andric      Filter out all suspended threads, they could not be the reason
39155ffd83dbSDimitry Andric      of stop and no need to perform any actions on them.
39165ffd83dbSDimitry Andric      */
39175ffd83dbSDimitry Andric     if (thread_sp->GetResumeState() != eStateSuspended) {
39185ffd83dbSDimitry Andric       not_suspended_thread_list.AddThread(thread_sp);
39195ffd83dbSDimitry Andric       thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
39205ffd83dbSDimitry Andric       not_suspended_idx++;
39215ffd83dbSDimitry Andric     }
39225ffd83dbSDimitry Andric   }
39235ffd83dbSDimitry Andric 
39245ffd83dbSDimitry Andric   // Use this to track whether we should continue from here.  We will only
39255ffd83dbSDimitry Andric   // continue the target running if no thread says we should stop.  Of course
39265ffd83dbSDimitry Andric   // if some thread's PerformAction actually sets the target running, then it
39275ffd83dbSDimitry Andric   // doesn't matter what the other threads say...
39285ffd83dbSDimitry Andric 
39295ffd83dbSDimitry Andric   bool still_should_stop = false;
39305ffd83dbSDimitry Andric 
39315ffd83dbSDimitry Andric   // Sometimes - for instance if we have a bug in the stub we are talking to,
39325ffd83dbSDimitry Andric   // we stop but no thread has a valid stop reason.  In that case we should
39335ffd83dbSDimitry Andric   // just stop, because we have no way of telling what the right thing to do
39345ffd83dbSDimitry Andric   // is, and it's better to let the user decide than continue behind their
39355ffd83dbSDimitry Andric   // backs.
39365ffd83dbSDimitry Andric 
39375ffd83dbSDimitry Andric   for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
39385ffd83dbSDimitry Andric     curr_thread_list = process_sp->GetThreadList();
39395ffd83dbSDimitry Andric     if (curr_thread_list.GetSize() != num_threads) {
39405ffd83dbSDimitry Andric       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
39415ffd83dbSDimitry Andric                                                       LIBLLDB_LOG_PROCESS));
39425ffd83dbSDimitry Andric       LLDB_LOGF(
39435ffd83dbSDimitry Andric           log,
39445ffd83dbSDimitry Andric           "Number of threads changed from %u to %u while processing event.",
39455ffd83dbSDimitry Andric           num_threads, curr_thread_list.GetSize());
39465ffd83dbSDimitry Andric       break;
39475ffd83dbSDimitry Andric     }
39485ffd83dbSDimitry Andric 
39495ffd83dbSDimitry Andric     lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
39505ffd83dbSDimitry Andric 
39515ffd83dbSDimitry Andric     if (thread_sp->GetIndexID() != thread_index_array[idx]) {
39525ffd83dbSDimitry Andric       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
39535ffd83dbSDimitry Andric                                                       LIBLLDB_LOG_PROCESS));
39545ffd83dbSDimitry Andric       LLDB_LOGF(log,
39555ffd83dbSDimitry Andric                 "The thread at position %u changed from %u to %u while "
39565ffd83dbSDimitry Andric                 "processing event.",
39575ffd83dbSDimitry Andric                 idx, thread_index_array[idx], thread_sp->GetIndexID());
39585ffd83dbSDimitry Andric       break;
39595ffd83dbSDimitry Andric     }
39605ffd83dbSDimitry Andric 
39615ffd83dbSDimitry Andric     StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
39625ffd83dbSDimitry Andric     if (stop_info_sp && stop_info_sp->IsValid()) {
39635ffd83dbSDimitry Andric       found_valid_stopinfo = true;
39645ffd83dbSDimitry Andric       bool this_thread_wants_to_stop;
39655ffd83dbSDimitry Andric       if (stop_info_sp->GetOverrideShouldStop()) {
39665ffd83dbSDimitry Andric         this_thread_wants_to_stop =
39675ffd83dbSDimitry Andric             stop_info_sp->GetOverriddenShouldStopValue();
39685ffd83dbSDimitry Andric       } else {
39695ffd83dbSDimitry Andric         stop_info_sp->PerformAction(event_ptr);
39705ffd83dbSDimitry Andric         // The stop action might restart the target.  If it does, then we
39715ffd83dbSDimitry Andric         // want to mark that in the event so that whoever is receiving it
39725ffd83dbSDimitry Andric         // will know to wait for the running event and reflect that state
39735ffd83dbSDimitry Andric         // appropriately. We also need to stop processing actions, since they
39745ffd83dbSDimitry Andric         // aren't expecting the target to be running.
39755ffd83dbSDimitry Andric 
39765ffd83dbSDimitry Andric         // FIXME: we might have run.
39775ffd83dbSDimitry Andric         if (stop_info_sp->HasTargetRunSinceMe()) {
39785ffd83dbSDimitry Andric           SetRestarted(true);
39795ffd83dbSDimitry Andric           break;
39805ffd83dbSDimitry Andric         }
39815ffd83dbSDimitry Andric 
39825ffd83dbSDimitry Andric         this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
39835ffd83dbSDimitry Andric       }
39845ffd83dbSDimitry Andric 
39855ffd83dbSDimitry Andric       if (!still_should_stop)
39865ffd83dbSDimitry Andric         still_should_stop = this_thread_wants_to_stop;
39875ffd83dbSDimitry Andric     }
39885ffd83dbSDimitry Andric   }
39895ffd83dbSDimitry Andric 
39905ffd83dbSDimitry Andric   return still_should_stop;
39915ffd83dbSDimitry Andric }
39925ffd83dbSDimitry Andric 
DoOnRemoval(Event * event_ptr)39930b57cec5SDimitry Andric void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
39940b57cec5SDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
39950b57cec5SDimitry Andric 
39960b57cec5SDimitry Andric   if (!process_sp)
39970b57cec5SDimitry Andric     return;
39980b57cec5SDimitry Andric 
39990b57cec5SDimitry Andric   // This function gets called twice for each event, once when the event gets
40000b57cec5SDimitry Andric   // pulled off of the private process event queue, and then any number of
40010b57cec5SDimitry Andric   // times, first when it gets pulled off of the public event queue, then other
40020b57cec5SDimitry Andric   // times when we're pretending that this is where we stopped at the end of
40030b57cec5SDimitry Andric   // expression evaluation.  m_update_state is used to distinguish these three
40040b57cec5SDimitry Andric   // cases; it is 0 when we're just pulling it off for private handling, and >
40050b57cec5SDimitry Andric   // 1 for expression evaluation, and we don't want to do the breakpoint
40060b57cec5SDimitry Andric   // command handling then.
40070b57cec5SDimitry Andric   if (m_update_state != 1)
40080b57cec5SDimitry Andric     return;
40090b57cec5SDimitry Andric 
40100b57cec5SDimitry Andric   process_sp->SetPublicState(
40110b57cec5SDimitry Andric       m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
40120b57cec5SDimitry Andric 
40130b57cec5SDimitry Andric   if (m_state == eStateStopped && !m_restarted) {
40140b57cec5SDimitry Andric     // Let process subclasses know we are about to do a public stop and do
40150b57cec5SDimitry Andric     // anything they might need to in order to speed up register and memory
40160b57cec5SDimitry Andric     // accesses.
40170b57cec5SDimitry Andric     process_sp->WillPublicStop();
40180b57cec5SDimitry Andric   }
40190b57cec5SDimitry Andric 
40200b57cec5SDimitry Andric   // If this is a halt event, even if the halt stopped with some reason other
40210b57cec5SDimitry Andric   // than a plain interrupt (e.g. we had already stopped for a breakpoint when
40220b57cec5SDimitry Andric   // the halt request came through) don't do the StopInfo actions, as they may
40230b57cec5SDimitry Andric   // end up restarting the process.
40240b57cec5SDimitry Andric   if (m_interrupted)
40250b57cec5SDimitry Andric     return;
40260b57cec5SDimitry Andric 
40275ffd83dbSDimitry Andric   // If we're not stopped or have restarted, then skip the StopInfo actions:
40285ffd83dbSDimitry Andric   if (m_state != eStateStopped || m_restarted) {
40295ffd83dbSDimitry Andric     return;
40305ffd83dbSDimitry Andric   }
40310b57cec5SDimitry Andric 
40320b57cec5SDimitry Andric   bool does_anybody_have_an_opinion = false;
40335ffd83dbSDimitry Andric   bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
40340b57cec5SDimitry Andric 
40355ffd83dbSDimitry Andric   if (GetRestarted()) {
40365ffd83dbSDimitry Andric     return;
40370b57cec5SDimitry Andric   }
40380b57cec5SDimitry Andric 
40390b57cec5SDimitry Andric   if (!still_should_stop && does_anybody_have_an_opinion) {
40400b57cec5SDimitry Andric     // We've been asked to continue, so do that here.
40410b57cec5SDimitry Andric     SetRestarted(true);
40420b57cec5SDimitry Andric     // Use the public resume method here, since this is just extending a
40430b57cec5SDimitry Andric     // public resume.
40440b57cec5SDimitry Andric     process_sp->PrivateResume();
40450b57cec5SDimitry Andric   } else {
40465ffd83dbSDimitry Andric     bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
40470b57cec5SDimitry Andric                     !process_sp->StateChangedIsHijackedForSynchronousResume();
40480b57cec5SDimitry Andric 
40490b57cec5SDimitry Andric     if (!hijacked) {
40500b57cec5SDimitry Andric       // If we didn't restart, run the Stop Hooks here.
40510b57cec5SDimitry Andric       // Don't do that if state changed events aren't hooked up to the
40520b57cec5SDimitry Andric       // public (or SyncResume) broadcasters.  StopHooks are just for
40530b57cec5SDimitry Andric       // real public stops.  They might also restart the target,
40540b57cec5SDimitry Andric       // so watch for that.
4055af732203SDimitry Andric       if (process_sp->GetTarget().RunStopHooks())
40560b57cec5SDimitry Andric         SetRestarted(true);
40570b57cec5SDimitry Andric     }
40580b57cec5SDimitry Andric   }
40590b57cec5SDimitry Andric }
40600b57cec5SDimitry Andric 
Dump(Stream * s) const40610b57cec5SDimitry Andric void Process::ProcessEventData::Dump(Stream *s) const {
40620b57cec5SDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
40630b57cec5SDimitry Andric 
40640b57cec5SDimitry Andric   if (process_sp)
40650b57cec5SDimitry Andric     s->Printf(" process = %p (pid = %" PRIu64 "), ",
40660b57cec5SDimitry Andric               static_cast<void *>(process_sp.get()), process_sp->GetID());
40670b57cec5SDimitry Andric   else
40680b57cec5SDimitry Andric     s->PutCString(" process = NULL, ");
40690b57cec5SDimitry Andric 
40700b57cec5SDimitry Andric   s->Printf("state = %s", StateAsCString(GetState()));
40710b57cec5SDimitry Andric }
40720b57cec5SDimitry Andric 
40730b57cec5SDimitry Andric const Process::ProcessEventData *
GetEventDataFromEvent(const Event * event_ptr)40740b57cec5SDimitry Andric Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
40750b57cec5SDimitry Andric   if (event_ptr) {
40760b57cec5SDimitry Andric     const EventData *event_data = event_ptr->GetData();
40770b57cec5SDimitry Andric     if (event_data &&
40780b57cec5SDimitry Andric         event_data->GetFlavor() == ProcessEventData::GetFlavorString())
40790b57cec5SDimitry Andric       return static_cast<const ProcessEventData *>(event_ptr->GetData());
40800b57cec5SDimitry Andric   }
40810b57cec5SDimitry Andric   return nullptr;
40820b57cec5SDimitry Andric }
40830b57cec5SDimitry Andric 
40840b57cec5SDimitry Andric ProcessSP
GetProcessFromEvent(const Event * event_ptr)40850b57cec5SDimitry Andric Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
40860b57cec5SDimitry Andric   ProcessSP process_sp;
40870b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
40880b57cec5SDimitry Andric   if (data)
40890b57cec5SDimitry Andric     process_sp = data->GetProcessSP();
40900b57cec5SDimitry Andric   return process_sp;
40910b57cec5SDimitry Andric }
40920b57cec5SDimitry Andric 
GetStateFromEvent(const Event * event_ptr)40930b57cec5SDimitry Andric StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
40940b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
40950b57cec5SDimitry Andric   if (data == nullptr)
40960b57cec5SDimitry Andric     return eStateInvalid;
40970b57cec5SDimitry Andric   else
40980b57cec5SDimitry Andric     return data->GetState();
40990b57cec5SDimitry Andric }
41000b57cec5SDimitry Andric 
GetRestartedFromEvent(const Event * event_ptr)41010b57cec5SDimitry Andric bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
41020b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
41030b57cec5SDimitry Andric   if (data == nullptr)
41040b57cec5SDimitry Andric     return false;
41050b57cec5SDimitry Andric   else
41060b57cec5SDimitry Andric     return data->GetRestarted();
41070b57cec5SDimitry Andric }
41080b57cec5SDimitry Andric 
SetRestartedInEvent(Event * event_ptr,bool new_value)41090b57cec5SDimitry Andric void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
41100b57cec5SDimitry Andric                                                     bool new_value) {
41110b57cec5SDimitry Andric   ProcessEventData *data =
41120b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41130b57cec5SDimitry Andric   if (data != nullptr)
41140b57cec5SDimitry Andric     data->SetRestarted(new_value);
41150b57cec5SDimitry Andric }
41160b57cec5SDimitry Andric 
41170b57cec5SDimitry Andric size_t
GetNumRestartedReasons(const Event * event_ptr)41180b57cec5SDimitry Andric Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
41190b57cec5SDimitry Andric   ProcessEventData *data =
41200b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41210b57cec5SDimitry Andric   if (data != nullptr)
41220b57cec5SDimitry Andric     return data->GetNumRestartedReasons();
41230b57cec5SDimitry Andric   else
41240b57cec5SDimitry Andric     return 0;
41250b57cec5SDimitry Andric }
41260b57cec5SDimitry Andric 
41270b57cec5SDimitry Andric const char *
GetRestartedReasonAtIndex(const Event * event_ptr,size_t idx)41280b57cec5SDimitry Andric Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
41290b57cec5SDimitry Andric                                                      size_t idx) {
41300b57cec5SDimitry Andric   ProcessEventData *data =
41310b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41320b57cec5SDimitry Andric   if (data != nullptr)
41330b57cec5SDimitry Andric     return data->GetRestartedReasonAtIndex(idx);
41340b57cec5SDimitry Andric   else
41350b57cec5SDimitry Andric     return nullptr;
41360b57cec5SDimitry Andric }
41370b57cec5SDimitry Andric 
AddRestartedReason(Event * event_ptr,const char * reason)41380b57cec5SDimitry Andric void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
41390b57cec5SDimitry Andric                                                    const char *reason) {
41400b57cec5SDimitry Andric   ProcessEventData *data =
41410b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41420b57cec5SDimitry Andric   if (data != nullptr)
41430b57cec5SDimitry Andric     data->AddRestartedReason(reason);
41440b57cec5SDimitry Andric }
41450b57cec5SDimitry Andric 
GetInterruptedFromEvent(const Event * event_ptr)41460b57cec5SDimitry Andric bool Process::ProcessEventData::GetInterruptedFromEvent(
41470b57cec5SDimitry Andric     const Event *event_ptr) {
41480b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
41490b57cec5SDimitry Andric   if (data == nullptr)
41500b57cec5SDimitry Andric     return false;
41510b57cec5SDimitry Andric   else
41520b57cec5SDimitry Andric     return data->GetInterrupted();
41530b57cec5SDimitry Andric }
41540b57cec5SDimitry Andric 
SetInterruptedInEvent(Event * event_ptr,bool new_value)41550b57cec5SDimitry Andric void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
41560b57cec5SDimitry Andric                                                       bool new_value) {
41570b57cec5SDimitry Andric   ProcessEventData *data =
41580b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41590b57cec5SDimitry Andric   if (data != nullptr)
41600b57cec5SDimitry Andric     data->SetInterrupted(new_value);
41610b57cec5SDimitry Andric }
41620b57cec5SDimitry Andric 
SetUpdateStateOnRemoval(Event * event_ptr)41630b57cec5SDimitry Andric bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
41640b57cec5SDimitry Andric   ProcessEventData *data =
41650b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41660b57cec5SDimitry Andric   if (data) {
41670b57cec5SDimitry Andric     data->SetUpdateStateOnRemoval();
41680b57cec5SDimitry Andric     return true;
41690b57cec5SDimitry Andric   }
41700b57cec5SDimitry Andric   return false;
41710b57cec5SDimitry Andric }
41720b57cec5SDimitry Andric 
CalculateTarget()41730b57cec5SDimitry Andric lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
41740b57cec5SDimitry Andric 
CalculateExecutionContext(ExecutionContext & exe_ctx)41750b57cec5SDimitry Andric void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
41760b57cec5SDimitry Andric   exe_ctx.SetTargetPtr(&GetTarget());
41770b57cec5SDimitry Andric   exe_ctx.SetProcessPtr(this);
41780b57cec5SDimitry Andric   exe_ctx.SetThreadPtr(nullptr);
41790b57cec5SDimitry Andric   exe_ctx.SetFramePtr(nullptr);
41800b57cec5SDimitry Andric }
41810b57cec5SDimitry Andric 
41820b57cec5SDimitry Andric // uint32_t
41830b57cec5SDimitry Andric // Process::ListProcessesMatchingName (const char *name, StringList &matches,
41840b57cec5SDimitry Andric // std::vector<lldb::pid_t> &pids)
41850b57cec5SDimitry Andric //{
41860b57cec5SDimitry Andric //    return 0;
41870b57cec5SDimitry Andric //}
41880b57cec5SDimitry Andric //
41890b57cec5SDimitry Andric // ArchSpec
41900b57cec5SDimitry Andric // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
41910b57cec5SDimitry Andric //{
41920b57cec5SDimitry Andric //    return Host::GetArchSpecForExistingProcess (pid);
41930b57cec5SDimitry Andric //}
41940b57cec5SDimitry Andric //
41950b57cec5SDimitry Andric // ArchSpec
41960b57cec5SDimitry Andric // Process::GetArchSpecForExistingProcess (const char *process_name)
41970b57cec5SDimitry Andric //{
41980b57cec5SDimitry Andric //    return Host::GetArchSpecForExistingProcess (process_name);
41990b57cec5SDimitry Andric //}
42000b57cec5SDimitry Andric 
AppendSTDOUT(const char * s,size_t len)42010b57cec5SDimitry Andric void Process::AppendSTDOUT(const char *s, size_t len) {
42020b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
42030b57cec5SDimitry Andric   m_stdout_data.append(s, len);
42040b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitSTDOUT,
42050b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
42060b57cec5SDimitry Andric }
42070b57cec5SDimitry Andric 
AppendSTDERR(const char * s,size_t len)42080b57cec5SDimitry Andric void Process::AppendSTDERR(const char *s, size_t len) {
42090b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
42100b57cec5SDimitry Andric   m_stderr_data.append(s, len);
42110b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitSTDERR,
42120b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
42130b57cec5SDimitry Andric }
42140b57cec5SDimitry Andric 
BroadcastAsyncProfileData(const std::string & one_profile_data)42150b57cec5SDimitry Andric void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
42160b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
42170b57cec5SDimitry Andric   m_profile_data.push_back(one_profile_data);
42180b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitProfileData,
42190b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
42200b57cec5SDimitry Andric }
42210b57cec5SDimitry Andric 
BroadcastStructuredData(const StructuredData::ObjectSP & object_sp,const StructuredDataPluginSP & plugin_sp)42220b57cec5SDimitry Andric void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
42230b57cec5SDimitry Andric                                       const StructuredDataPluginSP &plugin_sp) {
42240b57cec5SDimitry Andric   BroadcastEvent(
42250b57cec5SDimitry Andric       eBroadcastBitStructuredData,
42260b57cec5SDimitry Andric       new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
42270b57cec5SDimitry Andric }
42280b57cec5SDimitry Andric 
42290b57cec5SDimitry Andric StructuredDataPluginSP
GetStructuredDataPlugin(ConstString type_name) const42300b57cec5SDimitry Andric Process::GetStructuredDataPlugin(ConstString type_name) const {
42310b57cec5SDimitry Andric   auto find_it = m_structured_data_plugin_map.find(type_name);
42320b57cec5SDimitry Andric   if (find_it != m_structured_data_plugin_map.end())
42330b57cec5SDimitry Andric     return find_it->second;
42340b57cec5SDimitry Andric   else
42350b57cec5SDimitry Andric     return StructuredDataPluginSP();
42360b57cec5SDimitry Andric }
42370b57cec5SDimitry Andric 
GetAsyncProfileData(char * buf,size_t buf_size,Status & error)42380b57cec5SDimitry Andric size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
42390b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
42400b57cec5SDimitry Andric   if (m_profile_data.empty())
42410b57cec5SDimitry Andric     return 0;
42420b57cec5SDimitry Andric 
42430b57cec5SDimitry Andric   std::string &one_profile_data = m_profile_data.front();
42440b57cec5SDimitry Andric   size_t bytes_available = one_profile_data.size();
42450b57cec5SDimitry Andric   if (bytes_available > 0) {
42460b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
42479dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
42480b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
42490b57cec5SDimitry Andric     if (bytes_available > buf_size) {
42500b57cec5SDimitry Andric       memcpy(buf, one_profile_data.c_str(), buf_size);
42510b57cec5SDimitry Andric       one_profile_data.erase(0, buf_size);
42520b57cec5SDimitry Andric       bytes_available = buf_size;
42530b57cec5SDimitry Andric     } else {
42540b57cec5SDimitry Andric       memcpy(buf, one_profile_data.c_str(), bytes_available);
42550b57cec5SDimitry Andric       m_profile_data.erase(m_profile_data.begin());
42560b57cec5SDimitry Andric     }
42570b57cec5SDimitry Andric   }
42580b57cec5SDimitry Andric   return bytes_available;
42590b57cec5SDimitry Andric }
42600b57cec5SDimitry Andric 
42610b57cec5SDimitry Andric // Process STDIO
42620b57cec5SDimitry Andric 
GetSTDOUT(char * buf,size_t buf_size,Status & error)42630b57cec5SDimitry Andric size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
42640b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
42650b57cec5SDimitry Andric   size_t bytes_available = m_stdout_data.size();
42660b57cec5SDimitry Andric   if (bytes_available > 0) {
42670b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
42689dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
42690b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
42700b57cec5SDimitry Andric     if (bytes_available > buf_size) {
42710b57cec5SDimitry Andric       memcpy(buf, m_stdout_data.c_str(), buf_size);
42720b57cec5SDimitry Andric       m_stdout_data.erase(0, buf_size);
42730b57cec5SDimitry Andric       bytes_available = buf_size;
42740b57cec5SDimitry Andric     } else {
42750b57cec5SDimitry Andric       memcpy(buf, m_stdout_data.c_str(), bytes_available);
42760b57cec5SDimitry Andric       m_stdout_data.clear();
42770b57cec5SDimitry Andric     }
42780b57cec5SDimitry Andric   }
42790b57cec5SDimitry Andric   return bytes_available;
42800b57cec5SDimitry Andric }
42810b57cec5SDimitry Andric 
GetSTDERR(char * buf,size_t buf_size,Status & error)42820b57cec5SDimitry Andric size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
42830b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
42840b57cec5SDimitry Andric   size_t bytes_available = m_stderr_data.size();
42850b57cec5SDimitry Andric   if (bytes_available > 0) {
42860b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
42879dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
42880b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
42890b57cec5SDimitry Andric     if (bytes_available > buf_size) {
42900b57cec5SDimitry Andric       memcpy(buf, m_stderr_data.c_str(), buf_size);
42910b57cec5SDimitry Andric       m_stderr_data.erase(0, buf_size);
42920b57cec5SDimitry Andric       bytes_available = buf_size;
42930b57cec5SDimitry Andric     } else {
42940b57cec5SDimitry Andric       memcpy(buf, m_stderr_data.c_str(), bytes_available);
42950b57cec5SDimitry Andric       m_stderr_data.clear();
42960b57cec5SDimitry Andric     }
42970b57cec5SDimitry Andric   }
42980b57cec5SDimitry Andric   return bytes_available;
42990b57cec5SDimitry Andric }
43000b57cec5SDimitry Andric 
STDIOReadThreadBytesReceived(void * baton,const void * src,size_t src_len)43010b57cec5SDimitry Andric void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
43020b57cec5SDimitry Andric                                            size_t src_len) {
43030b57cec5SDimitry Andric   Process *process = (Process *)baton;
43040b57cec5SDimitry Andric   process->AppendSTDOUT(static_cast<const char *>(src), src_len);
43050b57cec5SDimitry Andric }
43060b57cec5SDimitry Andric 
43070b57cec5SDimitry Andric class IOHandlerProcessSTDIO : public IOHandler {
43080b57cec5SDimitry Andric public:
IOHandlerProcessSTDIO(Process * process,int write_fd)43090b57cec5SDimitry Andric   IOHandlerProcessSTDIO(Process *process, int write_fd)
43100b57cec5SDimitry Andric       : IOHandler(process->GetTarget().GetDebugger(),
43110b57cec5SDimitry Andric                   IOHandler::Type::ProcessIO),
43129dba64beSDimitry Andric         m_process(process),
43139dba64beSDimitry Andric         m_read_file(GetInputFD(), File::eOpenOptionRead, false),
43149dba64beSDimitry Andric         m_write_file(write_fd, File::eOpenOptionWrite, false) {
43150b57cec5SDimitry Andric     m_pipe.CreateNew(false);
43160b57cec5SDimitry Andric   }
43170b57cec5SDimitry Andric 
43180b57cec5SDimitry Andric   ~IOHandlerProcessSTDIO() override = default;
43190b57cec5SDimitry Andric 
43200b57cec5SDimitry Andric   // Each IOHandler gets to run until it is done. It should read data from the
43210b57cec5SDimitry Andric   // "in" and place output into "out" and "err and return when done.
Run()43220b57cec5SDimitry Andric   void Run() override {
43230b57cec5SDimitry Andric     if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
43240b57cec5SDimitry Andric         !m_pipe.CanRead() || !m_pipe.CanWrite()) {
43250b57cec5SDimitry Andric       SetIsDone(true);
43260b57cec5SDimitry Andric       return;
43270b57cec5SDimitry Andric     }
43280b57cec5SDimitry Andric 
43290b57cec5SDimitry Andric     SetIsDone(false);
43300b57cec5SDimitry Andric     const int read_fd = m_read_file.GetDescriptor();
43310b57cec5SDimitry Andric     TerminalState terminal_state;
43320b57cec5SDimitry Andric     terminal_state.Save(read_fd, false);
43330b57cec5SDimitry Andric     Terminal terminal(read_fd);
43340b57cec5SDimitry Andric     terminal.SetCanonical(false);
43350b57cec5SDimitry Andric     terminal.SetEcho(false);
43360b57cec5SDimitry Andric // FD_ZERO, FD_SET are not supported on windows
43370b57cec5SDimitry Andric #ifndef _WIN32
43380b57cec5SDimitry Andric     const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
43390b57cec5SDimitry Andric     m_is_running = true;
43400b57cec5SDimitry Andric     while (!GetIsDone()) {
43410b57cec5SDimitry Andric       SelectHelper select_helper;
43420b57cec5SDimitry Andric       select_helper.FDSetRead(read_fd);
43430b57cec5SDimitry Andric       select_helper.FDSetRead(pipe_read_fd);
43440b57cec5SDimitry Andric       Status error = select_helper.Select();
43450b57cec5SDimitry Andric 
43460b57cec5SDimitry Andric       if (error.Fail()) {
43470b57cec5SDimitry Andric         SetIsDone(true);
43480b57cec5SDimitry Andric       } else {
43490b57cec5SDimitry Andric         char ch = 0;
43500b57cec5SDimitry Andric         size_t n;
43510b57cec5SDimitry Andric         if (select_helper.FDIsSetRead(read_fd)) {
43520b57cec5SDimitry Andric           n = 1;
43530b57cec5SDimitry Andric           if (m_read_file.Read(&ch, n).Success() && n == 1) {
43540b57cec5SDimitry Andric             if (m_write_file.Write(&ch, n).Fail() || n != 1)
43550b57cec5SDimitry Andric               SetIsDone(true);
43560b57cec5SDimitry Andric           } else
43570b57cec5SDimitry Andric             SetIsDone(true);
43580b57cec5SDimitry Andric         }
43590b57cec5SDimitry Andric         if (select_helper.FDIsSetRead(pipe_read_fd)) {
43600b57cec5SDimitry Andric           size_t bytes_read;
43610b57cec5SDimitry Andric           // Consume the interrupt byte
43620b57cec5SDimitry Andric           Status error = m_pipe.Read(&ch, 1, bytes_read);
43630b57cec5SDimitry Andric           if (error.Success()) {
43640b57cec5SDimitry Andric             switch (ch) {
43650b57cec5SDimitry Andric             case 'q':
43660b57cec5SDimitry Andric               SetIsDone(true);
43670b57cec5SDimitry Andric               break;
43680b57cec5SDimitry Andric             case 'i':
43690b57cec5SDimitry Andric               if (StateIsRunningState(m_process->GetState()))
43700b57cec5SDimitry Andric                 m_process->SendAsyncInterrupt();
43710b57cec5SDimitry Andric               break;
43720b57cec5SDimitry Andric             }
43730b57cec5SDimitry Andric           }
43740b57cec5SDimitry Andric         }
43750b57cec5SDimitry Andric       }
43760b57cec5SDimitry Andric     }
43770b57cec5SDimitry Andric     m_is_running = false;
43780b57cec5SDimitry Andric #endif
43790b57cec5SDimitry Andric     terminal_state.Restore();
43800b57cec5SDimitry Andric   }
43810b57cec5SDimitry Andric 
Cancel()43820b57cec5SDimitry Andric   void Cancel() override {
43830b57cec5SDimitry Andric     SetIsDone(true);
43840b57cec5SDimitry Andric     // Only write to our pipe to cancel if we are in
43850b57cec5SDimitry Andric     // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
43860b57cec5SDimitry Andric     // is being run from the command interpreter:
43870b57cec5SDimitry Andric     //
43880b57cec5SDimitry Andric     // (lldb) step_process_thousands_of_times
43890b57cec5SDimitry Andric     //
43900b57cec5SDimitry Andric     // In this case the command interpreter will be in the middle of handling
43910b57cec5SDimitry Andric     // the command and if the process pushes and pops the IOHandler thousands
43920b57cec5SDimitry Andric     // of times, we can end up writing to m_pipe without ever consuming the
43930b57cec5SDimitry Andric     // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
43940b57cec5SDimitry Andric     // deadlocking when the pipe gets fed up and blocks until data is consumed.
43950b57cec5SDimitry Andric     if (m_is_running) {
43960b57cec5SDimitry Andric       char ch = 'q'; // Send 'q' for quit
43970b57cec5SDimitry Andric       size_t bytes_written = 0;
43980b57cec5SDimitry Andric       m_pipe.Write(&ch, 1, bytes_written);
43990b57cec5SDimitry Andric     }
44000b57cec5SDimitry Andric   }
44010b57cec5SDimitry Andric 
Interrupt()44020b57cec5SDimitry Andric   bool Interrupt() override {
44030b57cec5SDimitry Andric     // Do only things that are safe to do in an interrupt context (like in a
44040b57cec5SDimitry Andric     // SIGINT handler), like write 1 byte to a file descriptor. This will
44050b57cec5SDimitry Andric     // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
44060b57cec5SDimitry Andric     // that was written to the pipe and then call
44070b57cec5SDimitry Andric     // m_process->SendAsyncInterrupt() from a much safer location in code.
44080b57cec5SDimitry Andric     if (m_active) {
44090b57cec5SDimitry Andric       char ch = 'i'; // Send 'i' for interrupt
44100b57cec5SDimitry Andric       size_t bytes_written = 0;
44110b57cec5SDimitry Andric       Status result = m_pipe.Write(&ch, 1, bytes_written);
44120b57cec5SDimitry Andric       return result.Success();
44130b57cec5SDimitry Andric     } else {
44140b57cec5SDimitry Andric       // This IOHandler might be pushed on the stack, but not being run
44150b57cec5SDimitry Andric       // currently so do the right thing if we aren't actively watching for
44160b57cec5SDimitry Andric       // STDIN by sending the interrupt to the process. Otherwise the write to
44170b57cec5SDimitry Andric       // the pipe above would do nothing. This can happen when the command
44180b57cec5SDimitry Andric       // interpreter is running and gets a "expression ...". It will be on the
44190b57cec5SDimitry Andric       // IOHandler thread and sending the input is complete to the delegate
44200b57cec5SDimitry Andric       // which will cause the expression to run, which will push the process IO
44210b57cec5SDimitry Andric       // handler, but not run it.
44220b57cec5SDimitry Andric 
44230b57cec5SDimitry Andric       if (StateIsRunningState(m_process->GetState())) {
44240b57cec5SDimitry Andric         m_process->SendAsyncInterrupt();
44250b57cec5SDimitry Andric         return true;
44260b57cec5SDimitry Andric       }
44270b57cec5SDimitry Andric     }
44280b57cec5SDimitry Andric     return false;
44290b57cec5SDimitry Andric   }
44300b57cec5SDimitry Andric 
GotEOF()44310b57cec5SDimitry Andric   void GotEOF() override {}
44320b57cec5SDimitry Andric 
44330b57cec5SDimitry Andric protected:
44340b57cec5SDimitry Andric   Process *m_process;
44359dba64beSDimitry Andric   NativeFile m_read_file;  // Read from this file (usually actual STDIN for LLDB
44369dba64beSDimitry Andric   NativeFile m_write_file; // Write to this file (usually the master pty for
44379dba64beSDimitry Andric                            // getting io to debuggee)
44380b57cec5SDimitry Andric   Pipe m_pipe;
44390b57cec5SDimitry Andric   std::atomic<bool> m_is_running{false};
44400b57cec5SDimitry Andric };
44410b57cec5SDimitry Andric 
SetSTDIOFileDescriptor(int fd)44420b57cec5SDimitry Andric void Process::SetSTDIOFileDescriptor(int fd) {
44430b57cec5SDimitry Andric   // First set up the Read Thread for reading/handling process I/O
44445ffd83dbSDimitry Andric   m_stdio_communication.SetConnection(
44455ffd83dbSDimitry Andric       std::make_unique<ConnectionFileDescriptor>(fd, true));
44460b57cec5SDimitry Andric   if (m_stdio_communication.IsConnected()) {
44470b57cec5SDimitry Andric     m_stdio_communication.SetReadThreadBytesReceivedCallback(
44480b57cec5SDimitry Andric         STDIOReadThreadBytesReceived, this);
44490b57cec5SDimitry Andric     m_stdio_communication.StartReadThread();
44500b57cec5SDimitry Andric 
44510b57cec5SDimitry Andric     // Now read thread is set up, set up input reader.
44520b57cec5SDimitry Andric 
44530b57cec5SDimitry Andric     if (!m_process_input_reader)
44540b57cec5SDimitry Andric       m_process_input_reader =
44550b57cec5SDimitry Andric           std::make_shared<IOHandlerProcessSTDIO>(this, fd);
44560b57cec5SDimitry Andric   }
44570b57cec5SDimitry Andric }
44580b57cec5SDimitry Andric 
ProcessIOHandlerIsActive()44590b57cec5SDimitry Andric bool Process::ProcessIOHandlerIsActive() {
44600b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
44610b57cec5SDimitry Andric   if (io_handler_sp)
44620b57cec5SDimitry Andric     return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
44630b57cec5SDimitry Andric   return false;
44640b57cec5SDimitry Andric }
PushProcessIOHandler()44650b57cec5SDimitry Andric bool Process::PushProcessIOHandler() {
44660b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
44670b57cec5SDimitry Andric   if (io_handler_sp) {
44680b57cec5SDimitry Andric     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
44699dba64beSDimitry Andric     LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
44700b57cec5SDimitry Andric 
44710b57cec5SDimitry Andric     io_handler_sp->SetIsDone(false);
44720b57cec5SDimitry Andric     // If we evaluate an utility function, then we don't cancel the current
44730b57cec5SDimitry Andric     // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
44740b57cec5SDimitry Andric     // existing IOHandler that potentially provides the user interface (e.g.
44750b57cec5SDimitry Andric     // the IOHandler for Editline).
44760b57cec5SDimitry Andric     bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
44775ffd83dbSDimitry Andric     GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
44785ffd83dbSDimitry Andric                                                 cancel_top_handler);
44790b57cec5SDimitry Andric     return true;
44800b57cec5SDimitry Andric   }
44810b57cec5SDimitry Andric   return false;
44820b57cec5SDimitry Andric }
44830b57cec5SDimitry Andric 
PopProcessIOHandler()44840b57cec5SDimitry Andric bool Process::PopProcessIOHandler() {
44850b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
44860b57cec5SDimitry Andric   if (io_handler_sp)
44875ffd83dbSDimitry Andric     return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
44880b57cec5SDimitry Andric   return false;
44890b57cec5SDimitry Andric }
44900b57cec5SDimitry Andric 
44910b57cec5SDimitry Andric // The process needs to know about installed plug-ins
SettingsInitialize()44920b57cec5SDimitry Andric void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
44930b57cec5SDimitry Andric 
SettingsTerminate()44940b57cec5SDimitry Andric void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
44950b57cec5SDimitry Andric 
44960b57cec5SDimitry Andric namespace {
44970b57cec5SDimitry Andric // RestorePlanState is used to record the "is private", "is master" and "okay
44980b57cec5SDimitry Andric // to discard" fields of the plan we are running, and reset it on Clean or on
44990b57cec5SDimitry Andric // destruction. It will only reset the state once, so you can call Clean and
45000b57cec5SDimitry Andric // then monkey with the state and it won't get reset on you again.
45010b57cec5SDimitry Andric 
45020b57cec5SDimitry Andric class RestorePlanState {
45030b57cec5SDimitry Andric public:
RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)45040b57cec5SDimitry Andric   RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
45050b57cec5SDimitry Andric       : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
45060b57cec5SDimitry Andric     if (m_thread_plan_sp) {
45070b57cec5SDimitry Andric       m_private = m_thread_plan_sp->GetPrivate();
45080b57cec5SDimitry Andric       m_is_master = m_thread_plan_sp->IsMasterPlan();
45090b57cec5SDimitry Andric       m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
45100b57cec5SDimitry Andric     }
45110b57cec5SDimitry Andric   }
45120b57cec5SDimitry Andric 
~RestorePlanState()45130b57cec5SDimitry Andric   ~RestorePlanState() { Clean(); }
45140b57cec5SDimitry Andric 
Clean()45150b57cec5SDimitry Andric   void Clean() {
45160b57cec5SDimitry Andric     if (!m_already_reset && m_thread_plan_sp) {
45170b57cec5SDimitry Andric       m_already_reset = true;
45180b57cec5SDimitry Andric       m_thread_plan_sp->SetPrivate(m_private);
45190b57cec5SDimitry Andric       m_thread_plan_sp->SetIsMasterPlan(m_is_master);
45200b57cec5SDimitry Andric       m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
45210b57cec5SDimitry Andric     }
45220b57cec5SDimitry Andric   }
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric private:
45250b57cec5SDimitry Andric   lldb::ThreadPlanSP m_thread_plan_sp;
45260b57cec5SDimitry Andric   bool m_already_reset;
45270b57cec5SDimitry Andric   bool m_private;
45280b57cec5SDimitry Andric   bool m_is_master;
45290b57cec5SDimitry Andric   bool m_okay_to_discard;
45300b57cec5SDimitry Andric };
45310b57cec5SDimitry Andric } // anonymous namespace
45320b57cec5SDimitry Andric 
45330b57cec5SDimitry Andric static microseconds
GetOneThreadExpressionTimeout(const EvaluateExpressionOptions & options)45340b57cec5SDimitry Andric GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
45350b57cec5SDimitry Andric   const milliseconds default_one_thread_timeout(250);
45360b57cec5SDimitry Andric 
45370b57cec5SDimitry Andric   // If the overall wait is forever, then we don't need to worry about it.
45380b57cec5SDimitry Andric   if (!options.GetTimeout()) {
45390b57cec5SDimitry Andric     return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
45400b57cec5SDimitry Andric                                          : default_one_thread_timeout;
45410b57cec5SDimitry Andric   }
45420b57cec5SDimitry Andric 
45430b57cec5SDimitry Andric   // If the one thread timeout is set, use it.
45440b57cec5SDimitry Andric   if (options.GetOneThreadTimeout())
45450b57cec5SDimitry Andric     return *options.GetOneThreadTimeout();
45460b57cec5SDimitry Andric 
45470b57cec5SDimitry Andric   // Otherwise use half the total timeout, bounded by the
45480b57cec5SDimitry Andric   // default_one_thread_timeout.
45490b57cec5SDimitry Andric   return std::min<microseconds>(default_one_thread_timeout,
45500b57cec5SDimitry Andric                                 *options.GetTimeout() / 2);
45510b57cec5SDimitry Andric }
45520b57cec5SDimitry Andric 
45530b57cec5SDimitry Andric static Timeout<std::micro>
GetExpressionTimeout(const EvaluateExpressionOptions & options,bool before_first_timeout)45540b57cec5SDimitry Andric GetExpressionTimeout(const EvaluateExpressionOptions &options,
45550b57cec5SDimitry Andric                      bool before_first_timeout) {
45560b57cec5SDimitry Andric   // If we are going to run all threads the whole time, or if we are only going
45570b57cec5SDimitry Andric   // to run one thread, we can just return the overall timeout.
45580b57cec5SDimitry Andric   if (!options.GetStopOthers() || !options.GetTryAllThreads())
45590b57cec5SDimitry Andric     return options.GetTimeout();
45600b57cec5SDimitry Andric 
45610b57cec5SDimitry Andric   if (before_first_timeout)
45620b57cec5SDimitry Andric     return GetOneThreadExpressionTimeout(options);
45630b57cec5SDimitry Andric 
45640b57cec5SDimitry Andric   if (!options.GetTimeout())
45650b57cec5SDimitry Andric     return llvm::None;
45660b57cec5SDimitry Andric   else
45670b57cec5SDimitry Andric     return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
45680b57cec5SDimitry Andric }
45690b57cec5SDimitry Andric 
45700b57cec5SDimitry Andric static llvm::Optional<ExpressionResults>
HandleStoppedEvent(lldb::tid_t thread_id,const ThreadPlanSP & thread_plan_sp,RestorePlanState & restorer,const EventSP & event_sp,EventSP & event_to_broadcast_sp,const EvaluateExpressionOptions & options,bool handle_interrupts)45715ffd83dbSDimitry Andric HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
45720b57cec5SDimitry Andric                    RestorePlanState &restorer, const EventSP &event_sp,
45730b57cec5SDimitry Andric                    EventSP &event_to_broadcast_sp,
45745ffd83dbSDimitry Andric                    const EvaluateExpressionOptions &options,
45755ffd83dbSDimitry Andric                    bool handle_interrupts) {
45760b57cec5SDimitry Andric   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
45770b57cec5SDimitry Andric 
45785ffd83dbSDimitry Andric   ThreadSP thread_sp = thread_plan_sp->GetTarget()
45795ffd83dbSDimitry Andric                            .GetProcessSP()
45805ffd83dbSDimitry Andric                            ->GetThreadList()
45815ffd83dbSDimitry Andric                            .FindThreadByID(thread_id);
45825ffd83dbSDimitry Andric   if (!thread_sp) {
45835ffd83dbSDimitry Andric     LLDB_LOG(log,
45845ffd83dbSDimitry Andric              "The thread on which we were running the "
45855ffd83dbSDimitry Andric              "expression: tid = {0}, exited while "
45865ffd83dbSDimitry Andric              "the expression was running.",
45875ffd83dbSDimitry Andric              thread_id);
45885ffd83dbSDimitry Andric     return eExpressionThreadVanished;
45895ffd83dbSDimitry Andric   }
45905ffd83dbSDimitry Andric 
45915ffd83dbSDimitry Andric   ThreadPlanSP plan = thread_sp->GetCompletedPlan();
45920b57cec5SDimitry Andric   if (plan == thread_plan_sp && plan->PlanSucceeded()) {
45930b57cec5SDimitry Andric     LLDB_LOG(log, "execution completed successfully");
45940b57cec5SDimitry Andric 
45950b57cec5SDimitry Andric     // Restore the plan state so it will get reported as intended when we are
45960b57cec5SDimitry Andric     // done.
45970b57cec5SDimitry Andric     restorer.Clean();
45980b57cec5SDimitry Andric     return eExpressionCompleted;
45990b57cec5SDimitry Andric   }
46000b57cec5SDimitry Andric 
46015ffd83dbSDimitry Andric   StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
46020b57cec5SDimitry Andric   if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
46030b57cec5SDimitry Andric       stop_info_sp->ShouldNotify(event_sp.get())) {
46040b57cec5SDimitry Andric     LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
46050b57cec5SDimitry Andric     if (!options.DoesIgnoreBreakpoints()) {
46060b57cec5SDimitry Andric       // Restore the plan state and then force Private to false.  We are going
46070b57cec5SDimitry Andric       // to stop because of this plan so we need it to become a public plan or
46080b57cec5SDimitry Andric       // it won't report correctly when we continue to its termination later
46090b57cec5SDimitry Andric       // on.
46100b57cec5SDimitry Andric       restorer.Clean();
46110b57cec5SDimitry Andric       thread_plan_sp->SetPrivate(false);
46120b57cec5SDimitry Andric       event_to_broadcast_sp = event_sp;
46130b57cec5SDimitry Andric     }
46140b57cec5SDimitry Andric     return eExpressionHitBreakpoint;
46150b57cec5SDimitry Andric   }
46160b57cec5SDimitry Andric 
46170b57cec5SDimitry Andric   if (!handle_interrupts &&
46180b57cec5SDimitry Andric       Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
46190b57cec5SDimitry Andric     return llvm::None;
46200b57cec5SDimitry Andric 
46210b57cec5SDimitry Andric   LLDB_LOG(log, "thread plan did not successfully complete");
46220b57cec5SDimitry Andric   if (!options.DoesUnwindOnError())
46230b57cec5SDimitry Andric     event_to_broadcast_sp = event_sp;
46240b57cec5SDimitry Andric   return eExpressionInterrupted;
46250b57cec5SDimitry Andric }
46260b57cec5SDimitry Andric 
46270b57cec5SDimitry Andric ExpressionResults
RunThreadPlan(ExecutionContext & exe_ctx,lldb::ThreadPlanSP & thread_plan_sp,const EvaluateExpressionOptions & options,DiagnosticManager & diagnostic_manager)46280b57cec5SDimitry Andric Process::RunThreadPlan(ExecutionContext &exe_ctx,
46290b57cec5SDimitry Andric                        lldb::ThreadPlanSP &thread_plan_sp,
46300b57cec5SDimitry Andric                        const EvaluateExpressionOptions &options,
46310b57cec5SDimitry Andric                        DiagnosticManager &diagnostic_manager) {
46320b57cec5SDimitry Andric   ExpressionResults return_value = eExpressionSetupError;
46330b57cec5SDimitry Andric 
46340b57cec5SDimitry Andric   std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   if (!thread_plan_sp) {
46370b57cec5SDimitry Andric     diagnostic_manager.PutString(
46380b57cec5SDimitry Andric         eDiagnosticSeverityError,
46390b57cec5SDimitry Andric         "RunThreadPlan called with empty thread plan.");
46400b57cec5SDimitry Andric     return eExpressionSetupError;
46410b57cec5SDimitry Andric   }
46420b57cec5SDimitry Andric 
46430b57cec5SDimitry Andric   if (!thread_plan_sp->ValidatePlan(nullptr)) {
46440b57cec5SDimitry Andric     diagnostic_manager.PutString(
46450b57cec5SDimitry Andric         eDiagnosticSeverityError,
46460b57cec5SDimitry Andric         "RunThreadPlan called with an invalid thread plan.");
46470b57cec5SDimitry Andric     return eExpressionSetupError;
46480b57cec5SDimitry Andric   }
46490b57cec5SDimitry Andric 
46500b57cec5SDimitry Andric   if (exe_ctx.GetProcessPtr() != this) {
46510b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
46520b57cec5SDimitry Andric                                  "RunThreadPlan called on wrong process.");
46530b57cec5SDimitry Andric     return eExpressionSetupError;
46540b57cec5SDimitry Andric   }
46550b57cec5SDimitry Andric 
46560b57cec5SDimitry Andric   Thread *thread = exe_ctx.GetThreadPtr();
46570b57cec5SDimitry Andric   if (thread == nullptr) {
46580b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
46590b57cec5SDimitry Andric                                  "RunThreadPlan called with invalid thread.");
46600b57cec5SDimitry Andric     return eExpressionSetupError;
46610b57cec5SDimitry Andric   }
46620b57cec5SDimitry Andric 
46635ffd83dbSDimitry Andric   // Record the thread's id so we can tell when a thread we were using
46645ffd83dbSDimitry Andric   // to run the expression exits during the expression evaluation.
46655ffd83dbSDimitry Andric   lldb::tid_t expr_thread_id = thread->GetID();
46665ffd83dbSDimitry Andric 
46670b57cec5SDimitry Andric   // We need to change some of the thread plan attributes for the thread plan
46680b57cec5SDimitry Andric   // runner.  This will restore them when we are done:
46690b57cec5SDimitry Andric 
46700b57cec5SDimitry Andric   RestorePlanState thread_plan_restorer(thread_plan_sp);
46710b57cec5SDimitry Andric 
46720b57cec5SDimitry Andric   // We rely on the thread plan we are running returning "PlanCompleted" if
46730b57cec5SDimitry Andric   // when it successfully completes. For that to be true the plan can't be
46740b57cec5SDimitry Andric   // private - since private plans suppress themselves in the GetCompletedPlan
46750b57cec5SDimitry Andric   // call.
46760b57cec5SDimitry Andric 
46770b57cec5SDimitry Andric   thread_plan_sp->SetPrivate(false);
46780b57cec5SDimitry Andric 
46790b57cec5SDimitry Andric   // The plans run with RunThreadPlan also need to be terminal master plans or
46800b57cec5SDimitry Andric   // when they are done we will end up asking the plan above us whether we
46810b57cec5SDimitry Andric   // should stop, which may give the wrong answer.
46820b57cec5SDimitry Andric 
46830b57cec5SDimitry Andric   thread_plan_sp->SetIsMasterPlan(true);
46840b57cec5SDimitry Andric   thread_plan_sp->SetOkayToDiscard(false);
46850b57cec5SDimitry Andric 
46860b57cec5SDimitry Andric   // If we are running some utility expression for LLDB, we now have to mark
46870b57cec5SDimitry Andric   // this in the ProcesModID of this process. This RAII takes care of marking
46880b57cec5SDimitry Andric   // and reverting the mark it once we are done running the expression.
46890b57cec5SDimitry Andric   UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
46900b57cec5SDimitry Andric 
46910b57cec5SDimitry Andric   if (m_private_state.GetValue() != eStateStopped) {
46920b57cec5SDimitry Andric     diagnostic_manager.PutString(
46930b57cec5SDimitry Andric         eDiagnosticSeverityError,
46940b57cec5SDimitry Andric         "RunThreadPlan called while the private state was not stopped.");
46950b57cec5SDimitry Andric     return eExpressionSetupError;
46960b57cec5SDimitry Andric   }
46970b57cec5SDimitry Andric 
46980b57cec5SDimitry Andric   // Save the thread & frame from the exe_ctx for restoration after we run
46990b57cec5SDimitry Andric   const uint32_t thread_idx_id = thread->GetIndexID();
47000b57cec5SDimitry Andric   StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
47010b57cec5SDimitry Andric   if (!selected_frame_sp) {
47020b57cec5SDimitry Andric     thread->SetSelectedFrame(nullptr);
47030b57cec5SDimitry Andric     selected_frame_sp = thread->GetSelectedFrame();
47040b57cec5SDimitry Andric     if (!selected_frame_sp) {
47050b57cec5SDimitry Andric       diagnostic_manager.Printf(
47060b57cec5SDimitry Andric           eDiagnosticSeverityError,
47070b57cec5SDimitry Andric           "RunThreadPlan called without a selected frame on thread %d",
47080b57cec5SDimitry Andric           thread_idx_id);
47090b57cec5SDimitry Andric       return eExpressionSetupError;
47100b57cec5SDimitry Andric     }
47110b57cec5SDimitry Andric   }
47120b57cec5SDimitry Andric 
47130b57cec5SDimitry Andric   // Make sure the timeout values make sense. The one thread timeout needs to
47140b57cec5SDimitry Andric   // be smaller than the overall timeout.
47150b57cec5SDimitry Andric   if (options.GetOneThreadTimeout() && options.GetTimeout() &&
47160b57cec5SDimitry Andric       *options.GetTimeout() < *options.GetOneThreadTimeout()) {
47170b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
47180b57cec5SDimitry Andric                                  "RunThreadPlan called with one thread "
47190b57cec5SDimitry Andric                                  "timeout greater than total timeout");
47200b57cec5SDimitry Andric     return eExpressionSetupError;
47210b57cec5SDimitry Andric   }
47220b57cec5SDimitry Andric 
47230b57cec5SDimitry Andric   StackID ctx_frame_id = selected_frame_sp->GetStackID();
47240b57cec5SDimitry Andric 
47250b57cec5SDimitry Andric   // N.B. Running the target may unset the currently selected thread and frame.
47260b57cec5SDimitry Andric   // We don't want to do that either, so we should arrange to reset them as
47270b57cec5SDimitry Andric   // well.
47280b57cec5SDimitry Andric 
47290b57cec5SDimitry Andric   lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
47300b57cec5SDimitry Andric 
47310b57cec5SDimitry Andric   uint32_t selected_tid;
47320b57cec5SDimitry Andric   StackID selected_stack_id;
47330b57cec5SDimitry Andric   if (selected_thread_sp) {
47340b57cec5SDimitry Andric     selected_tid = selected_thread_sp->GetIndexID();
47350b57cec5SDimitry Andric     selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
47360b57cec5SDimitry Andric   } else {
47370b57cec5SDimitry Andric     selected_tid = LLDB_INVALID_THREAD_ID;
47380b57cec5SDimitry Andric   }
47390b57cec5SDimitry Andric 
47400b57cec5SDimitry Andric   HostThread backup_private_state_thread;
47410b57cec5SDimitry Andric   lldb::StateType old_state = eStateInvalid;
47420b57cec5SDimitry Andric   lldb::ThreadPlanSP stopper_base_plan_sp;
47430b57cec5SDimitry Andric 
47440b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
47450b57cec5SDimitry Andric                                                   LIBLLDB_LOG_PROCESS));
47460b57cec5SDimitry Andric   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
47470b57cec5SDimitry Andric     // Yikes, we are running on the private state thread!  So we can't wait for
47480b57cec5SDimitry Andric     // public events on this thread, since we are the thread that is generating
47490b57cec5SDimitry Andric     // public events. The simplest thing to do is to spin up a temporary thread
47500b57cec5SDimitry Andric     // to handle private state thread events while we are fielding public
47510b57cec5SDimitry Andric     // events here.
47529dba64beSDimitry Andric     LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
47530b57cec5SDimitry Andric                    "another state thread to handle the events.");
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric     backup_private_state_thread = m_private_state_thread;
47560b57cec5SDimitry Andric 
47570b57cec5SDimitry Andric     // One other bit of business: we want to run just this thread plan and
47580b57cec5SDimitry Andric     // anything it pushes, and then stop, returning control here. But in the
47590b57cec5SDimitry Andric     // normal course of things, the plan above us on the stack would be given a
47600b57cec5SDimitry Andric     // shot at the stop event before deciding to stop, and we don't want that.
47610b57cec5SDimitry Andric     // So we insert a "stopper" base plan on the stack before the plan we want
47620b57cec5SDimitry Andric     // to run.  Since base plans always stop and return control to the user,
47630b57cec5SDimitry Andric     // that will do just what we want.
47640b57cec5SDimitry Andric     stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
47650b57cec5SDimitry Andric     thread->QueueThreadPlan(stopper_base_plan_sp, false);
47660b57cec5SDimitry Andric     // Have to make sure our public state is stopped, since otherwise the
47670b57cec5SDimitry Andric     // reporting logic below doesn't work correctly.
47680b57cec5SDimitry Andric     old_state = m_public_state.GetValue();
47690b57cec5SDimitry Andric     m_public_state.SetValueNoLock(eStateStopped);
47700b57cec5SDimitry Andric 
47710b57cec5SDimitry Andric     // Now spin up the private state thread:
47720b57cec5SDimitry Andric     StartPrivateStateThread(true);
47730b57cec5SDimitry Andric   }
47740b57cec5SDimitry Andric 
47750b57cec5SDimitry Andric   thread->QueueThreadPlan(
47760b57cec5SDimitry Andric       thread_plan_sp, false); // This used to pass "true" does that make sense?
47770b57cec5SDimitry Andric 
47780b57cec5SDimitry Andric   if (options.GetDebug()) {
47790b57cec5SDimitry Andric     // In this case, we aren't actually going to run, we just want to stop
47800b57cec5SDimitry Andric     // right away. Flush this thread so we will refetch the stacks and show the
47810b57cec5SDimitry Andric     // correct backtrace.
47820b57cec5SDimitry Andric     // FIXME: To make this prettier we should invent some stop reason for this,
47830b57cec5SDimitry Andric     // but that
47840b57cec5SDimitry Andric     // is only cosmetic, and this functionality is only of use to lldb
47850b57cec5SDimitry Andric     // developers who can live with not pretty...
47860b57cec5SDimitry Andric     thread->Flush();
47870b57cec5SDimitry Andric     return eExpressionStoppedForDebug;
47880b57cec5SDimitry Andric   }
47890b57cec5SDimitry Andric 
47900b57cec5SDimitry Andric   ListenerSP listener_sp(
47910b57cec5SDimitry Andric       Listener::MakeListener("lldb.process.listener.run-thread-plan"));
47920b57cec5SDimitry Andric 
47930b57cec5SDimitry Andric   lldb::EventSP event_to_broadcast_sp;
47940b57cec5SDimitry Andric 
47950b57cec5SDimitry Andric   {
47960b57cec5SDimitry Andric     // This process event hijacker Hijacks the Public events and its destructor
47970b57cec5SDimitry Andric     // makes sure that the process events get restored on exit to the function.
47980b57cec5SDimitry Andric     //
47990b57cec5SDimitry Andric     // If the event needs to propagate beyond the hijacker (e.g., the process
48000b57cec5SDimitry Andric     // exits during execution), then the event is put into
48010b57cec5SDimitry Andric     // event_to_broadcast_sp for rebroadcasting.
48020b57cec5SDimitry Andric 
48030b57cec5SDimitry Andric     ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
48040b57cec5SDimitry Andric 
48050b57cec5SDimitry Andric     if (log) {
48060b57cec5SDimitry Andric       StreamString s;
48070b57cec5SDimitry Andric       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
48089dba64beSDimitry Andric       LLDB_LOGF(log,
48099dba64beSDimitry Andric                 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
48100b57cec5SDimitry Andric                 " to run thread plan \"%s\".",
48115ffd83dbSDimitry Andric                 thread_idx_id, expr_thread_id, s.GetData());
48120b57cec5SDimitry Andric     }
48130b57cec5SDimitry Andric 
48140b57cec5SDimitry Andric     bool got_event;
48150b57cec5SDimitry Andric     lldb::EventSP event_sp;
48160b57cec5SDimitry Andric     lldb::StateType stop_state = lldb::eStateInvalid;
48170b57cec5SDimitry Andric 
48180b57cec5SDimitry Andric     bool before_first_timeout = true; // This is set to false the first time
48190b57cec5SDimitry Andric                                       // that we have to halt the target.
48200b57cec5SDimitry Andric     bool do_resume = true;
48210b57cec5SDimitry Andric     bool handle_running_event = true;
48220b57cec5SDimitry Andric 
48230b57cec5SDimitry Andric     // This is just for accounting:
48240b57cec5SDimitry Andric     uint32_t num_resumes = 0;
48250b57cec5SDimitry Andric 
48260b57cec5SDimitry Andric     // If we are going to run all threads the whole time, or if we are only
48270b57cec5SDimitry Andric     // going to run one thread, then we don't need the first timeout.  So we
48280b57cec5SDimitry Andric     // pretend we are after the first timeout already.
48290b57cec5SDimitry Andric     if (!options.GetStopOthers() || !options.GetTryAllThreads())
48300b57cec5SDimitry Andric       before_first_timeout = false;
48310b57cec5SDimitry Andric 
48329dba64beSDimitry Andric     LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
48330b57cec5SDimitry Andric               options.GetStopOthers(), options.GetTryAllThreads(),
48340b57cec5SDimitry Andric               before_first_timeout);
48350b57cec5SDimitry Andric 
48360b57cec5SDimitry Andric     // This isn't going to work if there are unfetched events on the queue. Are
48370b57cec5SDimitry Andric     // there cases where we might want to run the remaining events here, and
48380b57cec5SDimitry Andric     // then try to call the function?  That's probably being too tricky for our
48390b57cec5SDimitry Andric     // own good.
48400b57cec5SDimitry Andric 
48410b57cec5SDimitry Andric     Event *other_events = listener_sp->PeekAtNextEvent();
48420b57cec5SDimitry Andric     if (other_events != nullptr) {
48430b57cec5SDimitry Andric       diagnostic_manager.PutString(
48440b57cec5SDimitry Andric           eDiagnosticSeverityError,
48450b57cec5SDimitry Andric           "RunThreadPlan called with pending events on the queue.");
48460b57cec5SDimitry Andric       return eExpressionSetupError;
48470b57cec5SDimitry Andric     }
48480b57cec5SDimitry Andric 
48490b57cec5SDimitry Andric     // We also need to make sure that the next event is delivered.  We might be
48500b57cec5SDimitry Andric     // calling a function as part of a thread plan, in which case the last
48510b57cec5SDimitry Andric     // delivered event could be the running event, and we don't want event
48520b57cec5SDimitry Andric     // coalescing to cause us to lose OUR running event...
48530b57cec5SDimitry Andric     ForceNextEventDelivery();
48540b57cec5SDimitry Andric 
48550b57cec5SDimitry Andric // This while loop must exit out the bottom, there's cleanup that we need to do
48560b57cec5SDimitry Andric // when we are done. So don't call return anywhere within it.
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
48590b57cec5SDimitry Andric     // It's pretty much impossible to write test cases for things like: One
48600b57cec5SDimitry Andric     // thread timeout expires, I go to halt, but the process already stopped on
48610b57cec5SDimitry Andric     // the function call stop breakpoint.  Turning on this define will make us
48620b57cec5SDimitry Andric     // not fetch the first event till after the halt.  So if you run a quick
48630b57cec5SDimitry Andric     // function, it will have completed, and the completion event will be
48640b57cec5SDimitry Andric     // waiting, when you interrupt for halt. The expression evaluation should
48650b57cec5SDimitry Andric     // still succeed.
48660b57cec5SDimitry Andric     bool miss_first_event = true;
48670b57cec5SDimitry Andric #endif
48680b57cec5SDimitry Andric     while (true) {
48690b57cec5SDimitry Andric       // We usually want to resume the process if we get to the top of the
48700b57cec5SDimitry Andric       // loop. The only exception is if we get two running events with no
48710b57cec5SDimitry Andric       // intervening stop, which can happen, we will just wait for then next
48720b57cec5SDimitry Andric       // stop event.
48739dba64beSDimitry Andric       LLDB_LOGF(log,
48749dba64beSDimitry Andric                 "Top of while loop: do_resume: %i handle_running_event: %i "
48750b57cec5SDimitry Andric                 "before_first_timeout: %i.",
48760b57cec5SDimitry Andric                 do_resume, handle_running_event, before_first_timeout);
48770b57cec5SDimitry Andric 
48780b57cec5SDimitry Andric       if (do_resume || handle_running_event) {
48790b57cec5SDimitry Andric         // Do the initial resume and wait for the running event before going
48800b57cec5SDimitry Andric         // further.
48810b57cec5SDimitry Andric 
48820b57cec5SDimitry Andric         if (do_resume) {
48830b57cec5SDimitry Andric           num_resumes++;
48840b57cec5SDimitry Andric           Status resume_error = PrivateResume();
48850b57cec5SDimitry Andric           if (!resume_error.Success()) {
48860b57cec5SDimitry Andric             diagnostic_manager.Printf(
48870b57cec5SDimitry Andric                 eDiagnosticSeverityError,
48880b57cec5SDimitry Andric                 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
48890b57cec5SDimitry Andric                 resume_error.AsCString());
48900b57cec5SDimitry Andric             return_value = eExpressionSetupError;
48910b57cec5SDimitry Andric             break;
48920b57cec5SDimitry Andric           }
48930b57cec5SDimitry Andric         }
48940b57cec5SDimitry Andric 
48950b57cec5SDimitry Andric         got_event =
48960b57cec5SDimitry Andric             listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
48970b57cec5SDimitry Andric         if (!got_event) {
48989dba64beSDimitry Andric           LLDB_LOGF(log,
48999dba64beSDimitry Andric                     "Process::RunThreadPlan(): didn't get any event after "
49000b57cec5SDimitry Andric                     "resume %" PRIu32 ", exiting.",
49010b57cec5SDimitry Andric                     num_resumes);
49020b57cec5SDimitry Andric 
49030b57cec5SDimitry Andric           diagnostic_manager.Printf(eDiagnosticSeverityError,
49040b57cec5SDimitry Andric                                     "didn't get any event after resume %" PRIu32
49050b57cec5SDimitry Andric                                     ", exiting.",
49060b57cec5SDimitry Andric                                     num_resumes);
49070b57cec5SDimitry Andric           return_value = eExpressionSetupError;
49080b57cec5SDimitry Andric           break;
49090b57cec5SDimitry Andric         }
49100b57cec5SDimitry Andric 
49110b57cec5SDimitry Andric         stop_state =
49120b57cec5SDimitry Andric             Process::ProcessEventData::GetStateFromEvent(event_sp.get());
49130b57cec5SDimitry Andric 
49140b57cec5SDimitry Andric         if (stop_state != eStateRunning) {
49150b57cec5SDimitry Andric           bool restarted = false;
49160b57cec5SDimitry Andric 
49170b57cec5SDimitry Andric           if (stop_state == eStateStopped) {
49180b57cec5SDimitry Andric             restarted = Process::ProcessEventData::GetRestartedFromEvent(
49190b57cec5SDimitry Andric                 event_sp.get());
49209dba64beSDimitry Andric             LLDB_LOGF(
49219dba64beSDimitry Andric                 log,
49220b57cec5SDimitry Andric                 "Process::RunThreadPlan(): didn't get running event after "
49230b57cec5SDimitry Andric                 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
49240b57cec5SDimitry Andric                 "handle_running_event: %i).",
49250b57cec5SDimitry Andric                 num_resumes, StateAsCString(stop_state), restarted, do_resume,
49260b57cec5SDimitry Andric                 handle_running_event);
49270b57cec5SDimitry Andric           }
49280b57cec5SDimitry Andric 
49290b57cec5SDimitry Andric           if (restarted) {
49300b57cec5SDimitry Andric             // This is probably an overabundance of caution, I don't think I
49310b57cec5SDimitry Andric             // should ever get a stopped & restarted event here.  But if I do,
49320b57cec5SDimitry Andric             // the best thing is to Halt and then get out of here.
49330b57cec5SDimitry Andric             const bool clear_thread_plans = false;
49340b57cec5SDimitry Andric             const bool use_run_lock = false;
49350b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
49360b57cec5SDimitry Andric           }
49370b57cec5SDimitry Andric 
49380b57cec5SDimitry Andric           diagnostic_manager.Printf(
49390b57cec5SDimitry Andric               eDiagnosticSeverityError,
49400b57cec5SDimitry Andric               "didn't get running event after initial resume, got %s instead.",
49410b57cec5SDimitry Andric               StateAsCString(stop_state));
49420b57cec5SDimitry Andric           return_value = eExpressionSetupError;
49430b57cec5SDimitry Andric           break;
49440b57cec5SDimitry Andric         }
49450b57cec5SDimitry Andric 
49460b57cec5SDimitry Andric         if (log)
49470b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
49480b57cec5SDimitry Andric         // We need to call the function synchronously, so spin waiting for it
49490b57cec5SDimitry Andric         // to return. If we get interrupted while executing, we're going to
49500b57cec5SDimitry Andric         // lose our context, and won't be able to gather the result at this
49510b57cec5SDimitry Andric         // point. We set the timeout AFTER the resume, since the resume takes
49520b57cec5SDimitry Andric         // some time and we don't want to charge that to the timeout.
49530b57cec5SDimitry Andric       } else {
49540b57cec5SDimitry Andric         if (log)
49550b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): waiting for next event.");
49560b57cec5SDimitry Andric       }
49570b57cec5SDimitry Andric 
49580b57cec5SDimitry Andric       do_resume = true;
49590b57cec5SDimitry Andric       handle_running_event = true;
49600b57cec5SDimitry Andric 
49610b57cec5SDimitry Andric       // Now wait for the process to stop again:
49620b57cec5SDimitry Andric       event_sp.reset();
49630b57cec5SDimitry Andric 
49640b57cec5SDimitry Andric       Timeout<std::micro> timeout =
49650b57cec5SDimitry Andric           GetExpressionTimeout(options, before_first_timeout);
49660b57cec5SDimitry Andric       if (log) {
49670b57cec5SDimitry Andric         if (timeout) {
49680b57cec5SDimitry Andric           auto now = system_clock::now();
49699dba64beSDimitry Andric           LLDB_LOGF(log,
49709dba64beSDimitry Andric                     "Process::RunThreadPlan(): about to wait - now is %s - "
49710b57cec5SDimitry Andric                     "endpoint is %s",
49720b57cec5SDimitry Andric                     llvm::to_string(now).c_str(),
49730b57cec5SDimitry Andric                     llvm::to_string(now + *timeout).c_str());
49740b57cec5SDimitry Andric         } else {
49759dba64beSDimitry Andric           LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
49760b57cec5SDimitry Andric         }
49770b57cec5SDimitry Andric       }
49780b57cec5SDimitry Andric 
49790b57cec5SDimitry Andric #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
49800b57cec5SDimitry Andric       // See comment above...
49810b57cec5SDimitry Andric       if (miss_first_event) {
49829dba64beSDimitry Andric         std::this_thread::sleep_for(std::chrono::milliseconds(1));
49830b57cec5SDimitry Andric         miss_first_event = false;
49840b57cec5SDimitry Andric         got_event = false;
49850b57cec5SDimitry Andric       } else
49860b57cec5SDimitry Andric #endif
49870b57cec5SDimitry Andric         got_event = listener_sp->GetEvent(event_sp, timeout);
49880b57cec5SDimitry Andric 
49890b57cec5SDimitry Andric       if (got_event) {
49900b57cec5SDimitry Andric         if (event_sp) {
49910b57cec5SDimitry Andric           bool keep_going = false;
49920b57cec5SDimitry Andric           if (event_sp->GetType() == eBroadcastBitInterrupt) {
49930b57cec5SDimitry Andric             const bool clear_thread_plans = false;
49940b57cec5SDimitry Andric             const bool use_run_lock = false;
49950b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
49960b57cec5SDimitry Andric             return_value = eExpressionInterrupted;
49970b57cec5SDimitry Andric             diagnostic_manager.PutString(eDiagnosticSeverityRemark,
49980b57cec5SDimitry Andric                                          "execution halted by user interrupt.");
49999dba64beSDimitry Andric             LLDB_LOGF(log, "Process::RunThreadPlan(): Got  interrupted by "
50000b57cec5SDimitry Andric                            "eBroadcastBitInterrupted, exiting.");
50010b57cec5SDimitry Andric             break;
50020b57cec5SDimitry Andric           } else {
50030b57cec5SDimitry Andric             stop_state =
50040b57cec5SDimitry Andric                 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
50059dba64beSDimitry Andric             LLDB_LOGF(log,
50060b57cec5SDimitry Andric                       "Process::RunThreadPlan(): in while loop, got event: %s.",
50070b57cec5SDimitry Andric                       StateAsCString(stop_state));
50080b57cec5SDimitry Andric 
50090b57cec5SDimitry Andric             switch (stop_state) {
50100b57cec5SDimitry Andric             case lldb::eStateStopped: {
50115ffd83dbSDimitry Andric               if (Process::ProcessEventData::GetRestartedFromEvent(
50120b57cec5SDimitry Andric                       event_sp.get())) {
50130b57cec5SDimitry Andric                 // If we were restarted, we just need to go back up to fetch
50140b57cec5SDimitry Andric                 // another event.
50159dba64beSDimitry Andric                 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
50160b57cec5SDimitry Andric                                "restart, so we'll continue waiting.");
50170b57cec5SDimitry Andric                 keep_going = true;
50180b57cec5SDimitry Andric                 do_resume = false;
50190b57cec5SDimitry Andric                 handle_running_event = true;
50200b57cec5SDimitry Andric               } else {
50210b57cec5SDimitry Andric                 const bool handle_interrupts = true;
50220b57cec5SDimitry Andric                 return_value = *HandleStoppedEvent(
50235ffd83dbSDimitry Andric                     expr_thread_id, thread_plan_sp, thread_plan_restorer,
50245ffd83dbSDimitry Andric                     event_sp, event_to_broadcast_sp, options,
50255ffd83dbSDimitry Andric                     handle_interrupts);
50265ffd83dbSDimitry Andric                 if (return_value == eExpressionThreadVanished)
50275ffd83dbSDimitry Andric                   keep_going = false;
50280b57cec5SDimitry Andric               }
50290b57cec5SDimitry Andric             } break;
50300b57cec5SDimitry Andric 
50310b57cec5SDimitry Andric             case lldb::eStateRunning:
50320b57cec5SDimitry Andric               // This shouldn't really happen, but sometimes we do get two
50330b57cec5SDimitry Andric               // running events without an intervening stop, and in that case
50340b57cec5SDimitry Andric               // we should just go back to waiting for the stop.
50350b57cec5SDimitry Andric               do_resume = false;
50360b57cec5SDimitry Andric               keep_going = true;
50370b57cec5SDimitry Andric               handle_running_event = false;
50380b57cec5SDimitry Andric               break;
50390b57cec5SDimitry Andric 
50400b57cec5SDimitry Andric             default:
50419dba64beSDimitry Andric               LLDB_LOGF(log,
50429dba64beSDimitry Andric                         "Process::RunThreadPlan(): execution stopped with "
50430b57cec5SDimitry Andric                         "unexpected state: %s.",
50440b57cec5SDimitry Andric                         StateAsCString(stop_state));
50450b57cec5SDimitry Andric 
50460b57cec5SDimitry Andric               if (stop_state == eStateExited)
50470b57cec5SDimitry Andric                 event_to_broadcast_sp = event_sp;
50480b57cec5SDimitry Andric 
50490b57cec5SDimitry Andric               diagnostic_manager.PutString(
50500b57cec5SDimitry Andric                   eDiagnosticSeverityError,
50510b57cec5SDimitry Andric                   "execution stopped with unexpected state.");
50520b57cec5SDimitry Andric               return_value = eExpressionInterrupted;
50530b57cec5SDimitry Andric               break;
50540b57cec5SDimitry Andric             }
50550b57cec5SDimitry Andric           }
50560b57cec5SDimitry Andric 
50570b57cec5SDimitry Andric           if (keep_going)
50580b57cec5SDimitry Andric             continue;
50590b57cec5SDimitry Andric           else
50600b57cec5SDimitry Andric             break;
50610b57cec5SDimitry Andric         } else {
50620b57cec5SDimitry Andric           if (log)
50630b57cec5SDimitry Andric             log->PutCString("Process::RunThreadPlan(): got_event was true, but "
50640b57cec5SDimitry Andric                             "the event pointer was null.  How odd...");
50650b57cec5SDimitry Andric           return_value = eExpressionInterrupted;
50660b57cec5SDimitry Andric           break;
50670b57cec5SDimitry Andric         }
50680b57cec5SDimitry Andric       } else {
50690b57cec5SDimitry Andric         // If we didn't get an event that means we've timed out... We will
50700b57cec5SDimitry Andric         // interrupt the process here.  Depending on what we were asked to do
50710b57cec5SDimitry Andric         // we will either exit, or try with all threads running for the same
50720b57cec5SDimitry Andric         // timeout.
50730b57cec5SDimitry Andric 
50740b57cec5SDimitry Andric         if (log) {
50750b57cec5SDimitry Andric           if (options.GetTryAllThreads()) {
50760b57cec5SDimitry Andric             if (before_first_timeout) {
50770b57cec5SDimitry Andric               LLDB_LOG(log,
50780b57cec5SDimitry Andric                        "Running function with one thread timeout timed out.");
50790b57cec5SDimitry Andric             } else
50800b57cec5SDimitry Andric               LLDB_LOG(log, "Restarting function with all threads enabled and "
50810b57cec5SDimitry Andric                             "timeout: {0} timed out, abandoning execution.",
50820b57cec5SDimitry Andric                        timeout);
50830b57cec5SDimitry Andric           } else
50840b57cec5SDimitry Andric             LLDB_LOG(log, "Running function with timeout: {0} timed out, "
50850b57cec5SDimitry Andric                           "abandoning execution.",
50860b57cec5SDimitry Andric                      timeout);
50870b57cec5SDimitry Andric         }
50880b57cec5SDimitry Andric 
50890b57cec5SDimitry Andric         // It is possible that between the time we issued the Halt, and we get
50900b57cec5SDimitry Andric         // around to calling Halt the target could have stopped.  That's fine,
50910b57cec5SDimitry Andric         // Halt will figure that out and send the appropriate Stopped event.
50920b57cec5SDimitry Andric         // BUT it is also possible that we stopped & restarted (e.g. hit a
50930b57cec5SDimitry Andric         // signal with "stop" set to false.)  In
50940b57cec5SDimitry Andric         // that case, we'll get the stopped & restarted event, and we should go
50950b57cec5SDimitry Andric         // back to waiting for the Halt's stopped event.  That's what this
50960b57cec5SDimitry Andric         // while loop does.
50970b57cec5SDimitry Andric 
50980b57cec5SDimitry Andric         bool back_to_top = true;
50990b57cec5SDimitry Andric         uint32_t try_halt_again = 0;
51000b57cec5SDimitry Andric         bool do_halt = true;
51010b57cec5SDimitry Andric         const uint32_t num_retries = 5;
51020b57cec5SDimitry Andric         while (try_halt_again < num_retries) {
51030b57cec5SDimitry Andric           Status halt_error;
51040b57cec5SDimitry Andric           if (do_halt) {
51059dba64beSDimitry Andric             LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
51060b57cec5SDimitry Andric             const bool clear_thread_plans = false;
51070b57cec5SDimitry Andric             const bool use_run_lock = false;
51080b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
51090b57cec5SDimitry Andric           }
51100b57cec5SDimitry Andric           if (halt_error.Success()) {
51110b57cec5SDimitry Andric             if (log)
51120b57cec5SDimitry Andric               log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
51130b57cec5SDimitry Andric 
51140b57cec5SDimitry Andric             got_event =
51150b57cec5SDimitry Andric                 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
51160b57cec5SDimitry Andric 
51170b57cec5SDimitry Andric             if (got_event) {
51180b57cec5SDimitry Andric               stop_state =
51190b57cec5SDimitry Andric                   Process::ProcessEventData::GetStateFromEvent(event_sp.get());
51200b57cec5SDimitry Andric               if (log) {
51219dba64beSDimitry Andric                 LLDB_LOGF(log,
51229dba64beSDimitry Andric                           "Process::RunThreadPlan(): Stopped with event: %s",
51230b57cec5SDimitry Andric                           StateAsCString(stop_state));
51240b57cec5SDimitry Andric                 if (stop_state == lldb::eStateStopped &&
51250b57cec5SDimitry Andric                     Process::ProcessEventData::GetInterruptedFromEvent(
51260b57cec5SDimitry Andric                         event_sp.get()))
51270b57cec5SDimitry Andric                   log->PutCString("    Event was the Halt interruption event.");
51280b57cec5SDimitry Andric               }
51290b57cec5SDimitry Andric 
51300b57cec5SDimitry Andric               if (stop_state == lldb::eStateStopped) {
51310b57cec5SDimitry Andric                 if (Process::ProcessEventData::GetRestartedFromEvent(
51320b57cec5SDimitry Andric                         event_sp.get())) {
51330b57cec5SDimitry Andric                   if (log)
51340b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): Went to halt "
51350b57cec5SDimitry Andric                                     "but got a restarted event, there must be "
51360b57cec5SDimitry Andric                                     "an un-restarted stopped event so try "
51370b57cec5SDimitry Andric                                     "again...  "
51380b57cec5SDimitry Andric                                     "Exiting wait loop.");
51390b57cec5SDimitry Andric                   try_halt_again++;
51400b57cec5SDimitry Andric                   do_halt = false;
51410b57cec5SDimitry Andric                   continue;
51420b57cec5SDimitry Andric                 }
51430b57cec5SDimitry Andric 
51440b57cec5SDimitry Andric                 // Between the time we initiated the Halt and the time we
51450b57cec5SDimitry Andric                 // delivered it, the process could have already finished its
51460b57cec5SDimitry Andric                 // job.  Check that here:
51470b57cec5SDimitry Andric                 const bool handle_interrupts = false;
51480b57cec5SDimitry Andric                 if (auto result = HandleStoppedEvent(
51495ffd83dbSDimitry Andric                         expr_thread_id, thread_plan_sp, thread_plan_restorer,
51505ffd83dbSDimitry Andric                         event_sp, event_to_broadcast_sp, options,
51515ffd83dbSDimitry Andric                         handle_interrupts)) {
51520b57cec5SDimitry Andric                   return_value = *result;
51530b57cec5SDimitry Andric                   back_to_top = false;
51540b57cec5SDimitry Andric                   break;
51550b57cec5SDimitry Andric                 }
51560b57cec5SDimitry Andric 
51570b57cec5SDimitry Andric                 if (!options.GetTryAllThreads()) {
51580b57cec5SDimitry Andric                   if (log)
51590b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): try_all_threads "
51600b57cec5SDimitry Andric                                     "was false, we stopped so now we're "
51610b57cec5SDimitry Andric                                     "quitting.");
51620b57cec5SDimitry Andric                   return_value = eExpressionInterrupted;
51630b57cec5SDimitry Andric                   back_to_top = false;
51640b57cec5SDimitry Andric                   break;
51650b57cec5SDimitry Andric                 }
51660b57cec5SDimitry Andric 
51670b57cec5SDimitry Andric                 if (before_first_timeout) {
51680b57cec5SDimitry Andric                   // Set all the other threads to run, and return to the top of
51690b57cec5SDimitry Andric                   // the loop, which will continue;
51700b57cec5SDimitry Andric                   before_first_timeout = false;
51710b57cec5SDimitry Andric                   thread_plan_sp->SetStopOthers(false);
51720b57cec5SDimitry Andric                   if (log)
51730b57cec5SDimitry Andric                     log->PutCString(
51740b57cec5SDimitry Andric                         "Process::RunThreadPlan(): about to resume.");
51750b57cec5SDimitry Andric 
51760b57cec5SDimitry Andric                   back_to_top = true;
51770b57cec5SDimitry Andric                   break;
51780b57cec5SDimitry Andric                 } else {
51790b57cec5SDimitry Andric                   // Running all threads failed, so return Interrupted.
51800b57cec5SDimitry Andric                   if (log)
51810b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): running all "
51820b57cec5SDimitry Andric                                     "threads timed out.");
51830b57cec5SDimitry Andric                   return_value = eExpressionInterrupted;
51840b57cec5SDimitry Andric                   back_to_top = false;
51850b57cec5SDimitry Andric                   break;
51860b57cec5SDimitry Andric                 }
51870b57cec5SDimitry Andric               }
51880b57cec5SDimitry Andric             } else {
51890b57cec5SDimitry Andric               if (log)
51900b57cec5SDimitry Andric                 log->PutCString("Process::RunThreadPlan(): halt said it "
51910b57cec5SDimitry Andric                                 "succeeded, but I got no event.  "
51920b57cec5SDimitry Andric                                 "I'm getting out of here passing Interrupted.");
51930b57cec5SDimitry Andric               return_value = eExpressionInterrupted;
51940b57cec5SDimitry Andric               back_to_top = false;
51950b57cec5SDimitry Andric               break;
51960b57cec5SDimitry Andric             }
51970b57cec5SDimitry Andric           } else {
51980b57cec5SDimitry Andric             try_halt_again++;
51990b57cec5SDimitry Andric             continue;
52000b57cec5SDimitry Andric           }
52010b57cec5SDimitry Andric         }
52020b57cec5SDimitry Andric 
52030b57cec5SDimitry Andric         if (!back_to_top || try_halt_again > num_retries)
52040b57cec5SDimitry Andric           break;
52050b57cec5SDimitry Andric         else
52060b57cec5SDimitry Andric           continue;
52070b57cec5SDimitry Andric       }
52080b57cec5SDimitry Andric     } // END WAIT LOOP
52090b57cec5SDimitry Andric 
52100b57cec5SDimitry Andric     // If we had to start up a temporary private state thread to run this
52110b57cec5SDimitry Andric     // thread plan, shut it down now.
52120b57cec5SDimitry Andric     if (backup_private_state_thread.IsJoinable()) {
52130b57cec5SDimitry Andric       StopPrivateStateThread();
52140b57cec5SDimitry Andric       Status error;
52150b57cec5SDimitry Andric       m_private_state_thread = backup_private_state_thread;
52160b57cec5SDimitry Andric       if (stopper_base_plan_sp) {
52170b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
52180b57cec5SDimitry Andric       }
52190b57cec5SDimitry Andric       if (old_state != eStateInvalid)
52200b57cec5SDimitry Andric         m_public_state.SetValueNoLock(old_state);
52210b57cec5SDimitry Andric     }
52220b57cec5SDimitry Andric 
52235ffd83dbSDimitry Andric     // If our thread went away on us, we need to get out of here without
52245ffd83dbSDimitry Andric     // doing any more work.  We don't have to clean up the thread plan, that
52255ffd83dbSDimitry Andric     // will have happened when the Thread was destroyed.
52265ffd83dbSDimitry Andric     if (return_value == eExpressionThreadVanished) {
52275ffd83dbSDimitry Andric       return return_value;
52285ffd83dbSDimitry Andric     }
52295ffd83dbSDimitry Andric 
52300b57cec5SDimitry Andric     if (return_value != eExpressionCompleted && log) {
52310b57cec5SDimitry Andric       // Print a backtrace into the log so we can figure out where we are:
52320b57cec5SDimitry Andric       StreamString s;
52330b57cec5SDimitry Andric       s.PutCString("Thread state after unsuccessful completion: \n");
52340b57cec5SDimitry Andric       thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
52350b57cec5SDimitry Andric       log->PutString(s.GetString());
52360b57cec5SDimitry Andric     }
52370b57cec5SDimitry Andric     // Restore the thread state if we are going to discard the plan execution.
52380b57cec5SDimitry Andric     // There are three cases where this could happen: 1) The execution
52390b57cec5SDimitry Andric     // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
52400b57cec5SDimitry Andric     // was true 3) We got some other error, and discard_on_error was true
52410b57cec5SDimitry Andric     bool should_unwind = (return_value == eExpressionInterrupted &&
52420b57cec5SDimitry Andric                           options.DoesUnwindOnError()) ||
52430b57cec5SDimitry Andric                          (return_value == eExpressionHitBreakpoint &&
52440b57cec5SDimitry Andric                           options.DoesIgnoreBreakpoints());
52450b57cec5SDimitry Andric 
52460b57cec5SDimitry Andric     if (return_value == eExpressionCompleted || should_unwind) {
52470b57cec5SDimitry Andric       thread_plan_sp->RestoreThreadState();
52480b57cec5SDimitry Andric     }
52490b57cec5SDimitry Andric 
52500b57cec5SDimitry Andric     // Now do some processing on the results of the run:
52510b57cec5SDimitry Andric     if (return_value == eExpressionInterrupted ||
52520b57cec5SDimitry Andric         return_value == eExpressionHitBreakpoint) {
52530b57cec5SDimitry Andric       if (log) {
52540b57cec5SDimitry Andric         StreamString s;
52550b57cec5SDimitry Andric         if (event_sp)
52560b57cec5SDimitry Andric           event_sp->Dump(&s);
52570b57cec5SDimitry Andric         else {
52580b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): Stop event that "
52590b57cec5SDimitry Andric                           "interrupted us is NULL.");
52600b57cec5SDimitry Andric         }
52610b57cec5SDimitry Andric 
52620b57cec5SDimitry Andric         StreamString ts;
52630b57cec5SDimitry Andric 
52640b57cec5SDimitry Andric         const char *event_explanation = nullptr;
52650b57cec5SDimitry Andric 
52660b57cec5SDimitry Andric         do {
52670b57cec5SDimitry Andric           if (!event_sp) {
52680b57cec5SDimitry Andric             event_explanation = "<no event>";
52690b57cec5SDimitry Andric             break;
52700b57cec5SDimitry Andric           } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
52710b57cec5SDimitry Andric             event_explanation = "<user interrupt>";
52720b57cec5SDimitry Andric             break;
52730b57cec5SDimitry Andric           } else {
52740b57cec5SDimitry Andric             const Process::ProcessEventData *event_data =
52750b57cec5SDimitry Andric                 Process::ProcessEventData::GetEventDataFromEvent(
52760b57cec5SDimitry Andric                     event_sp.get());
52770b57cec5SDimitry Andric 
52780b57cec5SDimitry Andric             if (!event_data) {
52790b57cec5SDimitry Andric               event_explanation = "<no event data>";
52800b57cec5SDimitry Andric               break;
52810b57cec5SDimitry Andric             }
52820b57cec5SDimitry Andric 
52830b57cec5SDimitry Andric             Process *process = event_data->GetProcessSP().get();
52840b57cec5SDimitry Andric 
52850b57cec5SDimitry Andric             if (!process) {
52860b57cec5SDimitry Andric               event_explanation = "<no process>";
52870b57cec5SDimitry Andric               break;
52880b57cec5SDimitry Andric             }
52890b57cec5SDimitry Andric 
52900b57cec5SDimitry Andric             ThreadList &thread_list = process->GetThreadList();
52910b57cec5SDimitry Andric 
52920b57cec5SDimitry Andric             uint32_t num_threads = thread_list.GetSize();
52930b57cec5SDimitry Andric             uint32_t thread_index;
52940b57cec5SDimitry Andric 
52950b57cec5SDimitry Andric             ts.Printf("<%u threads> ", num_threads);
52960b57cec5SDimitry Andric 
52970b57cec5SDimitry Andric             for (thread_index = 0; thread_index < num_threads; ++thread_index) {
52980b57cec5SDimitry Andric               Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
52990b57cec5SDimitry Andric 
53000b57cec5SDimitry Andric               if (!thread) {
53010b57cec5SDimitry Andric                 ts.Printf("<?> ");
53020b57cec5SDimitry Andric                 continue;
53030b57cec5SDimitry Andric               }
53040b57cec5SDimitry Andric 
53050b57cec5SDimitry Andric               ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
53060b57cec5SDimitry Andric               RegisterContext *register_context =
53070b57cec5SDimitry Andric                   thread->GetRegisterContext().get();
53080b57cec5SDimitry Andric 
53090b57cec5SDimitry Andric               if (register_context)
53100b57cec5SDimitry Andric                 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
53110b57cec5SDimitry Andric               else
53120b57cec5SDimitry Andric                 ts.Printf("[ip unknown] ");
53130b57cec5SDimitry Andric 
53140b57cec5SDimitry Andric               // Show the private stop info here, the public stop info will be
53150b57cec5SDimitry Andric               // from the last natural stop.
53160b57cec5SDimitry Andric               lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
53170b57cec5SDimitry Andric               if (stop_info_sp) {
53180b57cec5SDimitry Andric                 const char *stop_desc = stop_info_sp->GetDescription();
53190b57cec5SDimitry Andric                 if (stop_desc)
53200b57cec5SDimitry Andric                   ts.PutCString(stop_desc);
53210b57cec5SDimitry Andric               }
53220b57cec5SDimitry Andric               ts.Printf(">");
53230b57cec5SDimitry Andric             }
53240b57cec5SDimitry Andric 
53250b57cec5SDimitry Andric             event_explanation = ts.GetData();
53260b57cec5SDimitry Andric           }
53270b57cec5SDimitry Andric         } while (false);
53280b57cec5SDimitry Andric 
53290b57cec5SDimitry Andric         if (event_explanation)
53309dba64beSDimitry Andric           LLDB_LOGF(log,
53319dba64beSDimitry Andric                     "Process::RunThreadPlan(): execution interrupted: %s %s",
53320b57cec5SDimitry Andric                     s.GetData(), event_explanation);
53330b57cec5SDimitry Andric         else
53349dba64beSDimitry Andric           LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
53350b57cec5SDimitry Andric                     s.GetData());
53360b57cec5SDimitry Andric       }
53370b57cec5SDimitry Andric 
53380b57cec5SDimitry Andric       if (should_unwind) {
53399dba64beSDimitry Andric         LLDB_LOGF(log,
53409dba64beSDimitry Andric                   "Process::RunThreadPlan: ExecutionInterrupted - "
53410b57cec5SDimitry Andric                   "discarding thread plans up to %p.",
53420b57cec5SDimitry Andric                   static_cast<void *>(thread_plan_sp.get()));
53430b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
53440b57cec5SDimitry Andric       } else {
53459dba64beSDimitry Andric         LLDB_LOGF(log,
53469dba64beSDimitry Andric                   "Process::RunThreadPlan: ExecutionInterrupted - for "
53470b57cec5SDimitry Andric                   "plan: %p not discarding.",
53480b57cec5SDimitry Andric                   static_cast<void *>(thread_plan_sp.get()));
53490b57cec5SDimitry Andric       }
53500b57cec5SDimitry Andric     } else if (return_value == eExpressionSetupError) {
53510b57cec5SDimitry Andric       if (log)
53520b57cec5SDimitry Andric         log->PutCString("Process::RunThreadPlan(): execution set up error.");
53530b57cec5SDimitry Andric 
53540b57cec5SDimitry Andric       if (options.DoesUnwindOnError()) {
53550b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
53560b57cec5SDimitry Andric       }
53570b57cec5SDimitry Andric     } else {
53580b57cec5SDimitry Andric       if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
53590b57cec5SDimitry Andric         if (log)
53600b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): thread plan is done");
53610b57cec5SDimitry Andric         return_value = eExpressionCompleted;
53620b57cec5SDimitry Andric       } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
53630b57cec5SDimitry Andric         if (log)
53640b57cec5SDimitry Andric           log->PutCString(
53650b57cec5SDimitry Andric               "Process::RunThreadPlan(): thread plan was discarded");
53660b57cec5SDimitry Andric         return_value = eExpressionDiscarded;
53670b57cec5SDimitry Andric       } else {
53680b57cec5SDimitry Andric         if (log)
53690b57cec5SDimitry Andric           log->PutCString(
53700b57cec5SDimitry Andric               "Process::RunThreadPlan(): thread plan stopped in mid course");
53710b57cec5SDimitry Andric         if (options.DoesUnwindOnError() && thread_plan_sp) {
53720b57cec5SDimitry Andric           if (log)
53730b57cec5SDimitry Andric             log->PutCString("Process::RunThreadPlan(): discarding thread plan "
53740b57cec5SDimitry Andric                             "'cause unwind_on_error is set.");
53750b57cec5SDimitry Andric           thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
53760b57cec5SDimitry Andric         }
53770b57cec5SDimitry Andric       }
53780b57cec5SDimitry Andric     }
53790b57cec5SDimitry Andric 
53800b57cec5SDimitry Andric     // Thread we ran the function in may have gone away because we ran the
53810b57cec5SDimitry Andric     // target Check that it's still there, and if it is put it back in the
53820b57cec5SDimitry Andric     // context. Also restore the frame in the context if it is still present.
53830b57cec5SDimitry Andric     thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
53840b57cec5SDimitry Andric     if (thread) {
53850b57cec5SDimitry Andric       exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
53860b57cec5SDimitry Andric     }
53870b57cec5SDimitry Andric 
53880b57cec5SDimitry Andric     // Also restore the current process'es selected frame & thread, since this
53890b57cec5SDimitry Andric     // function calling may be done behind the user's back.
53900b57cec5SDimitry Andric 
53910b57cec5SDimitry Andric     if (selected_tid != LLDB_INVALID_THREAD_ID) {
53920b57cec5SDimitry Andric       if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
53930b57cec5SDimitry Andric           selected_stack_id.IsValid()) {
53940b57cec5SDimitry Andric         // We were able to restore the selected thread, now restore the frame:
53950b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
53960b57cec5SDimitry Andric         StackFrameSP old_frame_sp =
53970b57cec5SDimitry Andric             GetThreadList().GetSelectedThread()->GetFrameWithStackID(
53980b57cec5SDimitry Andric                 selected_stack_id);
53990b57cec5SDimitry Andric         if (old_frame_sp)
54000b57cec5SDimitry Andric           GetThreadList().GetSelectedThread()->SetSelectedFrame(
54010b57cec5SDimitry Andric               old_frame_sp.get());
54020b57cec5SDimitry Andric       }
54030b57cec5SDimitry Andric     }
54040b57cec5SDimitry Andric   }
54050b57cec5SDimitry Andric 
54060b57cec5SDimitry Andric   // If the process exited during the run of the thread plan, notify everyone.
54070b57cec5SDimitry Andric 
54080b57cec5SDimitry Andric   if (event_to_broadcast_sp) {
54090b57cec5SDimitry Andric     if (log)
54100b57cec5SDimitry Andric       log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
54110b57cec5SDimitry Andric     BroadcastEvent(event_to_broadcast_sp);
54120b57cec5SDimitry Andric   }
54130b57cec5SDimitry Andric 
54140b57cec5SDimitry Andric   return return_value;
54150b57cec5SDimitry Andric }
54160b57cec5SDimitry Andric 
ExecutionResultAsCString(ExpressionResults result)54170b57cec5SDimitry Andric const char *Process::ExecutionResultAsCString(ExpressionResults result) {
54185ffd83dbSDimitry Andric   const char *result_name = "<unknown>";
54190b57cec5SDimitry Andric 
54200b57cec5SDimitry Andric   switch (result) {
54210b57cec5SDimitry Andric   case eExpressionCompleted:
54220b57cec5SDimitry Andric     result_name = "eExpressionCompleted";
54230b57cec5SDimitry Andric     break;
54240b57cec5SDimitry Andric   case eExpressionDiscarded:
54250b57cec5SDimitry Andric     result_name = "eExpressionDiscarded";
54260b57cec5SDimitry Andric     break;
54270b57cec5SDimitry Andric   case eExpressionInterrupted:
54280b57cec5SDimitry Andric     result_name = "eExpressionInterrupted";
54290b57cec5SDimitry Andric     break;
54300b57cec5SDimitry Andric   case eExpressionHitBreakpoint:
54310b57cec5SDimitry Andric     result_name = "eExpressionHitBreakpoint";
54320b57cec5SDimitry Andric     break;
54330b57cec5SDimitry Andric   case eExpressionSetupError:
54340b57cec5SDimitry Andric     result_name = "eExpressionSetupError";
54350b57cec5SDimitry Andric     break;
54360b57cec5SDimitry Andric   case eExpressionParseError:
54370b57cec5SDimitry Andric     result_name = "eExpressionParseError";
54380b57cec5SDimitry Andric     break;
54390b57cec5SDimitry Andric   case eExpressionResultUnavailable:
54400b57cec5SDimitry Andric     result_name = "eExpressionResultUnavailable";
54410b57cec5SDimitry Andric     break;
54420b57cec5SDimitry Andric   case eExpressionTimedOut:
54430b57cec5SDimitry Andric     result_name = "eExpressionTimedOut";
54440b57cec5SDimitry Andric     break;
54450b57cec5SDimitry Andric   case eExpressionStoppedForDebug:
54460b57cec5SDimitry Andric     result_name = "eExpressionStoppedForDebug";
54470b57cec5SDimitry Andric     break;
54485ffd83dbSDimitry Andric   case eExpressionThreadVanished:
54495ffd83dbSDimitry Andric     result_name = "eExpressionThreadVanished";
54500b57cec5SDimitry Andric   }
54510b57cec5SDimitry Andric   return result_name;
54520b57cec5SDimitry Andric }
54530b57cec5SDimitry Andric 
GetStatus(Stream & strm)54540b57cec5SDimitry Andric void Process::GetStatus(Stream &strm) {
54550b57cec5SDimitry Andric   const StateType state = GetState();
54560b57cec5SDimitry Andric   if (StateIsStoppedState(state, false)) {
54570b57cec5SDimitry Andric     if (state == eStateExited) {
54580b57cec5SDimitry Andric       int exit_status = GetExitStatus();
54590b57cec5SDimitry Andric       const char *exit_description = GetExitDescription();
54600b57cec5SDimitry Andric       strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
54610b57cec5SDimitry Andric                   GetID(), exit_status, exit_status,
54620b57cec5SDimitry Andric                   exit_description ? exit_description : "");
54630b57cec5SDimitry Andric     } else {
54640b57cec5SDimitry Andric       if (state == eStateConnected)
54650b57cec5SDimitry Andric         strm.Printf("Connected to remote target.\n");
54660b57cec5SDimitry Andric       else
54670b57cec5SDimitry Andric         strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
54680b57cec5SDimitry Andric     }
54690b57cec5SDimitry Andric   } else {
54700b57cec5SDimitry Andric     strm.Printf("Process %" PRIu64 " is running.\n", GetID());
54710b57cec5SDimitry Andric   }
54720b57cec5SDimitry Andric }
54730b57cec5SDimitry Andric 
GetThreadStatus(Stream & strm,bool only_threads_with_stop_reason,uint32_t start_frame,uint32_t num_frames,uint32_t num_frames_with_source,bool stop_format)54740b57cec5SDimitry Andric size_t Process::GetThreadStatus(Stream &strm,
54750b57cec5SDimitry Andric                                 bool only_threads_with_stop_reason,
54760b57cec5SDimitry Andric                                 uint32_t start_frame, uint32_t num_frames,
54770b57cec5SDimitry Andric                                 uint32_t num_frames_with_source,
54780b57cec5SDimitry Andric                                 bool stop_format) {
54790b57cec5SDimitry Andric   size_t num_thread_infos_dumped = 0;
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric   // You can't hold the thread list lock while calling Thread::GetStatus.  That
54820b57cec5SDimitry Andric   // very well might run code (e.g. if we need it to get return values or
54830b57cec5SDimitry Andric   // arguments.)  For that to work the process has to be able to acquire it.
54840b57cec5SDimitry Andric   // So instead copy the thread ID's, and look them up one by one:
54850b57cec5SDimitry Andric 
54860b57cec5SDimitry Andric   uint32_t num_threads;
54870b57cec5SDimitry Andric   std::vector<lldb::tid_t> thread_id_array;
54880b57cec5SDimitry Andric   // Scope for thread list locker;
54890b57cec5SDimitry Andric   {
54900b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
54910b57cec5SDimitry Andric     ThreadList &curr_thread_list = GetThreadList();
54920b57cec5SDimitry Andric     num_threads = curr_thread_list.GetSize();
54930b57cec5SDimitry Andric     uint32_t idx;
54940b57cec5SDimitry Andric     thread_id_array.resize(num_threads);
54950b57cec5SDimitry Andric     for (idx = 0; idx < num_threads; ++idx)
54960b57cec5SDimitry Andric       thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
54970b57cec5SDimitry Andric   }
54980b57cec5SDimitry Andric 
54990b57cec5SDimitry Andric   for (uint32_t i = 0; i < num_threads; i++) {
55000b57cec5SDimitry Andric     ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
55010b57cec5SDimitry Andric     if (thread_sp) {
55020b57cec5SDimitry Andric       if (only_threads_with_stop_reason) {
55030b57cec5SDimitry Andric         StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
55040b57cec5SDimitry Andric         if (!stop_info_sp || !stop_info_sp->IsValid())
55050b57cec5SDimitry Andric           continue;
55060b57cec5SDimitry Andric       }
55070b57cec5SDimitry Andric       thread_sp->GetStatus(strm, start_frame, num_frames,
55080b57cec5SDimitry Andric                            num_frames_with_source,
55090b57cec5SDimitry Andric                            stop_format);
55100b57cec5SDimitry Andric       ++num_thread_infos_dumped;
55110b57cec5SDimitry Andric     } else {
55120b57cec5SDimitry Andric       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
55139dba64beSDimitry Andric       LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
55140b57cec5SDimitry Andric                      " vanished while running Thread::GetStatus.");
55150b57cec5SDimitry Andric     }
55160b57cec5SDimitry Andric   }
55170b57cec5SDimitry Andric   return num_thread_infos_dumped;
55180b57cec5SDimitry Andric }
55190b57cec5SDimitry Andric 
AddInvalidMemoryRegion(const LoadRange & region)55200b57cec5SDimitry Andric void Process::AddInvalidMemoryRegion(const LoadRange &region) {
55210b57cec5SDimitry Andric   m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
55220b57cec5SDimitry Andric }
55230b57cec5SDimitry Andric 
RemoveInvalidMemoryRange(const LoadRange & region)55240b57cec5SDimitry Andric bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
55250b57cec5SDimitry Andric   return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
55260b57cec5SDimitry Andric                                            region.GetByteSize());
55270b57cec5SDimitry Andric }
55280b57cec5SDimitry Andric 
AddPreResumeAction(PreResumeActionCallback callback,void * baton)55290b57cec5SDimitry Andric void Process::AddPreResumeAction(PreResumeActionCallback callback,
55300b57cec5SDimitry Andric                                  void *baton) {
55310b57cec5SDimitry Andric   m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
55320b57cec5SDimitry Andric }
55330b57cec5SDimitry Andric 
RunPreResumeActions()55340b57cec5SDimitry Andric bool Process::RunPreResumeActions() {
55350b57cec5SDimitry Andric   bool result = true;
55360b57cec5SDimitry Andric   while (!m_pre_resume_actions.empty()) {
55370b57cec5SDimitry Andric     struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
55380b57cec5SDimitry Andric     m_pre_resume_actions.pop_back();
55390b57cec5SDimitry Andric     bool this_result = action.callback(action.baton);
55400b57cec5SDimitry Andric     if (result)
55410b57cec5SDimitry Andric       result = this_result;
55420b57cec5SDimitry Andric   }
55430b57cec5SDimitry Andric   return result;
55440b57cec5SDimitry Andric }
55450b57cec5SDimitry Andric 
ClearPreResumeActions()55460b57cec5SDimitry Andric void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
55470b57cec5SDimitry Andric 
ClearPreResumeAction(PreResumeActionCallback callback,void * baton)55480b57cec5SDimitry Andric void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
55490b57cec5SDimitry Andric {
55500b57cec5SDimitry Andric     PreResumeCallbackAndBaton element(callback, baton);
55510b57cec5SDimitry Andric     auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
55520b57cec5SDimitry Andric     if (found_iter != m_pre_resume_actions.end())
55530b57cec5SDimitry Andric     {
55540b57cec5SDimitry Andric         m_pre_resume_actions.erase(found_iter);
55550b57cec5SDimitry Andric     }
55560b57cec5SDimitry Andric }
55570b57cec5SDimitry Andric 
GetRunLock()55580b57cec5SDimitry Andric ProcessRunLock &Process::GetRunLock() {
55590b57cec5SDimitry Andric   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
55600b57cec5SDimitry Andric     return m_private_run_lock;
55610b57cec5SDimitry Andric   else
55620b57cec5SDimitry Andric     return m_public_run_lock;
55630b57cec5SDimitry Andric }
55640b57cec5SDimitry Andric 
CurrentThreadIsPrivateStateThread()55659dba64beSDimitry Andric bool Process::CurrentThreadIsPrivateStateThread()
55669dba64beSDimitry Andric {
55679dba64beSDimitry Andric   return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
55689dba64beSDimitry Andric }
55699dba64beSDimitry Andric 
55709dba64beSDimitry Andric 
Flush()55710b57cec5SDimitry Andric void Process::Flush() {
55720b57cec5SDimitry Andric   m_thread_list.Flush();
55730b57cec5SDimitry Andric   m_extended_thread_list.Flush();
55740b57cec5SDimitry Andric   m_extended_thread_stop_id = 0;
55750b57cec5SDimitry Andric   m_queue_list.Clear();
55760b57cec5SDimitry Andric   m_queue_list_stop_id = 0;
55770b57cec5SDimitry Andric }
55780b57cec5SDimitry Andric 
GetCodeAddressMask()5579*5f7ddb14SDimitry Andric lldb::addr_t Process::GetCodeAddressMask() {
5580*5f7ddb14SDimitry Andric   if (m_code_address_mask == 0) {
5581*5f7ddb14SDimitry Andric     if (uint32_t number_of_addressable_bits = GetVirtualAddressableBits()) {
5582*5f7ddb14SDimitry Andric       lldb::addr_t address_mask = ~((1ULL << number_of_addressable_bits) - 1);
5583*5f7ddb14SDimitry Andric       SetCodeAddressMask(address_mask);
5584*5f7ddb14SDimitry Andric     }
5585*5f7ddb14SDimitry Andric   }
5586*5f7ddb14SDimitry Andric   return m_code_address_mask;
5587*5f7ddb14SDimitry Andric }
5588*5f7ddb14SDimitry Andric 
GetDataAddressMask()5589*5f7ddb14SDimitry Andric lldb::addr_t Process::GetDataAddressMask() {
5590*5f7ddb14SDimitry Andric   if (m_data_address_mask == 0) {
5591*5f7ddb14SDimitry Andric     if (uint32_t number_of_addressable_bits = GetVirtualAddressableBits()) {
5592*5f7ddb14SDimitry Andric       lldb::addr_t address_mask = ~((1ULL << number_of_addressable_bits) - 1);
5593*5f7ddb14SDimitry Andric       SetDataAddressMask(address_mask);
5594*5f7ddb14SDimitry Andric     }
5595*5f7ddb14SDimitry Andric   }
5596*5f7ddb14SDimitry Andric   return m_data_address_mask;
5597*5f7ddb14SDimitry Andric }
5598*5f7ddb14SDimitry Andric 
DidExec()55990b57cec5SDimitry Andric void Process::DidExec() {
56000b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
56019dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
56020b57cec5SDimitry Andric 
56030b57cec5SDimitry Andric   Target &target = GetTarget();
56040b57cec5SDimitry Andric   target.CleanupProcess();
56050b57cec5SDimitry Andric   target.ClearModules(false);
56060b57cec5SDimitry Andric   m_dynamic_checkers_up.reset();
56070b57cec5SDimitry Andric   m_abi_sp.reset();
56080b57cec5SDimitry Andric   m_system_runtime_up.reset();
56090b57cec5SDimitry Andric   m_os_up.reset();
56100b57cec5SDimitry Andric   m_dyld_up.reset();
56110b57cec5SDimitry Andric   m_jit_loaders_up.reset();
56120b57cec5SDimitry Andric   m_image_tokens.clear();
56130b57cec5SDimitry Andric   m_allocated_memory_cache.Clear();
56140b57cec5SDimitry Andric   {
56150b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
56160b57cec5SDimitry Andric     m_language_runtimes.clear();
56170b57cec5SDimitry Andric   }
56180b57cec5SDimitry Andric   m_instrumentation_runtimes.clear();
56190b57cec5SDimitry Andric   m_thread_list.DiscardThreadPlans();
56200b57cec5SDimitry Andric   m_memory_cache.Clear(true);
56210b57cec5SDimitry Andric   DoDidExec();
56220b57cec5SDimitry Andric   CompleteAttach();
56230b57cec5SDimitry Andric   // Flush the process (threads and all stack frames) after running
56240b57cec5SDimitry Andric   // CompleteAttach() in case the dynamic loader loaded things in new
56250b57cec5SDimitry Andric   // locations.
56260b57cec5SDimitry Andric   Flush();
56270b57cec5SDimitry Andric 
56280b57cec5SDimitry Andric   // After we figure out what was loaded/unloaded in CompleteAttach, we need to
56290b57cec5SDimitry Andric   // let the target know so it can do any cleanup it needs to.
56300b57cec5SDimitry Andric   target.DidExec();
56310b57cec5SDimitry Andric }
56320b57cec5SDimitry Andric 
ResolveIndirectFunction(const Address * address,Status & error)56330b57cec5SDimitry Andric addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
56340b57cec5SDimitry Andric   if (address == nullptr) {
56350b57cec5SDimitry Andric     error.SetErrorString("Invalid address argument");
56360b57cec5SDimitry Andric     return LLDB_INVALID_ADDRESS;
56370b57cec5SDimitry Andric   }
56380b57cec5SDimitry Andric 
56390b57cec5SDimitry Andric   addr_t function_addr = LLDB_INVALID_ADDRESS;
56400b57cec5SDimitry Andric 
56410b57cec5SDimitry Andric   addr_t addr = address->GetLoadAddress(&GetTarget());
56420b57cec5SDimitry Andric   std::map<addr_t, addr_t>::const_iterator iter =
56430b57cec5SDimitry Andric       m_resolved_indirect_addresses.find(addr);
56440b57cec5SDimitry Andric   if (iter != m_resolved_indirect_addresses.end()) {
56450b57cec5SDimitry Andric     function_addr = (*iter).second;
56460b57cec5SDimitry Andric   } else {
56479dba64beSDimitry Andric     if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
56480b57cec5SDimitry Andric       Symbol *symbol = address->CalculateSymbolContextSymbol();
56490b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
56500b57cec5SDimitry Andric           "Unable to call resolver for indirect function %s",
56510b57cec5SDimitry Andric           symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
56520b57cec5SDimitry Andric       function_addr = LLDB_INVALID_ADDRESS;
56530b57cec5SDimitry Andric     } else {
5654*5f7ddb14SDimitry Andric       if (ABISP abi_sp = GetABI())
5655*5f7ddb14SDimitry Andric         function_addr = abi_sp->FixCodeAddress(function_addr);
56560b57cec5SDimitry Andric       m_resolved_indirect_addresses.insert(
56570b57cec5SDimitry Andric           std::pair<addr_t, addr_t>(addr, function_addr));
56580b57cec5SDimitry Andric     }
56590b57cec5SDimitry Andric   }
56600b57cec5SDimitry Andric   return function_addr;
56610b57cec5SDimitry Andric }
56620b57cec5SDimitry Andric 
ModulesDidLoad(ModuleList & module_list)56630b57cec5SDimitry Andric void Process::ModulesDidLoad(ModuleList &module_list) {
5664af732203SDimitry Andric   // Inform the system runtime of the modified modules.
56650b57cec5SDimitry Andric   SystemRuntime *sys_runtime = GetSystemRuntime();
5666af732203SDimitry Andric   if (sys_runtime)
56670b57cec5SDimitry Andric     sys_runtime->ModulesDidLoad(module_list);
56680b57cec5SDimitry Andric 
56690b57cec5SDimitry Andric   GetJITLoaders().ModulesDidLoad(module_list);
56700b57cec5SDimitry Andric 
5671af732203SDimitry Andric   // Give the instrumentation runtimes a chance to be created before informing
5672af732203SDimitry Andric   // them of the modified modules.
56730b57cec5SDimitry Andric   InstrumentationRuntime::ModulesDidLoad(module_list, this,
56740b57cec5SDimitry Andric                                          m_instrumentation_runtimes);
5675af732203SDimitry Andric   for (auto &runtime : m_instrumentation_runtimes)
5676af732203SDimitry Andric     runtime.second->ModulesDidLoad(module_list);
56770b57cec5SDimitry Andric 
5678af732203SDimitry Andric   // Give the language runtimes a chance to be created before informing them of
5679af732203SDimitry Andric   // the modified modules.
5680af732203SDimitry Andric   for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
5681af732203SDimitry Andric     if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
56820b57cec5SDimitry Andric       runtime->ModulesDidLoad(module_list);
56830b57cec5SDimitry Andric   }
56840b57cec5SDimitry Andric 
56850b57cec5SDimitry Andric   // If we don't have an operating system plug-in, try to load one since
56860b57cec5SDimitry Andric   // loading shared libraries might cause a new one to try and load
56870b57cec5SDimitry Andric   if (!m_os_up)
56880b57cec5SDimitry Andric     LoadOperatingSystemPlugin(false);
56890b57cec5SDimitry Andric 
5690af732203SDimitry Andric   // Inform the structured-data plugins of the modified modules.
56910b57cec5SDimitry Andric   for (auto pair : m_structured_data_plugin_map) {
56920b57cec5SDimitry Andric     if (pair.second)
56930b57cec5SDimitry Andric       pair.second->ModulesDidLoad(*this, module_list);
56940b57cec5SDimitry Andric   }
56950b57cec5SDimitry Andric }
56960b57cec5SDimitry Andric 
PrintWarning(uint64_t warning_type,const void * repeat_key,const char * fmt,...)56970b57cec5SDimitry Andric void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
56980b57cec5SDimitry Andric                            const char *fmt, ...) {
56990b57cec5SDimitry Andric   bool print_warning = true;
57000b57cec5SDimitry Andric 
57010b57cec5SDimitry Andric   StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
57020b57cec5SDimitry Andric   if (!stream_sp)
57030b57cec5SDimitry Andric     return;
57040b57cec5SDimitry Andric 
57050b57cec5SDimitry Andric   if (repeat_key != nullptr) {
57060b57cec5SDimitry Andric     WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
57070b57cec5SDimitry Andric     if (it == m_warnings_issued.end()) {
57080b57cec5SDimitry Andric       m_warnings_issued[warning_type] = WarningsPointerSet();
57090b57cec5SDimitry Andric       m_warnings_issued[warning_type].insert(repeat_key);
57100b57cec5SDimitry Andric     } else {
57110b57cec5SDimitry Andric       if (it->second.find(repeat_key) != it->second.end()) {
57120b57cec5SDimitry Andric         print_warning = false;
57130b57cec5SDimitry Andric       } else {
57140b57cec5SDimitry Andric         it->second.insert(repeat_key);
57150b57cec5SDimitry Andric       }
57160b57cec5SDimitry Andric     }
57170b57cec5SDimitry Andric   }
57180b57cec5SDimitry Andric 
57190b57cec5SDimitry Andric   if (print_warning) {
57200b57cec5SDimitry Andric     va_list args;
57210b57cec5SDimitry Andric     va_start(args, fmt);
57220b57cec5SDimitry Andric     stream_sp->PrintfVarArg(fmt, args);
57230b57cec5SDimitry Andric     va_end(args);
57240b57cec5SDimitry Andric   }
57250b57cec5SDimitry Andric }
57260b57cec5SDimitry Andric 
PrintWarningOptimization(const SymbolContext & sc)57270b57cec5SDimitry Andric void Process::PrintWarningOptimization(const SymbolContext &sc) {
57285ffd83dbSDimitry Andric   if (!GetWarningsOptimization())
57295ffd83dbSDimitry Andric     return;
57305ffd83dbSDimitry Andric   if (!sc.module_sp)
57315ffd83dbSDimitry Andric     return;
57325ffd83dbSDimitry Andric   if (!sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
57330b57cec5SDimitry Andric       sc.function->GetIsOptimized()) {
57340b57cec5SDimitry Andric     PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
57350b57cec5SDimitry Andric                  "%s was compiled with optimization - stepping may behave "
57360b57cec5SDimitry Andric                  "oddly; variables may not be available.\n",
57370b57cec5SDimitry Andric                  sc.module_sp->GetFileSpec().GetFilename().GetCString());
57380b57cec5SDimitry Andric   }
57390b57cec5SDimitry Andric }
57400b57cec5SDimitry Andric 
PrintWarningUnsupportedLanguage(const SymbolContext & sc)57415ffd83dbSDimitry Andric void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {
57425ffd83dbSDimitry Andric   if (!GetWarningsUnsupportedLanguage())
57435ffd83dbSDimitry Andric     return;
57445ffd83dbSDimitry Andric   if (!sc.module_sp)
57455ffd83dbSDimitry Andric     return;
57465ffd83dbSDimitry Andric   LanguageType language = sc.GetLanguage();
57475ffd83dbSDimitry Andric   if (language == eLanguageTypeUnknown)
57485ffd83dbSDimitry Andric     return;
5749*5f7ddb14SDimitry Andric   LanguageSet plugins =
5750*5f7ddb14SDimitry Andric       PluginManager::GetAllTypeSystemSupportedLanguagesForTypes();
5751*5f7ddb14SDimitry Andric   if (!plugins[language]) {
57525ffd83dbSDimitry Andric     PrintWarning(Process::Warnings::eWarningsUnsupportedLanguage,
57535ffd83dbSDimitry Andric                  sc.module_sp.get(),
5754*5f7ddb14SDimitry Andric                  "This version of LLDB has no plugin for the language \"%s\". "
57555ffd83dbSDimitry Andric                  "Inspection of frame variables will be limited.\n",
57565ffd83dbSDimitry Andric                  Language::GetNameForLanguageType(language));
57575ffd83dbSDimitry Andric   }
57585ffd83dbSDimitry Andric }
57595ffd83dbSDimitry Andric 
GetProcessInfo(ProcessInstanceInfo & info)57600b57cec5SDimitry Andric bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
57610b57cec5SDimitry Andric   info.Clear();
57620b57cec5SDimitry Andric 
57630b57cec5SDimitry Andric   PlatformSP platform_sp = GetTarget().GetPlatform();
57640b57cec5SDimitry Andric   if (!platform_sp)
57650b57cec5SDimitry Andric     return false;
57660b57cec5SDimitry Andric 
57670b57cec5SDimitry Andric   return platform_sp->GetProcessInfo(GetID(), info);
57680b57cec5SDimitry Andric }
57690b57cec5SDimitry Andric 
GetHistoryThreads(lldb::addr_t addr)57700b57cec5SDimitry Andric ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
57710b57cec5SDimitry Andric   ThreadCollectionSP threads;
57720b57cec5SDimitry Andric 
57730b57cec5SDimitry Andric   const MemoryHistorySP &memory_history =
57740b57cec5SDimitry Andric       MemoryHistory::FindPlugin(shared_from_this());
57750b57cec5SDimitry Andric 
57760b57cec5SDimitry Andric   if (!memory_history) {
57770b57cec5SDimitry Andric     return threads;
57780b57cec5SDimitry Andric   }
57790b57cec5SDimitry Andric 
57800b57cec5SDimitry Andric   threads = std::make_shared<ThreadCollection>(
57810b57cec5SDimitry Andric       memory_history->GetHistoryThreads(addr));
57820b57cec5SDimitry Andric 
57830b57cec5SDimitry Andric   return threads;
57840b57cec5SDimitry Andric }
57850b57cec5SDimitry Andric 
57860b57cec5SDimitry Andric InstrumentationRuntimeSP
GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)57870b57cec5SDimitry Andric Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
57880b57cec5SDimitry Andric   InstrumentationRuntimeCollection::iterator pos;
57890b57cec5SDimitry Andric   pos = m_instrumentation_runtimes.find(type);
57900b57cec5SDimitry Andric   if (pos == m_instrumentation_runtimes.end()) {
57910b57cec5SDimitry Andric     return InstrumentationRuntimeSP();
57920b57cec5SDimitry Andric   } else
57930b57cec5SDimitry Andric     return (*pos).second;
57940b57cec5SDimitry Andric }
57950b57cec5SDimitry Andric 
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)57960b57cec5SDimitry Andric bool Process::GetModuleSpec(const FileSpec &module_file_spec,
57970b57cec5SDimitry Andric                             const ArchSpec &arch, ModuleSpec &module_spec) {
57980b57cec5SDimitry Andric   module_spec.Clear();
57990b57cec5SDimitry Andric   return false;
58000b57cec5SDimitry Andric }
58010b57cec5SDimitry Andric 
AddImageToken(lldb::addr_t image_ptr)58020b57cec5SDimitry Andric size_t Process::AddImageToken(lldb::addr_t image_ptr) {
58030b57cec5SDimitry Andric   m_image_tokens.push_back(image_ptr);
58040b57cec5SDimitry Andric   return m_image_tokens.size() - 1;
58050b57cec5SDimitry Andric }
58060b57cec5SDimitry Andric 
GetImagePtrFromToken(size_t token) const58070b57cec5SDimitry Andric lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
58080b57cec5SDimitry Andric   if (token < m_image_tokens.size())
58090b57cec5SDimitry Andric     return m_image_tokens[token];
58105ffd83dbSDimitry Andric   return LLDB_INVALID_ADDRESS;
58110b57cec5SDimitry Andric }
58120b57cec5SDimitry Andric 
ResetImageToken(size_t token)58130b57cec5SDimitry Andric void Process::ResetImageToken(size_t token) {
58140b57cec5SDimitry Andric   if (token < m_image_tokens.size())
58155ffd83dbSDimitry Andric     m_image_tokens[token] = LLDB_INVALID_ADDRESS;
58160b57cec5SDimitry Andric }
58170b57cec5SDimitry Andric 
58180b57cec5SDimitry Andric Address
AdvanceAddressToNextBranchInstruction(Address default_stop_addr,AddressRange range_bounds)58190b57cec5SDimitry Andric Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
58200b57cec5SDimitry Andric                                                AddressRange range_bounds) {
58210b57cec5SDimitry Andric   Target &target = GetTarget();
58220b57cec5SDimitry Andric   DisassemblerSP disassembler_sp;
58230b57cec5SDimitry Andric   InstructionList *insn_list = nullptr;
58240b57cec5SDimitry Andric 
58250b57cec5SDimitry Andric   Address retval = default_stop_addr;
58260b57cec5SDimitry Andric 
58270b57cec5SDimitry Andric   if (!target.GetUseFastStepping())
58280b57cec5SDimitry Andric     return retval;
58290b57cec5SDimitry Andric   if (!default_stop_addr.IsValid())
58300b57cec5SDimitry Andric     return retval;
58310b57cec5SDimitry Andric 
58320b57cec5SDimitry Andric   const char *plugin_name = nullptr;
58330b57cec5SDimitry Andric   const char *flavor = nullptr;
58340b57cec5SDimitry Andric   disassembler_sp = Disassembler::DisassembleRange(
5835*5f7ddb14SDimitry Andric       target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds);
58360b57cec5SDimitry Andric   if (disassembler_sp)
58370b57cec5SDimitry Andric     insn_list = &disassembler_sp->GetInstructionList();
58380b57cec5SDimitry Andric 
58390b57cec5SDimitry Andric   if (insn_list == nullptr) {
58400b57cec5SDimitry Andric     return retval;
58410b57cec5SDimitry Andric   }
58420b57cec5SDimitry Andric 
58430b57cec5SDimitry Andric   size_t insn_offset =
58440b57cec5SDimitry Andric       insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
58450b57cec5SDimitry Andric   if (insn_offset == UINT32_MAX) {
58460b57cec5SDimitry Andric     return retval;
58470b57cec5SDimitry Andric   }
58480b57cec5SDimitry Andric 
5849af732203SDimitry Andric   uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
5850af732203SDimitry Andric       insn_offset, false /* ignore_calls*/, nullptr);
58510b57cec5SDimitry Andric   if (branch_index == UINT32_MAX) {
58520b57cec5SDimitry Andric     return retval;
58530b57cec5SDimitry Andric   }
58540b57cec5SDimitry Andric 
58550b57cec5SDimitry Andric   if (branch_index > insn_offset) {
58560b57cec5SDimitry Andric     Address next_branch_insn_address =
58570b57cec5SDimitry Andric         insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
58580b57cec5SDimitry Andric     if (next_branch_insn_address.IsValid() &&
58590b57cec5SDimitry Andric         range_bounds.ContainsFileAddress(next_branch_insn_address)) {
58600b57cec5SDimitry Andric       retval = next_branch_insn_address;
58610b57cec5SDimitry Andric     }
58620b57cec5SDimitry Andric   }
58630b57cec5SDimitry Andric 
58640b57cec5SDimitry Andric   return retval;
58650b57cec5SDimitry Andric }
58660b57cec5SDimitry Andric 
58670b57cec5SDimitry Andric Status
GetMemoryRegions(lldb_private::MemoryRegionInfos & region_list)58680b57cec5SDimitry Andric Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
58690b57cec5SDimitry Andric 
58700b57cec5SDimitry Andric   Status error;
58710b57cec5SDimitry Andric 
58720b57cec5SDimitry Andric   lldb::addr_t range_end = 0;
58730b57cec5SDimitry Andric 
58740b57cec5SDimitry Andric   region_list.clear();
58750b57cec5SDimitry Andric   do {
58760b57cec5SDimitry Andric     lldb_private::MemoryRegionInfo region_info;
58770b57cec5SDimitry Andric     error = GetMemoryRegionInfo(range_end, region_info);
58780b57cec5SDimitry Andric     // GetMemoryRegionInfo should only return an error if it is unimplemented.
58790b57cec5SDimitry Andric     if (error.Fail()) {
58800b57cec5SDimitry Andric       region_list.clear();
58810b57cec5SDimitry Andric       break;
58820b57cec5SDimitry Andric     }
58830b57cec5SDimitry Andric 
58840b57cec5SDimitry Andric     range_end = region_info.GetRange().GetRangeEnd();
58850b57cec5SDimitry Andric     if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
58860b57cec5SDimitry Andric       region_list.push_back(std::move(region_info));
58870b57cec5SDimitry Andric     }
58880b57cec5SDimitry Andric   } while (range_end != LLDB_INVALID_ADDRESS);
58890b57cec5SDimitry Andric 
58900b57cec5SDimitry Andric   return error;
58910b57cec5SDimitry Andric }
58920b57cec5SDimitry Andric 
58930b57cec5SDimitry Andric Status
ConfigureStructuredData(ConstString type_name,const StructuredData::ObjectSP & config_sp)58940b57cec5SDimitry Andric Process::ConfigureStructuredData(ConstString type_name,
58950b57cec5SDimitry Andric                                  const StructuredData::ObjectSP &config_sp) {
58960b57cec5SDimitry Andric   // If you get this, the Process-derived class needs to implement a method to
58970b57cec5SDimitry Andric   // enable an already-reported asynchronous structured data feature. See
58980b57cec5SDimitry Andric   // ProcessGDBRemote for an example implementation over gdb-remote.
58990b57cec5SDimitry Andric   return Status("unimplemented");
59000b57cec5SDimitry Andric }
59010b57cec5SDimitry Andric 
MapSupportedStructuredDataPlugins(const StructuredData::Array & supported_type_names)59020b57cec5SDimitry Andric void Process::MapSupportedStructuredDataPlugins(
59030b57cec5SDimitry Andric     const StructuredData::Array &supported_type_names) {
59040b57cec5SDimitry Andric   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
59050b57cec5SDimitry Andric 
59060b57cec5SDimitry Andric   // Bail out early if there are no type names to map.
59070b57cec5SDimitry Andric   if (supported_type_names.GetSize() == 0) {
59089dba64beSDimitry Andric     LLDB_LOGF(log, "Process::%s(): no structured data types supported",
59090b57cec5SDimitry Andric               __FUNCTION__);
59100b57cec5SDimitry Andric     return;
59110b57cec5SDimitry Andric   }
59120b57cec5SDimitry Andric 
59130b57cec5SDimitry Andric   // Convert StructuredData type names to ConstString instances.
59140b57cec5SDimitry Andric   std::set<ConstString> const_type_names;
59150b57cec5SDimitry Andric 
59169dba64beSDimitry Andric   LLDB_LOGF(log,
59179dba64beSDimitry Andric             "Process::%s(): the process supports the following async "
59180b57cec5SDimitry Andric             "structured data types:",
59190b57cec5SDimitry Andric             __FUNCTION__);
59200b57cec5SDimitry Andric 
59210b57cec5SDimitry Andric   supported_type_names.ForEach(
59220b57cec5SDimitry Andric       [&const_type_names, &log](StructuredData::Object *object) {
59230b57cec5SDimitry Andric         if (!object) {
59240b57cec5SDimitry Andric           // Invalid - shouldn't be null objects in the array.
59250b57cec5SDimitry Andric           return false;
59260b57cec5SDimitry Andric         }
59270b57cec5SDimitry Andric 
59280b57cec5SDimitry Andric         auto type_name = object->GetAsString();
59290b57cec5SDimitry Andric         if (!type_name) {
59300b57cec5SDimitry Andric           // Invalid format - all type names should be strings.
59310b57cec5SDimitry Andric           return false;
59320b57cec5SDimitry Andric         }
59330b57cec5SDimitry Andric 
59340b57cec5SDimitry Andric         const_type_names.insert(ConstString(type_name->GetValue()));
59350b57cec5SDimitry Andric         LLDB_LOG(log, "- {0}", type_name->GetValue());
59360b57cec5SDimitry Andric         return true;
59370b57cec5SDimitry Andric       });
59380b57cec5SDimitry Andric 
59390b57cec5SDimitry Andric   // For each StructuredDataPlugin, if the plugin handles any of the types in
59400b57cec5SDimitry Andric   // the supported_type_names, map that type name to that plugin. Stop when
59410b57cec5SDimitry Andric   // we've consumed all the type names.
59420b57cec5SDimitry Andric   // FIXME: should we return an error if there are type names nobody
59430b57cec5SDimitry Andric   // supports?
59440b57cec5SDimitry Andric   for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
59450b57cec5SDimitry Andric     auto create_instance =
59460b57cec5SDimitry Andric            PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
59470b57cec5SDimitry Andric                plugin_index);
59480b57cec5SDimitry Andric     if (!create_instance)
59490b57cec5SDimitry Andric       break;
59500b57cec5SDimitry Andric 
59510b57cec5SDimitry Andric     // Create the plugin.
59520b57cec5SDimitry Andric     StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
59530b57cec5SDimitry Andric     if (!plugin_sp) {
59540b57cec5SDimitry Andric       // This plugin doesn't think it can work with the process. Move on to the
59550b57cec5SDimitry Andric       // next.
59560b57cec5SDimitry Andric       continue;
59570b57cec5SDimitry Andric     }
59580b57cec5SDimitry Andric 
59590b57cec5SDimitry Andric     // For any of the remaining type names, map any that this plugin supports.
59600b57cec5SDimitry Andric     std::vector<ConstString> names_to_remove;
59610b57cec5SDimitry Andric     for (auto &type_name : const_type_names) {
59620b57cec5SDimitry Andric       if (plugin_sp->SupportsStructuredDataType(type_name)) {
59630b57cec5SDimitry Andric         m_structured_data_plugin_map.insert(
59640b57cec5SDimitry Andric             std::make_pair(type_name, plugin_sp));
59650b57cec5SDimitry Andric         names_to_remove.push_back(type_name);
59669dba64beSDimitry Andric         LLDB_LOGF(log,
59679dba64beSDimitry Andric                   "Process::%s(): using plugin %s for type name "
59680b57cec5SDimitry Andric                   "%s",
59690b57cec5SDimitry Andric                   __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
59700b57cec5SDimitry Andric                   type_name.GetCString());
59710b57cec5SDimitry Andric       }
59720b57cec5SDimitry Andric     }
59730b57cec5SDimitry Andric 
59740b57cec5SDimitry Andric     // Remove the type names that were consumed by this plugin.
59750b57cec5SDimitry Andric     for (auto &type_name : names_to_remove)
59760b57cec5SDimitry Andric       const_type_names.erase(type_name);
59770b57cec5SDimitry Andric   }
59780b57cec5SDimitry Andric }
59790b57cec5SDimitry Andric 
RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)59800b57cec5SDimitry Andric bool Process::RouteAsyncStructuredData(
59810b57cec5SDimitry Andric     const StructuredData::ObjectSP object_sp) {
59820b57cec5SDimitry Andric   // Nothing to do if there's no data.
59830b57cec5SDimitry Andric   if (!object_sp)
59840b57cec5SDimitry Andric     return false;
59850b57cec5SDimitry Andric 
59860b57cec5SDimitry Andric   // The contract is this must be a dictionary, so we can look up the routing
59870b57cec5SDimitry Andric   // key via the top-level 'type' string value within the dictionary.
59880b57cec5SDimitry Andric   StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
59890b57cec5SDimitry Andric   if (!dictionary)
59900b57cec5SDimitry Andric     return false;
59910b57cec5SDimitry Andric 
59920b57cec5SDimitry Andric   // Grab the async structured type name (i.e. the feature/plugin name).
59930b57cec5SDimitry Andric   ConstString type_name;
59940b57cec5SDimitry Andric   if (!dictionary->GetValueForKeyAsString("type", type_name))
59950b57cec5SDimitry Andric     return false;
59960b57cec5SDimitry Andric 
59970b57cec5SDimitry Andric   // Check if there's a plugin registered for this type name.
59980b57cec5SDimitry Andric   auto find_it = m_structured_data_plugin_map.find(type_name);
59990b57cec5SDimitry Andric   if (find_it == m_structured_data_plugin_map.end()) {
60000b57cec5SDimitry Andric     // We don't have a mapping for this structured data type.
60010b57cec5SDimitry Andric     return false;
60020b57cec5SDimitry Andric   }
60030b57cec5SDimitry Andric 
60040b57cec5SDimitry Andric   // Route the structured data to the plugin.
60050b57cec5SDimitry Andric   find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
60060b57cec5SDimitry Andric   return true;
60070b57cec5SDimitry Andric }
60080b57cec5SDimitry Andric 
UpdateAutomaticSignalFiltering()60090b57cec5SDimitry Andric Status Process::UpdateAutomaticSignalFiltering() {
60100b57cec5SDimitry Andric   // Default implementation does nothign.
60110b57cec5SDimitry Andric   // No automatic signal filtering to speak of.
60120b57cec5SDimitry Andric   return Status();
60130b57cec5SDimitry Andric }
60140b57cec5SDimitry Andric 
GetLoadImageUtilityFunction(Platform * platform,llvm::function_ref<std::unique_ptr<UtilityFunction> ()> factory)60150b57cec5SDimitry Andric UtilityFunction *Process::GetLoadImageUtilityFunction(
60160b57cec5SDimitry Andric     Platform *platform,
60170b57cec5SDimitry Andric     llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
60180b57cec5SDimitry Andric   if (platform != GetTarget().GetPlatform().get())
60190b57cec5SDimitry Andric     return nullptr;
60209dba64beSDimitry Andric   llvm::call_once(m_dlopen_utility_func_flag_once,
60210b57cec5SDimitry Andric                   [&] { m_dlopen_utility_func_up = factory(); });
60220b57cec5SDimitry Andric   return m_dlopen_utility_func_up.get();
60230b57cec5SDimitry Andric }
60249dba64beSDimitry Andric 
TraceSupported()6025*5f7ddb14SDimitry Andric llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6026af732203SDimitry Andric   if (!IsLiveDebugSession())
6027af732203SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
6028af732203SDimitry Andric                                    "Can't trace a non-live process.");
6029af732203SDimitry Andric   return llvm::make_error<UnimplementedError>();
6030af732203SDimitry Andric }
6031af732203SDimitry Andric 
CallVoidArgVoidPtrReturn(const Address * address,addr_t & returned_func,bool trap_exceptions)60329dba64beSDimitry Andric bool Process::CallVoidArgVoidPtrReturn(const Address *address,
60339dba64beSDimitry Andric                                        addr_t &returned_func,
60349dba64beSDimitry Andric                                        bool trap_exceptions) {
60359dba64beSDimitry Andric   Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
60369dba64beSDimitry Andric   if (thread == nullptr || address == nullptr)
60379dba64beSDimitry Andric     return false;
60389dba64beSDimitry Andric 
60399dba64beSDimitry Andric   EvaluateExpressionOptions options;
60409dba64beSDimitry Andric   options.SetStopOthers(true);
60419dba64beSDimitry Andric   options.SetUnwindOnError(true);
60429dba64beSDimitry Andric   options.SetIgnoreBreakpoints(true);
60439dba64beSDimitry Andric   options.SetTryAllThreads(true);
60449dba64beSDimitry Andric   options.SetDebug(false);
60459dba64beSDimitry Andric   options.SetTimeout(GetUtilityExpressionTimeout());
60469dba64beSDimitry Andric   options.SetTrapExceptions(trap_exceptions);
60479dba64beSDimitry Andric 
60489dba64beSDimitry Andric   auto type_system_or_err =
60499dba64beSDimitry Andric       GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
60509dba64beSDimitry Andric   if (!type_system_or_err) {
60519dba64beSDimitry Andric     llvm::consumeError(type_system_or_err.takeError());
60529dba64beSDimitry Andric     return false;
60539dba64beSDimitry Andric   }
60549dba64beSDimitry Andric   CompilerType void_ptr_type =
60559dba64beSDimitry Andric       type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
60569dba64beSDimitry Andric   lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
60579dba64beSDimitry Andric       *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
60589dba64beSDimitry Andric   if (call_plan_sp) {
60599dba64beSDimitry Andric     DiagnosticManager diagnostics;
60609dba64beSDimitry Andric 
60619dba64beSDimitry Andric     StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
60629dba64beSDimitry Andric     if (frame) {
60639dba64beSDimitry Andric       ExecutionContext exe_ctx;
60649dba64beSDimitry Andric       frame->CalculateExecutionContext(exe_ctx);
60659dba64beSDimitry Andric       ExpressionResults result =
60669dba64beSDimitry Andric           RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
60679dba64beSDimitry Andric       if (result == eExpressionCompleted) {
60689dba64beSDimitry Andric         returned_func =
60699dba64beSDimitry Andric             call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
60709dba64beSDimitry Andric                 LLDB_INVALID_ADDRESS);
60719dba64beSDimitry Andric 
60729dba64beSDimitry Andric         if (GetAddressByteSize() == 4) {
60739dba64beSDimitry Andric           if (returned_func == UINT32_MAX)
60749dba64beSDimitry Andric             return false;
60759dba64beSDimitry Andric         } else if (GetAddressByteSize() == 8) {
60769dba64beSDimitry Andric           if (returned_func == UINT64_MAX)
60779dba64beSDimitry Andric             return false;
60789dba64beSDimitry Andric         }
60799dba64beSDimitry Andric         return true;
60809dba64beSDimitry Andric       }
60819dba64beSDimitry Andric     }
60829dba64beSDimitry Andric   }
60839dba64beSDimitry Andric 
60849dba64beSDimitry Andric   return false;
60859dba64beSDimitry Andric }
6086*5f7ddb14SDimitry Andric 
GetMemoryTagManager()6087*5f7ddb14SDimitry Andric llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6088*5f7ddb14SDimitry Andric   Architecture *arch = GetTarget().GetArchitecturePlugin();
6089*5f7ddb14SDimitry Andric   const MemoryTagManager *tag_manager =
6090*5f7ddb14SDimitry Andric       arch ? arch->GetMemoryTagManager() : nullptr;
6091*5f7ddb14SDimitry Andric   if (!arch || !tag_manager) {
6092*5f7ddb14SDimitry Andric     return llvm::createStringError(
6093*5f7ddb14SDimitry Andric         llvm::inconvertibleErrorCode(),
6094*5f7ddb14SDimitry Andric         "This architecture does not support memory tagging",
6095*5f7ddb14SDimitry Andric         GetPluginName().GetCString());
6096*5f7ddb14SDimitry Andric   }
6097*5f7ddb14SDimitry Andric 
6098*5f7ddb14SDimitry Andric   if (!SupportsMemoryTagging()) {
6099*5f7ddb14SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
6100*5f7ddb14SDimitry Andric                                    "Process does not support memory tagging");
6101*5f7ddb14SDimitry Andric   }
6102*5f7ddb14SDimitry Andric 
6103*5f7ddb14SDimitry Andric   return tag_manager;
6104*5f7ddb14SDimitry Andric }
6105*5f7ddb14SDimitry Andric 
6106*5f7ddb14SDimitry Andric llvm::Expected<std::vector<lldb::addr_t>>
ReadMemoryTags(lldb::addr_t addr,size_t len)6107*5f7ddb14SDimitry Andric Process::ReadMemoryTags(lldb::addr_t addr, size_t len) {
6108*5f7ddb14SDimitry Andric   llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6109*5f7ddb14SDimitry Andric       GetMemoryTagManager();
6110*5f7ddb14SDimitry Andric   if (!tag_manager_or_err)
6111*5f7ddb14SDimitry Andric     return tag_manager_or_err.takeError();
6112*5f7ddb14SDimitry Andric 
6113*5f7ddb14SDimitry Andric   const MemoryTagManager *tag_manager = *tag_manager_or_err;
6114*5f7ddb14SDimitry Andric   llvm::Expected<std::vector<uint8_t>> tag_data =
6115*5f7ddb14SDimitry Andric       DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6116*5f7ddb14SDimitry Andric   if (!tag_data)
6117*5f7ddb14SDimitry Andric     return tag_data.takeError();
6118*5f7ddb14SDimitry Andric 
6119*5f7ddb14SDimitry Andric   return tag_manager->UnpackTagsData(*tag_data,
6120*5f7ddb14SDimitry Andric                                      len / tag_manager->GetGranuleSize());
6121*5f7ddb14SDimitry Andric }
6122*5f7ddb14SDimitry Andric 
WriteMemoryTags(lldb::addr_t addr,size_t len,const std::vector<lldb::addr_t> & tags)6123*5f7ddb14SDimitry Andric Status Process::WriteMemoryTags(lldb::addr_t addr, size_t len,
6124*5f7ddb14SDimitry Andric                                 const std::vector<lldb::addr_t> &tags) {
6125*5f7ddb14SDimitry Andric   llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6126*5f7ddb14SDimitry Andric       GetMemoryTagManager();
6127*5f7ddb14SDimitry Andric   if (!tag_manager_or_err)
6128*5f7ddb14SDimitry Andric     return Status(tag_manager_or_err.takeError());
6129*5f7ddb14SDimitry Andric 
6130*5f7ddb14SDimitry Andric   const MemoryTagManager *tag_manager = *tag_manager_or_err;
6131*5f7ddb14SDimitry Andric   llvm::Expected<std::vector<uint8_t>> packed_tags =
6132*5f7ddb14SDimitry Andric       tag_manager->PackTags(tags);
6133*5f7ddb14SDimitry Andric   if (!packed_tags) {
6134*5f7ddb14SDimitry Andric     return Status(packed_tags.takeError());
6135*5f7ddb14SDimitry Andric   }
6136*5f7ddb14SDimitry Andric 
6137*5f7ddb14SDimitry Andric   return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6138*5f7ddb14SDimitry Andric                            *packed_tags);
6139*5f7ddb14SDimitry Andric }
6140