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>
12bdd1243dSDimitry Andric #include <optional>
130b57cec5SDimitry Andric 
14fe6060f1SDimitry Andric #include "llvm/ADT/ScopeExit.h"
150b57cec5SDimitry Andric #include "llvm/Support/ScopedPrinter.h"
160b57cec5SDimitry Andric #include "llvm/Support/Threading.h"
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "lldb/Breakpoint/BreakpointLocation.h"
190b57cec5SDimitry Andric #include "lldb/Breakpoint/StoppointCallbackContext.h"
200b57cec5SDimitry Andric #include "lldb/Core/Debugger.h"
210b57cec5SDimitry Andric #include "lldb/Core/Module.h"
220b57cec5SDimitry Andric #include "lldb/Core/ModuleSpec.h"
230b57cec5SDimitry Andric #include "lldb/Core/PluginManager.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"
6781ad6265SDimitry Andric #include "lldb/Utility/LLDBLog.h"
680b57cec5SDimitry Andric #include "lldb/Utility/Log.h"
690b57cec5SDimitry Andric #include "lldb/Utility/NameMatches.h"
700b57cec5SDimitry Andric #include "lldb/Utility/ProcessInfo.h"
710b57cec5SDimitry Andric #include "lldb/Utility/SelectHelper.h"
720b57cec5SDimitry Andric #include "lldb/Utility/State.h"
73fe6060f1SDimitry Andric #include "lldb/Utility/Timer.h"
740b57cec5SDimitry Andric 
750b57cec5SDimitry Andric using namespace lldb;
760b57cec5SDimitry Andric using namespace lldb_private;
770b57cec5SDimitry Andric using namespace std::chrono;
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric // Comment out line below to disable memory caching, overriding the process
800b57cec5SDimitry Andric // setting target.process.disable-memory-cache
810b57cec5SDimitry Andric #define ENABLE_MEMORY_CACHING
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric #ifdef ENABLE_MEMORY_CACHING
840b57cec5SDimitry Andric #define DISABLE_MEM_CACHE_DEFAULT false
850b57cec5SDimitry Andric #else
860b57cec5SDimitry Andric #define DISABLE_MEM_CACHE_DEFAULT true
870b57cec5SDimitry Andric #endif
880b57cec5SDimitry Andric 
89fe6060f1SDimitry Andric class ProcessOptionValueProperties
90fe6060f1SDimitry Andric     : public Cloneable<ProcessOptionValueProperties, OptionValueProperties> {
910b57cec5SDimitry Andric public:
ProcessOptionValueProperties(llvm::StringRef name)92c9157d92SDimitry Andric   ProcessOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
930b57cec5SDimitry Andric 
94fe013be4SDimitry Andric   const Property *
GetPropertyAtIndex(size_t idx,const ExecutionContext * exe_ctx) const95fe013be4SDimitry Andric   GetPropertyAtIndex(size_t idx,
96fe013be4SDimitry Andric                      const ExecutionContext *exe_ctx) const override {
970b57cec5SDimitry Andric     // When getting the value for a key from the process options, we will
980b57cec5SDimitry Andric     // always try and grab the setting from the current process if there is
990b57cec5SDimitry Andric     // one. Else we just use the one from this instance.
1000b57cec5SDimitry Andric     if (exe_ctx) {
1010b57cec5SDimitry Andric       Process *process = exe_ctx->GetProcessPtr();
1020b57cec5SDimitry Andric       if (process) {
1030b57cec5SDimitry Andric         ProcessOptionValueProperties *instance_properties =
1040b57cec5SDimitry Andric             static_cast<ProcessOptionValueProperties *>(
1050b57cec5SDimitry Andric                 process->GetValueProperties().get());
1060b57cec5SDimitry Andric         if (this != instance_properties)
1070b57cec5SDimitry Andric           return instance_properties->ProtectedGetPropertyAtIndex(idx);
1080b57cec5SDimitry Andric       }
1090b57cec5SDimitry Andric     }
1100b57cec5SDimitry Andric     return ProtectedGetPropertyAtIndex(idx);
1110b57cec5SDimitry Andric   }
1120b57cec5SDimitry Andric };
1130b57cec5SDimitry Andric 
114349cc55cSDimitry Andric static constexpr OptionEnumValueElement g_follow_fork_mode_values[] = {
115349cc55cSDimitry Andric     {
116349cc55cSDimitry Andric         eFollowParent,
117349cc55cSDimitry Andric         "parent",
118349cc55cSDimitry Andric         "Continue tracing the parent process and detach the child.",
119349cc55cSDimitry Andric     },
120349cc55cSDimitry Andric     {
121349cc55cSDimitry Andric         eFollowChild,
122349cc55cSDimitry Andric         "child",
123349cc55cSDimitry Andric         "Trace the child process and detach the parent.",
124349cc55cSDimitry Andric     },
125349cc55cSDimitry Andric };
126349cc55cSDimitry Andric 
1279dba64beSDimitry Andric #define LLDB_PROPERTIES_process
1289dba64beSDimitry Andric #include "TargetProperties.inc"
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric enum {
1319dba64beSDimitry Andric #define LLDB_PROPERTIES_process
1329dba64beSDimitry Andric #include "TargetPropertiesEnum.inc"
1335ffd83dbSDimitry Andric   ePropertyExperimental,
1340b57cec5SDimitry Andric };
1350b57cec5SDimitry Andric 
1365ffd83dbSDimitry Andric #define LLDB_PROPERTIES_process_experimental
1375ffd83dbSDimitry Andric #include "TargetProperties.inc"
1385ffd83dbSDimitry Andric 
1395ffd83dbSDimitry Andric enum {
1405ffd83dbSDimitry Andric #define LLDB_PROPERTIES_process_experimental
1415ffd83dbSDimitry Andric #include "TargetPropertiesEnum.inc"
1425ffd83dbSDimitry Andric };
1435ffd83dbSDimitry Andric 
144fe6060f1SDimitry Andric class ProcessExperimentalOptionValueProperties
145fe6060f1SDimitry Andric     : public Cloneable<ProcessExperimentalOptionValueProperties,
146fe6060f1SDimitry Andric                        OptionValueProperties> {
1475ffd83dbSDimitry Andric public:
ProcessExperimentalOptionValueProperties()1485ffd83dbSDimitry Andric   ProcessExperimentalOptionValueProperties()
149c9157d92SDimitry Andric       : Cloneable(Properties::GetExperimentalSettingsName()) {}
1505ffd83dbSDimitry Andric };
1515ffd83dbSDimitry Andric 
ProcessExperimentalProperties()1525ffd83dbSDimitry Andric ProcessExperimentalProperties::ProcessExperimentalProperties()
1535ffd83dbSDimitry Andric     : Properties(OptionValuePropertiesSP(
1545ffd83dbSDimitry Andric           new ProcessExperimentalOptionValueProperties())) {
1555ffd83dbSDimitry Andric   m_collection_sp->Initialize(g_process_experimental_properties);
1565ffd83dbSDimitry Andric }
1575ffd83dbSDimitry Andric 
ProcessProperties(lldb_private::Process * process)1580b57cec5SDimitry Andric ProcessProperties::ProcessProperties(lldb_private::Process *process)
1590b57cec5SDimitry Andric     : Properties(),
1600b57cec5SDimitry Andric       m_process(process) // Can be nullptr for global ProcessProperties
1610b57cec5SDimitry Andric {
1620b57cec5SDimitry Andric   if (process == nullptr) {
1630b57cec5SDimitry Andric     // Global process properties, set them up one time
164c9157d92SDimitry Andric     m_collection_sp = std::make_shared<ProcessOptionValueProperties>("process");
1659dba64beSDimitry Andric     m_collection_sp->Initialize(g_process_properties);
1660b57cec5SDimitry Andric     m_collection_sp->AppendProperty(
167fe013be4SDimitry Andric         "thread", "Settings specific to threads.", true,
168fe013be4SDimitry Andric         Thread::GetGlobalProperties().GetValueProperties());
1690b57cec5SDimitry Andric   } else {
170fe6060f1SDimitry Andric     m_collection_sp =
171349cc55cSDimitry Andric         OptionValueProperties::CreateLocalCopy(Process::GetGlobalProperties());
1720b57cec5SDimitry Andric     m_collection_sp->SetValueChangedCallback(
1730b57cec5SDimitry Andric         ePropertyPythonOSPluginPath,
174480093f4SDimitry Andric         [this] { m_process->LoadOperatingSystemPlugin(true); });
1750b57cec5SDimitry Andric   }
1765ffd83dbSDimitry Andric 
1775ffd83dbSDimitry Andric   m_experimental_properties_up =
1785ffd83dbSDimitry Andric       std::make_unique<ProcessExperimentalProperties>();
1795ffd83dbSDimitry Andric   m_collection_sp->AppendProperty(
180fe013be4SDimitry Andric       Properties::GetExperimentalSettingsName(),
181fe013be4SDimitry Andric       "Experimental settings - setting these won't produce "
182fe013be4SDimitry Andric       "errors if the setting is not present.",
1835ffd83dbSDimitry Andric       true, m_experimental_properties_up->GetValueProperties());
1840b57cec5SDimitry Andric }
1850b57cec5SDimitry Andric 
1860b57cec5SDimitry Andric ProcessProperties::~ProcessProperties() = default;
1870b57cec5SDimitry Andric 
GetDisableMemoryCache() const1880b57cec5SDimitry Andric bool ProcessProperties::GetDisableMemoryCache() const {
1890b57cec5SDimitry Andric   const uint32_t idx = ePropertyDisableMemCache;
190fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
191fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
1920b57cec5SDimitry Andric }
1930b57cec5SDimitry Andric 
GetMemoryCacheLineSize() const1940b57cec5SDimitry Andric uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
1950b57cec5SDimitry Andric   const uint32_t idx = ePropertyMemCacheLineSize;
196fe013be4SDimitry Andric   return GetPropertyAtIndexAs<uint64_t>(
197fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value);
1980b57cec5SDimitry Andric }
1990b57cec5SDimitry Andric 
GetExtraStartupCommands() const2000b57cec5SDimitry Andric Args ProcessProperties::GetExtraStartupCommands() const {
2010b57cec5SDimitry Andric   Args args;
2020b57cec5SDimitry Andric   const uint32_t idx = ePropertyExtraStartCommand;
203fe013be4SDimitry Andric   m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
2040b57cec5SDimitry Andric   return args;
2050b57cec5SDimitry Andric }
2060b57cec5SDimitry Andric 
SetExtraStartupCommands(const Args & args)2070b57cec5SDimitry Andric void ProcessProperties::SetExtraStartupCommands(const Args &args) {
2080b57cec5SDimitry Andric   const uint32_t idx = ePropertyExtraStartCommand;
209fe013be4SDimitry Andric   m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
2100b57cec5SDimitry Andric }
2110b57cec5SDimitry Andric 
GetPythonOSPluginPath() const2120b57cec5SDimitry Andric FileSpec ProcessProperties::GetPythonOSPluginPath() const {
2130b57cec5SDimitry Andric   const uint32_t idx = ePropertyPythonOSPluginPath;
214fe013be4SDimitry Andric   return GetPropertyAtIndexAs<FileSpec>(idx, {});
2150b57cec5SDimitry Andric }
2160b57cec5SDimitry Andric 
GetVirtualAddressableBits() const217fe6060f1SDimitry Andric uint32_t ProcessProperties::GetVirtualAddressableBits() const {
218fe6060f1SDimitry Andric   const uint32_t idx = ePropertyVirtualAddressableBits;
219fe013be4SDimitry Andric   return GetPropertyAtIndexAs<uint64_t>(
220fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value);
221fe6060f1SDimitry Andric }
222fe6060f1SDimitry Andric 
SetVirtualAddressableBits(uint32_t bits)223fe6060f1SDimitry Andric void ProcessProperties::SetVirtualAddressableBits(uint32_t bits) {
224fe6060f1SDimitry Andric   const uint32_t idx = ePropertyVirtualAddressableBits;
225fe013be4SDimitry Andric   SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
226fe6060f1SDimitry Andric }
227fe013be4SDimitry Andric 
GetHighmemVirtualAddressableBits() const228fe013be4SDimitry Andric uint32_t ProcessProperties::GetHighmemVirtualAddressableBits() const {
229fe013be4SDimitry Andric   const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
230fe013be4SDimitry Andric   return GetPropertyAtIndexAs<uint64_t>(
231fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value);
232fe013be4SDimitry Andric }
233fe013be4SDimitry Andric 
SetHighmemVirtualAddressableBits(uint32_t bits)234fe013be4SDimitry Andric void ProcessProperties::SetHighmemVirtualAddressableBits(uint32_t bits) {
235fe013be4SDimitry Andric   const uint32_t idx = ePropertyHighmemVirtualAddressableBits;
236fe013be4SDimitry Andric   SetPropertyAtIndex(idx, static_cast<uint64_t>(bits));
237fe013be4SDimitry Andric }
238fe013be4SDimitry Andric 
SetPythonOSPluginPath(const FileSpec & file)2390b57cec5SDimitry Andric void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
2400b57cec5SDimitry Andric   const uint32_t idx = ePropertyPythonOSPluginPath;
241fe013be4SDimitry Andric   SetPropertyAtIndex(idx, file);
2420b57cec5SDimitry Andric }
2430b57cec5SDimitry Andric 
GetIgnoreBreakpointsInExpressions() const2440b57cec5SDimitry Andric bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
2450b57cec5SDimitry Andric   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
246fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
247fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
SetIgnoreBreakpointsInExpressions(bool ignore)2500b57cec5SDimitry Andric void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
2510b57cec5SDimitry Andric   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
252fe013be4SDimitry Andric   SetPropertyAtIndex(idx, ignore);
2530b57cec5SDimitry Andric }
2540b57cec5SDimitry Andric 
GetUnwindOnErrorInExpressions() const2550b57cec5SDimitry Andric bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
2560b57cec5SDimitry Andric   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
257fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
258fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
2590b57cec5SDimitry Andric }
2600b57cec5SDimitry Andric 
SetUnwindOnErrorInExpressions(bool ignore)2610b57cec5SDimitry Andric void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
2620b57cec5SDimitry Andric   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
263fe013be4SDimitry Andric   SetPropertyAtIndex(idx, ignore);
2640b57cec5SDimitry Andric }
2650b57cec5SDimitry Andric 
GetStopOnSharedLibraryEvents() const2660b57cec5SDimitry Andric bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
2670b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
268fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
269fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
2700b57cec5SDimitry Andric }
2710b57cec5SDimitry Andric 
SetStopOnSharedLibraryEvents(bool stop)2720b57cec5SDimitry Andric void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
2730b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
274fe013be4SDimitry Andric   SetPropertyAtIndex(idx, stop);
2750b57cec5SDimitry Andric }
2760b57cec5SDimitry Andric 
GetDisableLangRuntimeUnwindPlans() const277fe6060f1SDimitry Andric bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const {
278fe6060f1SDimitry Andric   const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
279fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
280fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
281fe6060f1SDimitry Andric }
282fe6060f1SDimitry Andric 
SetDisableLangRuntimeUnwindPlans(bool disable)283fe6060f1SDimitry Andric void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable) {
284fe6060f1SDimitry Andric   const uint32_t idx = ePropertyDisableLangRuntimeUnwindPlans;
285fe013be4SDimitry Andric   SetPropertyAtIndex(idx, disable);
286fe6060f1SDimitry Andric   m_process->Flush();
287fe6060f1SDimitry Andric }
288fe6060f1SDimitry Andric 
GetDetachKeepsStopped() const2890b57cec5SDimitry Andric bool ProcessProperties::GetDetachKeepsStopped() const {
2900b57cec5SDimitry Andric   const uint32_t idx = ePropertyDetachKeepsStopped;
291fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
292fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
2930b57cec5SDimitry Andric }
2940b57cec5SDimitry Andric 
SetDetachKeepsStopped(bool stop)2950b57cec5SDimitry Andric void ProcessProperties::SetDetachKeepsStopped(bool stop) {
2960b57cec5SDimitry Andric   const uint32_t idx = ePropertyDetachKeepsStopped;
297fe013be4SDimitry Andric   SetPropertyAtIndex(idx, stop);
2980b57cec5SDimitry Andric }
2990b57cec5SDimitry Andric 
GetWarningsOptimization() const3000b57cec5SDimitry Andric bool ProcessProperties::GetWarningsOptimization() const {
3010b57cec5SDimitry Andric   const uint32_t idx = ePropertyWarningOptimization;
302fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
303fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
3040b57cec5SDimitry Andric }
3050b57cec5SDimitry Andric 
GetWarningsUnsupportedLanguage() const3065ffd83dbSDimitry Andric bool ProcessProperties::GetWarningsUnsupportedLanguage() const {
3075ffd83dbSDimitry Andric   const uint32_t idx = ePropertyWarningUnsupportedLanguage;
308fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
309fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
3105ffd83dbSDimitry Andric }
3115ffd83dbSDimitry Andric 
GetStopOnExec() const3120b57cec5SDimitry Andric bool ProcessProperties::GetStopOnExec() const {
3130b57cec5SDimitry Andric   const uint32_t idx = ePropertyStopOnExec;
314fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
315fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
3160b57cec5SDimitry Andric }
3170b57cec5SDimitry Andric 
GetUtilityExpressionTimeout() const3180b57cec5SDimitry Andric std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
3190b57cec5SDimitry Andric   const uint32_t idx = ePropertyUtilityExpressionTimeout;
320fe013be4SDimitry Andric   uint64_t value = GetPropertyAtIndexAs<uint64_t>(
321fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value);
3220b57cec5SDimitry Andric   return std::chrono::seconds(value);
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
GetInterruptTimeout() const325fe6060f1SDimitry Andric std::chrono::seconds ProcessProperties::GetInterruptTimeout() const {
326fe6060f1SDimitry Andric   const uint32_t idx = ePropertyInterruptTimeout;
327fe013be4SDimitry Andric   uint64_t value = GetPropertyAtIndexAs<uint64_t>(
328fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value);
329fe6060f1SDimitry Andric   return std::chrono::seconds(value);
330fe6060f1SDimitry Andric }
331fe6060f1SDimitry Andric 
GetSteppingRunsAllThreads() const332e8d8bef9SDimitry Andric bool ProcessProperties::GetSteppingRunsAllThreads() const {
333e8d8bef9SDimitry Andric   const uint32_t idx = ePropertySteppingRunsAllThreads;
334fe013be4SDimitry Andric   return GetPropertyAtIndexAs<bool>(
335fe013be4SDimitry Andric       idx, g_process_properties[idx].default_uint_value != 0);
336e8d8bef9SDimitry Andric }
337e8d8bef9SDimitry Andric 
GetOSPluginReportsAllThreads() const3385ffd83dbSDimitry Andric bool ProcessProperties::GetOSPluginReportsAllThreads() const {
3395ffd83dbSDimitry Andric   const bool fail_value = true;
3405ffd83dbSDimitry Andric   const Property *exp_property =
341fe013be4SDimitry Andric       m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
3425ffd83dbSDimitry Andric   OptionValueProperties *exp_values =
3435ffd83dbSDimitry Andric       exp_property->GetValue()->GetAsProperties();
3445ffd83dbSDimitry Andric   if (!exp_values)
3455ffd83dbSDimitry Andric     return fail_value;
3465ffd83dbSDimitry Andric 
347fe013be4SDimitry Andric   return exp_values
348fe013be4SDimitry Andric       ->GetPropertyAtIndexAs<bool>(ePropertyOSPluginReportsAllThreads)
349fe013be4SDimitry Andric       .value_or(fail_value);
3505ffd83dbSDimitry Andric }
3515ffd83dbSDimitry Andric 
SetOSPluginReportsAllThreads(bool does_report)3525ffd83dbSDimitry Andric void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report) {
3535ffd83dbSDimitry Andric   const Property *exp_property =
354fe013be4SDimitry Andric       m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
3555ffd83dbSDimitry Andric   OptionValueProperties *exp_values =
3565ffd83dbSDimitry Andric       exp_property->GetValue()->GetAsProperties();
3575ffd83dbSDimitry Andric   if (exp_values)
358fe013be4SDimitry Andric     exp_values->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads,
359fe013be4SDimitry Andric                                    does_report);
3605ffd83dbSDimitry Andric }
3615ffd83dbSDimitry Andric 
GetFollowForkMode() const362349cc55cSDimitry Andric FollowForkMode ProcessProperties::GetFollowForkMode() const {
363349cc55cSDimitry Andric   const uint32_t idx = ePropertyFollowForkMode;
364fe013be4SDimitry Andric   return GetPropertyAtIndexAs<FollowForkMode>(
365fe013be4SDimitry Andric       idx, static_cast<FollowForkMode>(
366fe013be4SDimitry Andric                g_process_properties[idx].default_uint_value));
367349cc55cSDimitry Andric }
368349cc55cSDimitry Andric 
FindPlugin(lldb::TargetSP target_sp,llvm::StringRef plugin_name,ListenerSP listener_sp,const FileSpec * crash_file_path,bool can_connect)3690b57cec5SDimitry Andric ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
3700b57cec5SDimitry Andric                               llvm::StringRef plugin_name,
3710b57cec5SDimitry Andric                               ListenerSP listener_sp,
372e8d8bef9SDimitry Andric                               const FileSpec *crash_file_path,
373e8d8bef9SDimitry Andric                               bool can_connect) {
3740b57cec5SDimitry Andric   static uint32_t g_process_unique_id = 0;
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric   ProcessSP process_sp;
3770b57cec5SDimitry Andric   ProcessCreateInstance create_callback = nullptr;
3780b57cec5SDimitry Andric   if (!plugin_name.empty()) {
3790b57cec5SDimitry Andric     create_callback =
380349cc55cSDimitry Andric         PluginManager::GetProcessCreateCallbackForPluginName(plugin_name);
3810b57cec5SDimitry Andric     if (create_callback) {
382e8d8bef9SDimitry Andric       process_sp = create_callback(target_sp, listener_sp, crash_file_path,
383e8d8bef9SDimitry Andric                                    can_connect);
3840b57cec5SDimitry Andric       if (process_sp) {
3850b57cec5SDimitry Andric         if (process_sp->CanDebug(target_sp, true)) {
3860b57cec5SDimitry Andric           process_sp->m_process_unique_id = ++g_process_unique_id;
3870b57cec5SDimitry Andric         } else
3880b57cec5SDimitry Andric           process_sp.reset();
3890b57cec5SDimitry Andric       }
3900b57cec5SDimitry Andric     }
3910b57cec5SDimitry Andric   } else {
3920b57cec5SDimitry Andric     for (uint32_t idx = 0;
3930b57cec5SDimitry Andric          (create_callback =
3940b57cec5SDimitry Andric               PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
3950b57cec5SDimitry Andric          ++idx) {
396e8d8bef9SDimitry Andric       process_sp = create_callback(target_sp, listener_sp, crash_file_path,
397e8d8bef9SDimitry Andric                                    can_connect);
3980b57cec5SDimitry Andric       if (process_sp) {
3990b57cec5SDimitry Andric         if (process_sp->CanDebug(target_sp, false)) {
4000b57cec5SDimitry Andric           process_sp->m_process_unique_id = ++g_process_unique_id;
4010b57cec5SDimitry Andric           break;
4020b57cec5SDimitry Andric         } else
4030b57cec5SDimitry Andric           process_sp.reset();
4040b57cec5SDimitry Andric       }
4050b57cec5SDimitry Andric     }
4060b57cec5SDimitry Andric   }
4070b57cec5SDimitry Andric   return process_sp;
4080b57cec5SDimitry Andric }
4090b57cec5SDimitry Andric 
GetStaticBroadcasterClass()4100b57cec5SDimitry Andric ConstString &Process::GetStaticBroadcasterClass() {
4110b57cec5SDimitry Andric   static ConstString class_name("lldb.process");
4120b57cec5SDimitry Andric   return class_name;
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric 
Process(lldb::TargetSP target_sp,ListenerSP listener_sp)4150b57cec5SDimitry Andric Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
416fe013be4SDimitry Andric     : Process(target_sp, listener_sp, UnixSignals::CreateForHost()) {
4170b57cec5SDimitry Andric   // This constructor just delegates to the full Process constructor,
4180b57cec5SDimitry Andric   // defaulting to using the Host's UnixSignals.
4190b57cec5SDimitry Andric }
4200b57cec5SDimitry Andric 
Process(lldb::TargetSP target_sp,ListenerSP listener_sp,const UnixSignalsSP & unix_signals_sp)4210b57cec5SDimitry Andric Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
4220b57cec5SDimitry Andric                  const UnixSignalsSP &unix_signals_sp)
423e8d8bef9SDimitry Andric     : ProcessProperties(this),
4240b57cec5SDimitry Andric       Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
4250b57cec5SDimitry Andric                   Process::GetStaticBroadcasterClass().AsCString()),
4260b57cec5SDimitry Andric       m_target_wp(target_sp), m_public_state(eStateUnloaded),
4270b57cec5SDimitry Andric       m_private_state(eStateUnloaded),
4280b57cec5SDimitry Andric       m_private_state_broadcaster(nullptr,
4290b57cec5SDimitry Andric                                   "lldb.process.internal_state_broadcaster"),
4300b57cec5SDimitry Andric       m_private_state_control_broadcaster(
4310b57cec5SDimitry Andric           nullptr, "lldb.process.internal_state_control_broadcaster"),
4320b57cec5SDimitry Andric       m_private_state_listener_sp(
4330b57cec5SDimitry Andric           Listener::MakeListener("lldb.process.internal_state_listener")),
4340b57cec5SDimitry Andric       m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
4350b57cec5SDimitry Andric       m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
4360b57cec5SDimitry Andric       m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
4375ffd83dbSDimitry Andric       m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
4380b57cec5SDimitry Andric       m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
439c9157d92SDimitry Andric       m_watchpoint_resource_list(), m_notifications(), m_image_tokens(),
4400b57cec5SDimitry Andric       m_breakpoint_site_list(), m_dynamic_checkers_up(),
4410b57cec5SDimitry Andric       m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
4420b57cec5SDimitry Andric       m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
4430b57cec5SDimitry Andric       m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
4440b57cec5SDimitry Andric       m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
4450b57cec5SDimitry Andric       m_memory_cache(*this), m_allocated_memory_cache(*this),
4460b57cec5SDimitry Andric       m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
447972a253aSDimitry Andric       m_private_run_lock(), m_currently_handling_do_on_removals(false),
448c9157d92SDimitry Andric       m_resume_requested(false), m_finalizing(false), m_destructing(false),
4490b57cec5SDimitry Andric       m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
4500b57cec5SDimitry Andric       m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
45181ad6265SDimitry Andric       m_can_interpret_function_calls(false), m_run_thread_plan_lock(),
45281ad6265SDimitry Andric       m_can_jit(eCanJITDontKnow) {
4530b57cec5SDimitry Andric   CheckInWithManager();
4540b57cec5SDimitry Andric 
45581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Object);
4569dba64beSDimitry Andric   LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
4570b57cec5SDimitry Andric 
4580b57cec5SDimitry Andric   if (!m_unix_signals_sp)
4590b57cec5SDimitry Andric     m_unix_signals_sp = std::make_shared<UnixSignals>();
4600b57cec5SDimitry Andric 
4610b57cec5SDimitry Andric   SetEventName(eBroadcastBitStateChanged, "state-changed");
4620b57cec5SDimitry Andric   SetEventName(eBroadcastBitInterrupt, "interrupt");
4630b57cec5SDimitry Andric   SetEventName(eBroadcastBitSTDOUT, "stdout-available");
4640b57cec5SDimitry Andric   SetEventName(eBroadcastBitSTDERR, "stderr-available");
4650b57cec5SDimitry Andric   SetEventName(eBroadcastBitProfileData, "profile-data-available");
4660b57cec5SDimitry Andric   SetEventName(eBroadcastBitStructuredData, "structured-data-available");
4670b57cec5SDimitry Andric 
4680b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4690b57cec5SDimitry Andric       eBroadcastInternalStateControlStop, "control-stop");
4700b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4710b57cec5SDimitry Andric       eBroadcastInternalStateControlPause, "control-pause");
4720b57cec5SDimitry Andric   m_private_state_control_broadcaster.SetEventName(
4730b57cec5SDimitry Andric       eBroadcastInternalStateControlResume, "control-resume");
4740b57cec5SDimitry Andric 
475c9157d92SDimitry Andric   // The listener passed into process creation is the primary listener:
476c9157d92SDimitry Andric   // It always listens for all the event bits for Process:
477c9157d92SDimitry Andric   SetPrimaryListener(listener_sp);
4780b57cec5SDimitry Andric 
4790b57cec5SDimitry Andric   m_private_state_listener_sp->StartListeningForEvents(
4800b57cec5SDimitry Andric       &m_private_state_broadcaster,
4810b57cec5SDimitry Andric       eBroadcastBitStateChanged | eBroadcastBitInterrupt);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   m_private_state_listener_sp->StartListeningForEvents(
4840b57cec5SDimitry Andric       &m_private_state_control_broadcaster,
4850b57cec5SDimitry Andric       eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
4860b57cec5SDimitry Andric           eBroadcastInternalStateControlResume);
4870b57cec5SDimitry Andric   // We need something valid here, even if just the default UnixSignalsSP.
4880b57cec5SDimitry Andric   assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric   // Allow the platform to override the default cache line size
4910b57cec5SDimitry Andric   OptionValueSP value_sp =
492fe013be4SDimitry Andric       m_collection_sp->GetPropertyAtIndex(ePropertyMemCacheLineSize)
4930b57cec5SDimitry Andric           ->GetValue();
494fe013be4SDimitry Andric   uint64_t platform_cache_line_size =
4950b57cec5SDimitry Andric       target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
4960b57cec5SDimitry Andric   if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
497fe013be4SDimitry Andric     value_sp->SetValueAs(platform_cache_line_size);
4985ffd83dbSDimitry Andric 
4995ffd83dbSDimitry Andric   RegisterAssertFrameRecognizer(this);
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric 
~Process()5020b57cec5SDimitry Andric Process::~Process() {
50381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Object);
5049dba64beSDimitry Andric   LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
5050b57cec5SDimitry Andric   StopPrivateStateThread();
5060b57cec5SDimitry Andric 
5070b57cec5SDimitry Andric   // ThreadList::Clear() will try to acquire this process's mutex, so
5080b57cec5SDimitry Andric   // explicitly clear the thread list here to ensure that the mutex is not
5090b57cec5SDimitry Andric   // destroyed before the thread list.
5100b57cec5SDimitry Andric   m_thread_list.Clear();
5110b57cec5SDimitry Andric }
5120b57cec5SDimitry Andric 
GetGlobalProperties()513349cc55cSDimitry Andric ProcessProperties &Process::GetGlobalProperties() {
5140b57cec5SDimitry Andric   // NOTE: intentional leak so we don't crash if global destructor chain gets
5150b57cec5SDimitry Andric   // called as other threads still use the result of this function
516349cc55cSDimitry Andric   static ProcessProperties *g_settings_ptr =
517349cc55cSDimitry Andric       new ProcessProperties(nullptr);
518349cc55cSDimitry Andric   return *g_settings_ptr;
5190b57cec5SDimitry Andric }
5200b57cec5SDimitry Andric 
Finalize(bool destructing)521c9157d92SDimitry Andric void Process::Finalize(bool destructing) {
522e8d8bef9SDimitry Andric   if (m_finalizing.exchange(true))
523e8d8bef9SDimitry Andric     return;
524c9157d92SDimitry Andric   if (destructing)
525c9157d92SDimitry Andric     m_destructing.exchange(true);
5260b57cec5SDimitry Andric 
527fe6060f1SDimitry Andric   // Destroy the process. This will call the virtual function DoDestroy under
528fe6060f1SDimitry Andric   // the hood, giving our derived class a chance to do the ncessary tear down.
529e8d8bef9SDimitry Andric   DestroyImpl(false);
5300b57cec5SDimitry Andric 
5310b57cec5SDimitry Andric   // Clear our broadcaster before we proceed with destroying
5320b57cec5SDimitry Andric   Broadcaster::Clear();
5330b57cec5SDimitry Andric 
5340b57cec5SDimitry Andric   // Do any cleanup needed prior to being destructed... Subclasses that
5350b57cec5SDimitry Andric   // override this method should call this superclass method as well.
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric   // We need to destroy the loader before the derived Process class gets
5380b57cec5SDimitry Andric   // destroyed since it is very likely that undoing the loader will require
5390b57cec5SDimitry Andric   // access to the real process.
5400b57cec5SDimitry Andric   m_dynamic_checkers_up.reset();
5410b57cec5SDimitry Andric   m_abi_sp.reset();
5420b57cec5SDimitry Andric   m_os_up.reset();
5430b57cec5SDimitry Andric   m_system_runtime_up.reset();
5440b57cec5SDimitry Andric   m_dyld_up.reset();
5450b57cec5SDimitry Andric   m_jit_loaders_up.reset();
5465ffd83dbSDimitry Andric   m_thread_plans.Clear();
5470b57cec5SDimitry Andric   m_thread_list_real.Destroy();
5480b57cec5SDimitry Andric   m_thread_list.Destroy();
5490b57cec5SDimitry Andric   m_extended_thread_list.Destroy();
5500b57cec5SDimitry Andric   m_queue_list.Clear();
5510b57cec5SDimitry Andric   m_queue_list_stop_id = 0;
552c9157d92SDimitry Andric   m_watchpoint_resource_list.Clear();
5530b57cec5SDimitry Andric   std::vector<Notifications> empty_notifications;
5540b57cec5SDimitry Andric   m_notifications.swap(empty_notifications);
5550b57cec5SDimitry Andric   m_image_tokens.clear();
5560b57cec5SDimitry Andric   m_memory_cache.Clear();
557bdd1243dSDimitry Andric   m_allocated_memory_cache.Clear(/*deallocate_memory=*/true);
5580b57cec5SDimitry Andric   {
5590b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5600b57cec5SDimitry Andric     m_language_runtimes.clear();
5610b57cec5SDimitry Andric   }
5620b57cec5SDimitry Andric   m_instrumentation_runtimes.clear();
5630b57cec5SDimitry Andric   m_next_event_action_up.reset();
5640b57cec5SDimitry Andric   // Clear the last natural stop ID since it has a strong reference to this
5650b57cec5SDimitry Andric   // process
5660b57cec5SDimitry Andric   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
5670b57cec5SDimitry Andric   // We have to be very careful here as the m_private_state_listener might
5680b57cec5SDimitry Andric   // contain events that have ProcessSP values in them which can keep this
5690b57cec5SDimitry Andric   // process around forever. These events need to be cleared out.
5700b57cec5SDimitry Andric   m_private_state_listener_sp->Clear();
5710b57cec5SDimitry Andric   m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
5720b57cec5SDimitry Andric   m_public_run_lock.SetStopped();
5730b57cec5SDimitry Andric   m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
5740b57cec5SDimitry Andric   m_private_run_lock.SetStopped();
5750b57cec5SDimitry Andric   m_structured_data_plugin_map.clear();
5760b57cec5SDimitry Andric }
5770b57cec5SDimitry Andric 
RegisterNotificationCallbacks(const Notifications & callbacks)5780b57cec5SDimitry Andric void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
5790b57cec5SDimitry Andric   m_notifications.push_back(callbacks);
5800b57cec5SDimitry Andric   if (callbacks.initialize != nullptr)
5810b57cec5SDimitry Andric     callbacks.initialize(callbacks.baton, this);
5820b57cec5SDimitry Andric }
5830b57cec5SDimitry Andric 
UnregisterNotificationCallbacks(const Notifications & callbacks)5840b57cec5SDimitry Andric bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
5850b57cec5SDimitry Andric   std::vector<Notifications>::iterator pos, end = m_notifications.end();
5860b57cec5SDimitry Andric   for (pos = m_notifications.begin(); pos != end; ++pos) {
5870b57cec5SDimitry Andric     if (pos->baton == callbacks.baton &&
5880b57cec5SDimitry Andric         pos->initialize == callbacks.initialize &&
5890b57cec5SDimitry Andric         pos->process_state_changed == callbacks.process_state_changed) {
5900b57cec5SDimitry Andric       m_notifications.erase(pos);
5910b57cec5SDimitry Andric       return true;
5920b57cec5SDimitry Andric     }
5930b57cec5SDimitry Andric   }
5940b57cec5SDimitry Andric   return false;
5950b57cec5SDimitry Andric }
5960b57cec5SDimitry Andric 
SynchronouslyNotifyStateChanged(StateType state)5970b57cec5SDimitry Andric void Process::SynchronouslyNotifyStateChanged(StateType state) {
5980b57cec5SDimitry Andric   std::vector<Notifications>::iterator notification_pos,
5990b57cec5SDimitry Andric       notification_end = m_notifications.end();
6000b57cec5SDimitry Andric   for (notification_pos = m_notifications.begin();
6010b57cec5SDimitry Andric        notification_pos != notification_end; ++notification_pos) {
6020b57cec5SDimitry Andric     if (notification_pos->process_state_changed)
6030b57cec5SDimitry Andric       notification_pos->process_state_changed(notification_pos->baton, this,
6040b57cec5SDimitry Andric                                               state);
6050b57cec5SDimitry Andric   }
6060b57cec5SDimitry Andric }
6070b57cec5SDimitry Andric 
6080b57cec5SDimitry Andric // FIXME: We need to do some work on events before the general Listener sees
6090b57cec5SDimitry Andric // them.
6100b57cec5SDimitry Andric // For instance if we are continuing from a breakpoint, we need to ensure that
6110b57cec5SDimitry Andric // we do the little "insert real insn, step & stop" trick.  But we can't do
6120b57cec5SDimitry Andric // that when the event is delivered by the broadcaster - since that is done on
6130b57cec5SDimitry Andric // the thread that is waiting for new events, so if we needed more than one
6140b57cec5SDimitry Andric // event for our handling, we would stall.  So instead we do it when we fetch
6150b57cec5SDimitry Andric // the event off of the queue.
6160b57cec5SDimitry Andric //
6170b57cec5SDimitry Andric 
GetNextEvent(EventSP & event_sp)6180b57cec5SDimitry Andric StateType Process::GetNextEvent(EventSP &event_sp) {
6190b57cec5SDimitry Andric   StateType state = eStateInvalid;
6200b57cec5SDimitry Andric 
621c9157d92SDimitry Andric   if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp,
6220b57cec5SDimitry Andric                                             std::chrono::seconds(0)) &&
6230b57cec5SDimitry Andric       event_sp)
6240b57cec5SDimitry Andric     state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
6250b57cec5SDimitry Andric 
6260b57cec5SDimitry Andric   return state;
6270b57cec5SDimitry Andric }
6280b57cec5SDimitry Andric 
SyncIOHandler(uint32_t iohandler_id,const Timeout<std::micro> & timeout)6290b57cec5SDimitry Andric void Process::SyncIOHandler(uint32_t iohandler_id,
6300b57cec5SDimitry Andric                             const Timeout<std::micro> &timeout) {
6310b57cec5SDimitry Andric   // don't sync (potentially context switch) in case where there is no process
6320b57cec5SDimitry Andric   // IO
633c9157d92SDimitry Andric   if (!ProcessIOHandlerExists())
6340b57cec5SDimitry Andric     return;
6350b57cec5SDimitry Andric 
6360b57cec5SDimitry Andric   auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
6370b57cec5SDimitry Andric 
63881ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
6390b57cec5SDimitry Andric   if (Result) {
6400b57cec5SDimitry Andric     LLDB_LOG(
6410b57cec5SDimitry Andric         log,
6420b57cec5SDimitry Andric         "waited from m_iohandler_sync to change from {0}. New value is {1}.",
6430b57cec5SDimitry Andric         iohandler_id, *Result);
6440b57cec5SDimitry Andric   } else {
6450b57cec5SDimitry Andric     LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
6460b57cec5SDimitry Andric              iohandler_id);
6470b57cec5SDimitry Andric   }
6480b57cec5SDimitry Andric }
6490b57cec5SDimitry Andric 
WaitForProcessToStop(const Timeout<std::micro> & timeout,EventSP * event_sp_ptr,bool wait_always,ListenerSP hijack_listener_sp,Stream * stream,bool use_run_lock,SelectMostRelevant select_most_relevant)650fe013be4SDimitry Andric StateType Process::WaitForProcessToStop(
651fe013be4SDimitry Andric     const Timeout<std::micro> &timeout, EventSP *event_sp_ptr, bool wait_always,
652fe013be4SDimitry Andric     ListenerSP hijack_listener_sp, Stream *stream, bool use_run_lock,
653fe013be4SDimitry Andric     SelectMostRelevant select_most_relevant) {
6540b57cec5SDimitry Andric   // We can't just wait for a "stopped" event, because the stopped event may
6550b57cec5SDimitry Andric   // have restarted the target. We have to actually check each event, and in
6560b57cec5SDimitry Andric   // the case of a stopped event check the restarted flag on the event.
6570b57cec5SDimitry Andric   if (event_sp_ptr)
6580b57cec5SDimitry Andric     event_sp_ptr->reset();
6590b57cec5SDimitry Andric   StateType state = GetState();
6600b57cec5SDimitry Andric   // If we are exited or detached, we won't ever get back to any other valid
6610b57cec5SDimitry Andric   // state...
6620b57cec5SDimitry Andric   if (state == eStateDetached || state == eStateExited)
6630b57cec5SDimitry Andric     return state;
6640b57cec5SDimitry Andric 
66581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
6660b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}", timeout);
6670b57cec5SDimitry Andric 
6680b57cec5SDimitry Andric   if (!wait_always && StateIsStoppedState(state, true) &&
6690b57cec5SDimitry Andric       StateIsStoppedState(GetPrivateState(), true)) {
6709dba64beSDimitry Andric     LLDB_LOGF(log,
6719dba64beSDimitry Andric               "Process::%s returning without waiting for events; process "
6720b57cec5SDimitry Andric               "private and public states are already 'stopped'.",
6730b57cec5SDimitry Andric               __FUNCTION__);
6740b57cec5SDimitry Andric     // We need to toggle the run lock as this won't get done in
6750b57cec5SDimitry Andric     // SetPublicState() if the process is hijacked.
6760b57cec5SDimitry Andric     if (hijack_listener_sp && use_run_lock)
6770b57cec5SDimitry Andric       m_public_run_lock.SetStopped();
6780b57cec5SDimitry Andric     return state;
6790b57cec5SDimitry Andric   }
6800b57cec5SDimitry Andric 
6810b57cec5SDimitry Andric   while (state != eStateInvalid) {
6820b57cec5SDimitry Andric     EventSP event_sp;
6830b57cec5SDimitry Andric     state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
6840b57cec5SDimitry Andric     if (event_sp_ptr && event_sp)
6850b57cec5SDimitry Andric       *event_sp_ptr = event_sp;
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric     bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
688fe013be4SDimitry Andric     Process::HandleProcessStateChangedEvent(
689fe013be4SDimitry Andric         event_sp, stream, select_most_relevant, pop_process_io_handler);
6900b57cec5SDimitry Andric 
6910b57cec5SDimitry Andric     switch (state) {
6920b57cec5SDimitry Andric     case eStateCrashed:
6930b57cec5SDimitry Andric     case eStateDetached:
6940b57cec5SDimitry Andric     case eStateExited:
6950b57cec5SDimitry Andric     case eStateUnloaded:
6960b57cec5SDimitry Andric       // We need to toggle the run lock as this won't get done in
6970b57cec5SDimitry Andric       // SetPublicState() if the process is hijacked.
6980b57cec5SDimitry Andric       if (hijack_listener_sp && use_run_lock)
6990b57cec5SDimitry Andric         m_public_run_lock.SetStopped();
7000b57cec5SDimitry Andric       return state;
7010b57cec5SDimitry Andric     case eStateStopped:
7020b57cec5SDimitry Andric       if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
7030b57cec5SDimitry Andric         continue;
7040b57cec5SDimitry Andric       else {
7050b57cec5SDimitry Andric         // We need to toggle the run lock as this won't get done in
7060b57cec5SDimitry Andric         // SetPublicState() if the process is hijacked.
7070b57cec5SDimitry Andric         if (hijack_listener_sp && use_run_lock)
7080b57cec5SDimitry Andric           m_public_run_lock.SetStopped();
7090b57cec5SDimitry Andric         return state;
7100b57cec5SDimitry Andric       }
7110b57cec5SDimitry Andric     default:
7120b57cec5SDimitry Andric       continue;
7130b57cec5SDimitry Andric     }
7140b57cec5SDimitry Andric   }
7150b57cec5SDimitry Andric   return state;
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
HandleProcessStateChangedEvent(const EventSP & event_sp,Stream * stream,SelectMostRelevant select_most_relevant,bool & pop_process_io_handler)718fe013be4SDimitry Andric bool Process::HandleProcessStateChangedEvent(
719fe013be4SDimitry Andric     const EventSP &event_sp, Stream *stream,
720fe013be4SDimitry Andric     SelectMostRelevant select_most_relevant,
7210b57cec5SDimitry Andric     bool &pop_process_io_handler) {
7220b57cec5SDimitry Andric   const bool handle_pop = pop_process_io_handler;
7230b57cec5SDimitry Andric 
7240b57cec5SDimitry Andric   pop_process_io_handler = false;
7250b57cec5SDimitry Andric   ProcessSP process_sp =
7260b57cec5SDimitry Andric       Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
7270b57cec5SDimitry Andric 
7280b57cec5SDimitry Andric   if (!process_sp)
7290b57cec5SDimitry Andric     return false;
7300b57cec5SDimitry Andric 
7310b57cec5SDimitry Andric   StateType event_state =
7320b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
7330b57cec5SDimitry Andric   if (event_state == eStateInvalid)
7340b57cec5SDimitry Andric     return false;
7350b57cec5SDimitry Andric 
7360b57cec5SDimitry Andric   switch (event_state) {
7370b57cec5SDimitry Andric   case eStateInvalid:
7380b57cec5SDimitry Andric   case eStateUnloaded:
7390b57cec5SDimitry Andric   case eStateAttaching:
7400b57cec5SDimitry Andric   case eStateLaunching:
7410b57cec5SDimitry Andric   case eStateStepping:
7420b57cec5SDimitry Andric   case eStateDetached:
7430b57cec5SDimitry Andric     if (stream)
7440b57cec5SDimitry Andric       stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
7450b57cec5SDimitry Andric                      StateAsCString(event_state));
7460b57cec5SDimitry Andric     if (event_state == eStateDetached)
7470b57cec5SDimitry Andric       pop_process_io_handler = true;
7480b57cec5SDimitry Andric     break;
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric   case eStateConnected:
7510b57cec5SDimitry Andric   case eStateRunning:
7520b57cec5SDimitry Andric     // Don't be chatty when we run...
7530b57cec5SDimitry Andric     break;
7540b57cec5SDimitry Andric 
7550b57cec5SDimitry Andric   case eStateExited:
7560b57cec5SDimitry Andric     if (stream)
7570b57cec5SDimitry Andric       process_sp->GetStatus(*stream);
7580b57cec5SDimitry Andric     pop_process_io_handler = true;
7590b57cec5SDimitry Andric     break;
7600b57cec5SDimitry Andric 
7610b57cec5SDimitry Andric   case eStateStopped:
7620b57cec5SDimitry Andric   case eStateCrashed:
7630b57cec5SDimitry Andric   case eStateSuspended:
7640b57cec5SDimitry Andric     // Make sure the program hasn't been auto-restarted:
7650b57cec5SDimitry Andric     if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
7660b57cec5SDimitry Andric       if (stream) {
7670b57cec5SDimitry Andric         size_t num_reasons =
7680b57cec5SDimitry Andric             Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
7690b57cec5SDimitry Andric         if (num_reasons > 0) {
7700b57cec5SDimitry Andric           // FIXME: Do we want to report this, or would that just be annoyingly
7710b57cec5SDimitry Andric           // chatty?
7720b57cec5SDimitry Andric           if (num_reasons == 1) {
7730b57cec5SDimitry Andric             const char *reason =
7740b57cec5SDimitry Andric                 Process::ProcessEventData::GetRestartedReasonAtIndex(
7750b57cec5SDimitry Andric                     event_sp.get(), 0);
7760b57cec5SDimitry Andric             stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
7770b57cec5SDimitry Andric                            process_sp->GetID(),
7780b57cec5SDimitry Andric                            reason ? reason : "<UNKNOWN REASON>");
7790b57cec5SDimitry Andric           } else {
7800b57cec5SDimitry Andric             stream->Printf("Process %" PRIu64
7810b57cec5SDimitry Andric                            " stopped and restarted, reasons:\n",
7820b57cec5SDimitry Andric                            process_sp->GetID());
7830b57cec5SDimitry Andric 
7840b57cec5SDimitry Andric             for (size_t i = 0; i < num_reasons; i++) {
7850b57cec5SDimitry Andric               const char *reason =
7860b57cec5SDimitry Andric                   Process::ProcessEventData::GetRestartedReasonAtIndex(
7870b57cec5SDimitry Andric                       event_sp.get(), i);
7880b57cec5SDimitry Andric               stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
7890b57cec5SDimitry Andric             }
7900b57cec5SDimitry Andric           }
7910b57cec5SDimitry Andric         }
7920b57cec5SDimitry Andric       }
7930b57cec5SDimitry Andric     } else {
7940b57cec5SDimitry Andric       StopInfoSP curr_thread_stop_info_sp;
7950b57cec5SDimitry Andric       // Lock the thread list so it doesn't change on us, this is the scope for
7960b57cec5SDimitry Andric       // the locker:
7970b57cec5SDimitry Andric       {
7980b57cec5SDimitry Andric         ThreadList &thread_list = process_sp->GetThreadList();
7990b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
8000b57cec5SDimitry Andric 
8010b57cec5SDimitry Andric         ThreadSP curr_thread(thread_list.GetSelectedThread());
8020b57cec5SDimitry Andric         ThreadSP thread;
8030b57cec5SDimitry Andric         StopReason curr_thread_stop_reason = eStopReasonInvalid;
804fe6060f1SDimitry Andric         bool prefer_curr_thread = false;
805fe6060f1SDimitry Andric         if (curr_thread && curr_thread->IsValid()) {
8060b57cec5SDimitry Andric           curr_thread_stop_reason = curr_thread->GetStopReason();
807fe6060f1SDimitry Andric           switch (curr_thread_stop_reason) {
808fe6060f1SDimitry Andric           case eStopReasonNone:
809fe6060f1SDimitry Andric           case eStopReasonInvalid:
810fe6060f1SDimitry Andric             // Don't prefer the current thread if it didn't stop for a reason.
811fe6060f1SDimitry Andric             break;
812fe6060f1SDimitry Andric           case eStopReasonSignal: {
813fe6060f1SDimitry Andric             // We need to do the same computation we do for other threads
814fe6060f1SDimitry Andric             // below in case the current thread happens to be the one that
815fe6060f1SDimitry Andric             // stopped for the no-stop signal.
816fe6060f1SDimitry Andric             uint64_t signo = curr_thread->GetStopInfo()->GetValue();
817fe6060f1SDimitry Andric             if (process_sp->GetUnixSignals()->GetShouldStop(signo))
818fe6060f1SDimitry Andric               prefer_curr_thread = true;
819fe6060f1SDimitry Andric           } break;
820fe6060f1SDimitry Andric           default:
821fe6060f1SDimitry Andric             prefer_curr_thread = true;
822fe6060f1SDimitry Andric             break;
823fe6060f1SDimitry Andric           }
8240b57cec5SDimitry Andric           curr_thread_stop_info_sp = curr_thread->GetStopInfo();
8250b57cec5SDimitry Andric         }
826fe6060f1SDimitry Andric 
827fe6060f1SDimitry Andric         if (!prefer_curr_thread) {
8280b57cec5SDimitry Andric           // Prefer a thread that has just completed its plan over another
8290b57cec5SDimitry Andric           // thread as current thread.
8300b57cec5SDimitry Andric           ThreadSP plan_thread;
8310b57cec5SDimitry Andric           ThreadSP other_thread;
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric           const size_t num_threads = thread_list.GetSize();
8340b57cec5SDimitry Andric           size_t i;
8350b57cec5SDimitry Andric           for (i = 0; i < num_threads; ++i) {
8360b57cec5SDimitry Andric             thread = thread_list.GetThreadAtIndex(i);
8370b57cec5SDimitry Andric             StopReason thread_stop_reason = thread->GetStopReason();
8380b57cec5SDimitry Andric             switch (thread_stop_reason) {
8390b57cec5SDimitry Andric             case eStopReasonInvalid:
8400b57cec5SDimitry Andric             case eStopReasonNone:
8410b57cec5SDimitry Andric               break;
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric             case eStopReasonSignal: {
8440b57cec5SDimitry Andric               // Don't select a signal thread if we weren't going to stop at
8450b57cec5SDimitry Andric               // that signal.  We have to have had another reason for stopping
8460b57cec5SDimitry Andric               // here, and the user doesn't want to see this thread.
8470b57cec5SDimitry Andric               uint64_t signo = thread->GetStopInfo()->GetValue();
8480b57cec5SDimitry Andric               if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
8490b57cec5SDimitry Andric                 if (!other_thread)
8500b57cec5SDimitry Andric                   other_thread = thread;
8510b57cec5SDimitry Andric               }
8520b57cec5SDimitry Andric               break;
8530b57cec5SDimitry Andric             }
8540b57cec5SDimitry Andric             case eStopReasonTrace:
8550b57cec5SDimitry Andric             case eStopReasonBreakpoint:
8560b57cec5SDimitry Andric             case eStopReasonWatchpoint:
8570b57cec5SDimitry Andric             case eStopReasonException:
8580b57cec5SDimitry Andric             case eStopReasonExec:
859fe6060f1SDimitry Andric             case eStopReasonFork:
860fe6060f1SDimitry Andric             case eStopReasonVFork:
861fe6060f1SDimitry Andric             case eStopReasonVForkDone:
8620b57cec5SDimitry Andric             case eStopReasonThreadExiting:
8630b57cec5SDimitry Andric             case eStopReasonInstrumentation:
864fe6060f1SDimitry Andric             case eStopReasonProcessorTrace:
8650b57cec5SDimitry Andric               if (!other_thread)
8660b57cec5SDimitry Andric                 other_thread = thread;
8670b57cec5SDimitry Andric               break;
8680b57cec5SDimitry Andric             case eStopReasonPlanComplete:
8690b57cec5SDimitry Andric               if (!plan_thread)
8700b57cec5SDimitry Andric                 plan_thread = thread;
8710b57cec5SDimitry Andric               break;
8720b57cec5SDimitry Andric             }
8730b57cec5SDimitry Andric           }
8740b57cec5SDimitry Andric           if (plan_thread)
8750b57cec5SDimitry Andric             thread_list.SetSelectedThreadByID(plan_thread->GetID());
8760b57cec5SDimitry Andric           else if (other_thread)
8770b57cec5SDimitry Andric             thread_list.SetSelectedThreadByID(other_thread->GetID());
8780b57cec5SDimitry Andric           else {
8790b57cec5SDimitry Andric             if (curr_thread && curr_thread->IsValid())
8800b57cec5SDimitry Andric               thread = curr_thread;
8810b57cec5SDimitry Andric             else
8820b57cec5SDimitry Andric               thread = thread_list.GetThreadAtIndex(0);
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric             if (thread)
8850b57cec5SDimitry Andric               thread_list.SetSelectedThreadByID(thread->GetID());
8860b57cec5SDimitry Andric           }
8870b57cec5SDimitry Andric         }
8880b57cec5SDimitry Andric       }
8890b57cec5SDimitry Andric       // Drop the ThreadList mutex by here, since GetThreadStatus below might
8900b57cec5SDimitry Andric       // have to run code, e.g. for Data formatters, and if we hold the
8910b57cec5SDimitry Andric       // ThreadList mutex, then the process is going to have a hard time
8920b57cec5SDimitry Andric       // restarting the process.
8930b57cec5SDimitry Andric       if (stream) {
8940b57cec5SDimitry Andric         Debugger &debugger = process_sp->GetTarget().GetDebugger();
8950b57cec5SDimitry Andric         if (debugger.GetTargetList().GetSelectedTarget().get() ==
8960b57cec5SDimitry Andric             &process_sp->GetTarget()) {
8975ffd83dbSDimitry Andric           ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
8985ffd83dbSDimitry Andric 
8995ffd83dbSDimitry Andric           if (!thread_sp || !thread_sp->IsValid())
9005ffd83dbSDimitry Andric             return false;
9015ffd83dbSDimitry Andric 
9020b57cec5SDimitry Andric           const bool only_threads_with_stop_reason = true;
903fe013be4SDimitry Andric           const uint32_t start_frame =
904fe013be4SDimitry Andric               thread_sp->GetSelectedFrameIndex(select_most_relevant);
9050b57cec5SDimitry Andric           const uint32_t num_frames = 1;
9060b57cec5SDimitry Andric           const uint32_t num_frames_with_source = 1;
9070b57cec5SDimitry Andric           const bool stop_format = true;
9085ffd83dbSDimitry Andric 
9090b57cec5SDimitry Andric           process_sp->GetStatus(*stream);
9100b57cec5SDimitry Andric           process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
9110b57cec5SDimitry Andric                                       start_frame, num_frames,
9120b57cec5SDimitry Andric                                       num_frames_with_source,
9130b57cec5SDimitry Andric                                       stop_format);
9140b57cec5SDimitry Andric           if (curr_thread_stop_info_sp) {
9150b57cec5SDimitry Andric             lldb::addr_t crashing_address;
9160b57cec5SDimitry Andric             ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
9170b57cec5SDimitry Andric                 curr_thread_stop_info_sp, &crashing_address);
9180b57cec5SDimitry Andric             if (valobj_sp) {
9190b57cec5SDimitry Andric               const ValueObject::GetExpressionPathFormat format =
9200b57cec5SDimitry Andric                   ValueObject::GetExpressionPathFormat::
9210b57cec5SDimitry Andric                       eGetExpressionPathFormatHonorPointers;
9220b57cec5SDimitry Andric               stream->PutCString("Likely cause: ");
9235ffd83dbSDimitry Andric               valobj_sp->GetExpressionPath(*stream, format);
9240b57cec5SDimitry Andric               stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
9250b57cec5SDimitry Andric             }
9260b57cec5SDimitry Andric           }
9270b57cec5SDimitry Andric         } else {
9280b57cec5SDimitry Andric           uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
9290b57cec5SDimitry Andric               process_sp->GetTarget().shared_from_this());
9300b57cec5SDimitry Andric           if (target_idx != UINT32_MAX)
9310b57cec5SDimitry Andric             stream->Printf("Target %d: (", target_idx);
9320b57cec5SDimitry Andric           else
9330b57cec5SDimitry Andric             stream->Printf("Target <unknown index>: (");
9340b57cec5SDimitry Andric           process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
9350b57cec5SDimitry Andric           stream->Printf(") stopped.\n");
9360b57cec5SDimitry Andric         }
9370b57cec5SDimitry Andric       }
9380b57cec5SDimitry Andric 
9390b57cec5SDimitry Andric       // Pop the process IO handler
9400b57cec5SDimitry Andric       pop_process_io_handler = true;
9410b57cec5SDimitry Andric     }
9420b57cec5SDimitry Andric     break;
9430b57cec5SDimitry Andric   }
9440b57cec5SDimitry Andric 
9450b57cec5SDimitry Andric   if (handle_pop && pop_process_io_handler)
9460b57cec5SDimitry Andric     process_sp->PopProcessIOHandler();
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   return true;
9490b57cec5SDimitry Andric }
9500b57cec5SDimitry Andric 
HijackProcessEvents(ListenerSP listener_sp)9510b57cec5SDimitry Andric bool Process::HijackProcessEvents(ListenerSP listener_sp) {
9520b57cec5SDimitry Andric   if (listener_sp) {
9530b57cec5SDimitry Andric     return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
9540b57cec5SDimitry Andric                                               eBroadcastBitInterrupt);
9550b57cec5SDimitry Andric   } else
9560b57cec5SDimitry Andric     return false;
9570b57cec5SDimitry Andric }
9580b57cec5SDimitry Andric 
RestoreProcessEvents()9590b57cec5SDimitry Andric void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
9600b57cec5SDimitry Andric 
GetStateChangedEvents(EventSP & event_sp,const Timeout<std::micro> & timeout,ListenerSP hijack_listener_sp)9610b57cec5SDimitry Andric StateType Process::GetStateChangedEvents(EventSP &event_sp,
9620b57cec5SDimitry Andric                                          const Timeout<std::micro> &timeout,
9630b57cec5SDimitry Andric                                          ListenerSP hijack_listener_sp) {
96481ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
9650b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
9660b57cec5SDimitry Andric 
9670b57cec5SDimitry Andric   ListenerSP listener_sp = hijack_listener_sp;
9680b57cec5SDimitry Andric   if (!listener_sp)
969c9157d92SDimitry Andric     listener_sp = GetPrimaryListener();
9700b57cec5SDimitry Andric 
9710b57cec5SDimitry Andric   StateType state = eStateInvalid;
9720b57cec5SDimitry Andric   if (listener_sp->GetEventForBroadcasterWithType(
9730b57cec5SDimitry Andric           this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
9740b57cec5SDimitry Andric           timeout)) {
9750b57cec5SDimitry Andric     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
9760b57cec5SDimitry Andric       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
9770b57cec5SDimitry Andric     else
9780b57cec5SDimitry Andric       LLDB_LOG(log, "got no event or was interrupted.");
9790b57cec5SDimitry Andric   }
9800b57cec5SDimitry Andric 
9810b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
9820b57cec5SDimitry Andric   return state;
9830b57cec5SDimitry Andric }
9840b57cec5SDimitry Andric 
PeekAtStateChangedEvents()9850b57cec5SDimitry Andric Event *Process::PeekAtStateChangedEvents() {
98681ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
9870b57cec5SDimitry Andric 
9889dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
9890b57cec5SDimitry Andric 
9900b57cec5SDimitry Andric   Event *event_ptr;
991c9157d92SDimitry Andric   event_ptr = GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(
9920b57cec5SDimitry Andric       this, eBroadcastBitStateChanged);
9930b57cec5SDimitry Andric   if (log) {
9940b57cec5SDimitry Andric     if (event_ptr) {
9959dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
9960b57cec5SDimitry Andric                 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
9970b57cec5SDimitry Andric     } else {
9989dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
9990b57cec5SDimitry Andric     }
10000b57cec5SDimitry Andric   }
10010b57cec5SDimitry Andric   return event_ptr;
10020b57cec5SDimitry Andric }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric StateType
GetStateChangedEventsPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout)10050b57cec5SDimitry Andric Process::GetStateChangedEventsPrivate(EventSP &event_sp,
10060b57cec5SDimitry Andric                                       const Timeout<std::micro> &timeout) {
100781ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
10080b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric   StateType state = eStateInvalid;
10110b57cec5SDimitry Andric   if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
10120b57cec5SDimitry Andric           &m_private_state_broadcaster,
10130b57cec5SDimitry Andric           eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
10140b57cec5SDimitry Andric           timeout))
10150b57cec5SDimitry Andric     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
10160b57cec5SDimitry Andric       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
10170b57cec5SDimitry Andric 
10180b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
10190b57cec5SDimitry Andric            state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
10200b57cec5SDimitry Andric   return state;
10210b57cec5SDimitry Andric }
10220b57cec5SDimitry Andric 
GetEventsPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout,bool control_only)10230b57cec5SDimitry Andric bool Process::GetEventsPrivate(EventSP &event_sp,
10240b57cec5SDimitry Andric                                const Timeout<std::micro> &timeout,
10250b57cec5SDimitry Andric                                bool control_only) {
102681ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
10270b57cec5SDimitry Andric   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
10280b57cec5SDimitry Andric 
10290b57cec5SDimitry Andric   if (control_only)
10300b57cec5SDimitry Andric     return m_private_state_listener_sp->GetEventForBroadcaster(
10310b57cec5SDimitry Andric         &m_private_state_control_broadcaster, event_sp, timeout);
10320b57cec5SDimitry Andric   else
10330b57cec5SDimitry Andric     return m_private_state_listener_sp->GetEvent(event_sp, timeout);
10340b57cec5SDimitry Andric }
10350b57cec5SDimitry Andric 
IsRunning() const10360b57cec5SDimitry Andric bool Process::IsRunning() const {
10370b57cec5SDimitry Andric   return StateIsRunningState(m_public_state.GetValue());
10380b57cec5SDimitry Andric }
10390b57cec5SDimitry Andric 
GetExitStatus()10400b57cec5SDimitry Andric int Process::GetExitStatus() {
10410b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10420b57cec5SDimitry Andric 
10430b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateExited)
10440b57cec5SDimitry Andric     return m_exit_status;
10450b57cec5SDimitry Andric   return -1;
10460b57cec5SDimitry Andric }
10470b57cec5SDimitry Andric 
GetExitDescription()10480b57cec5SDimitry Andric const char *Process::GetExitDescription() {
10490b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10500b57cec5SDimitry Andric 
10510b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
10520b57cec5SDimitry Andric     return m_exit_string.c_str();
10530b57cec5SDimitry Andric   return nullptr;
10540b57cec5SDimitry Andric }
10550b57cec5SDimitry Andric 
SetExitStatus(int status,llvm::StringRef exit_string)1056c9157d92SDimitry Andric bool Process::SetExitStatus(int status, llvm::StringRef exit_string) {
10570b57cec5SDimitry Andric   // Use a mutex to protect setting the exit status.
10580b57cec5SDimitry Andric   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
10590b57cec5SDimitry Andric 
106081ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::State | LLDBLog::Process));
1061c9157d92SDimitry Andric   LLDB_LOG(log, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1062c9157d92SDimitry Andric            GetPluginName(), status, exit_string);
10630b57cec5SDimitry Andric 
10640b57cec5SDimitry Andric   // We were already in the exited state
10650b57cec5SDimitry Andric   if (m_private_state.GetValue() == eStateExited) {
1066c9157d92SDimitry Andric     LLDB_LOG(
1067c9157d92SDimitry Andric         log,
1068c9157d92SDimitry Andric         "(plugin = {0}) ignoring exit status because state was already set "
1069fe013be4SDimitry Andric         "to eStateExited",
1070c9157d92SDimitry Andric         GetPluginName());
10710b57cec5SDimitry Andric     return false;
10720b57cec5SDimitry Andric   }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric   m_exit_status = status;
1075c9157d92SDimitry Andric   if (!exit_string.empty())
1076c9157d92SDimitry Andric     m_exit_string = exit_string.str();
10770b57cec5SDimitry Andric   else
10780b57cec5SDimitry Andric     m_exit_string.clear();
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   // Clear the last natural stop ID since it has a strong reference to this
10810b57cec5SDimitry Andric   // process
10820b57cec5SDimitry Andric   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
10830b57cec5SDimitry Andric 
10840b57cec5SDimitry Andric   SetPrivateState(eStateExited);
10850b57cec5SDimitry Andric 
10860b57cec5SDimitry Andric   // Allow subclasses to do some cleanup
10870b57cec5SDimitry Andric   DidExit();
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   return true;
10900b57cec5SDimitry Andric }
10910b57cec5SDimitry Andric 
IsAlive()10920b57cec5SDimitry Andric bool Process::IsAlive() {
10930b57cec5SDimitry Andric   switch (m_private_state.GetValue()) {
10940b57cec5SDimitry Andric   case eStateConnected:
10950b57cec5SDimitry Andric   case eStateAttaching:
10960b57cec5SDimitry Andric   case eStateLaunching:
10970b57cec5SDimitry Andric   case eStateStopped:
10980b57cec5SDimitry Andric   case eStateRunning:
10990b57cec5SDimitry Andric   case eStateStepping:
11000b57cec5SDimitry Andric   case eStateCrashed:
11010b57cec5SDimitry Andric   case eStateSuspended:
11020b57cec5SDimitry Andric     return true;
11030b57cec5SDimitry Andric   default:
11040b57cec5SDimitry Andric     return false;
11050b57cec5SDimitry Andric   }
11060b57cec5SDimitry Andric }
11070b57cec5SDimitry Andric 
11080b57cec5SDimitry Andric // This static callback can be used to watch for local child processes on the
11090b57cec5SDimitry Andric // current host. The child process exits, the process will be found in the
11100b57cec5SDimitry Andric // global target list (we want to be completely sure that the
11110b57cec5SDimitry 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)11120b57cec5SDimitry Andric bool Process::SetProcessExitStatus(
11130b57cec5SDimitry Andric     lldb::pid_t pid, bool exited,
11140b57cec5SDimitry Andric     int signo,      // Zero for no signal
11150b57cec5SDimitry Andric     int exit_status // Exit value of process if signal is zero
11160b57cec5SDimitry Andric     ) {
111781ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
11189dba64beSDimitry Andric   LLDB_LOGF(log,
11199dba64beSDimitry Andric             "Process::SetProcessExitStatus (pid=%" PRIu64
11200b57cec5SDimitry Andric             ", exited=%i, signal=%i, exit_status=%i)\n",
11210b57cec5SDimitry Andric             pid, exited, signo, exit_status);
11220b57cec5SDimitry Andric 
11230b57cec5SDimitry Andric   if (exited) {
11240b57cec5SDimitry Andric     TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
11250b57cec5SDimitry Andric     if (target_sp) {
11260b57cec5SDimitry Andric       ProcessSP process_sp(target_sp->GetProcessSP());
11270b57cec5SDimitry Andric       if (process_sp) {
1128c9157d92SDimitry Andric         llvm::StringRef signal_str =
1129c9157d92SDimitry Andric             process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
1130c9157d92SDimitry Andric         process_sp->SetExitStatus(exit_status, signal_str);
11310b57cec5SDimitry Andric       }
11320b57cec5SDimitry Andric     }
11330b57cec5SDimitry Andric     return true;
11340b57cec5SDimitry Andric   }
11350b57cec5SDimitry Andric   return false;
11360b57cec5SDimitry Andric }
11370b57cec5SDimitry Andric 
UpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)1138e8d8bef9SDimitry Andric bool Process::UpdateThreadList(ThreadList &old_thread_list,
1139e8d8bef9SDimitry Andric                                ThreadList &new_thread_list) {
1140e8d8bef9SDimitry Andric   m_thread_plans.ClearThreadCache();
1141e8d8bef9SDimitry Andric   return DoUpdateThreadList(old_thread_list, new_thread_list);
1142e8d8bef9SDimitry Andric }
1143e8d8bef9SDimitry Andric 
UpdateThreadListIfNeeded()11440b57cec5SDimitry Andric void Process::UpdateThreadListIfNeeded() {
11450b57cec5SDimitry Andric   const uint32_t stop_id = GetStopID();
11460b57cec5SDimitry Andric   if (m_thread_list.GetSize(false) == 0 ||
11470b57cec5SDimitry Andric       stop_id != m_thread_list.GetStopID()) {
11485ffd83dbSDimitry Andric     bool clear_unused_threads = true;
11490b57cec5SDimitry Andric     const StateType state = GetPrivateState();
11500b57cec5SDimitry Andric     if (StateIsStoppedState(state, true)) {
11510b57cec5SDimitry Andric       std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
11525ffd83dbSDimitry Andric       m_thread_list.SetStopID(stop_id);
11535ffd83dbSDimitry Andric 
11540b57cec5SDimitry Andric       // m_thread_list does have its own mutex, but we need to hold onto the
11550b57cec5SDimitry Andric       // mutex between the call to UpdateThreadList(...) and the
11560b57cec5SDimitry Andric       // os->UpdateThreadList(...) so it doesn't change on us
11570b57cec5SDimitry Andric       ThreadList &old_thread_list = m_thread_list;
11580b57cec5SDimitry Andric       ThreadList real_thread_list(this);
11590b57cec5SDimitry Andric       ThreadList new_thread_list(this);
11600b57cec5SDimitry Andric       // Always update the thread list with the protocol specific thread list,
11610b57cec5SDimitry Andric       // but only update if "true" is returned
11620b57cec5SDimitry Andric       if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
11630b57cec5SDimitry Andric         // Don't call into the OperatingSystem to update the thread list if we
11640b57cec5SDimitry Andric         // are shutting down, since that may call back into the SBAPI's,
11650b57cec5SDimitry Andric         // requiring the API lock which is already held by whoever is shutting
11660b57cec5SDimitry Andric         // us down, causing a deadlock.
11670b57cec5SDimitry Andric         OperatingSystem *os = GetOperatingSystem();
11680b57cec5SDimitry Andric         if (os && !m_destroy_in_process) {
11690b57cec5SDimitry Andric           // Clear any old backing threads where memory threads might have been
11700b57cec5SDimitry Andric           // backed by actual threads from the lldb_private::Process subclass
11710b57cec5SDimitry Andric           size_t num_old_threads = old_thread_list.GetSize(false);
11720b57cec5SDimitry Andric           for (size_t i = 0; i < num_old_threads; ++i)
11730b57cec5SDimitry Andric             old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
11745ffd83dbSDimitry Andric           // See if the OS plugin reports all threads.  If it does, then
11755ffd83dbSDimitry Andric           // it is safe to clear unseen thread's plans here.  Otherwise we
11765ffd83dbSDimitry Andric           // should preserve them in case they show up again:
11775ffd83dbSDimitry Andric           clear_unused_threads = GetOSPluginReportsAllThreads();
11780b57cec5SDimitry Andric 
11790b57cec5SDimitry Andric           // Turn off dynamic types to ensure we don't run any expressions.
11800b57cec5SDimitry Andric           // Objective-C can run an expression to determine if a SBValue is a
11810b57cec5SDimitry Andric           // dynamic type or not and we need to avoid this. OperatingSystem
11820b57cec5SDimitry Andric           // plug-ins can't run expressions that require running code...
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric           Target &target = GetTarget();
11850b57cec5SDimitry Andric           const lldb::DynamicValueType saved_prefer_dynamic =
11860b57cec5SDimitry Andric               target.GetPreferDynamicValue();
11870b57cec5SDimitry Andric           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
11880b57cec5SDimitry Andric             target.SetPreferDynamicValue(lldb::eNoDynamicValues);
11890b57cec5SDimitry Andric 
11900b57cec5SDimitry Andric           // Now let the OperatingSystem plug-in update the thread list
11910b57cec5SDimitry Andric 
11920b57cec5SDimitry Andric           os->UpdateThreadList(
11930b57cec5SDimitry Andric               old_thread_list, // Old list full of threads created by OS plug-in
11940b57cec5SDimitry Andric               real_thread_list, // The actual thread list full of threads
11950b57cec5SDimitry Andric                                 // created by each lldb_private::Process
11960b57cec5SDimitry Andric                                 // subclass
11970b57cec5SDimitry Andric               new_thread_list); // The new thread list that we will show to the
11980b57cec5SDimitry Andric                                 // user that gets filled in
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
12010b57cec5SDimitry Andric             target.SetPreferDynamicValue(saved_prefer_dynamic);
12020b57cec5SDimitry Andric         } else {
12030b57cec5SDimitry Andric           // No OS plug-in, the new thread list is the same as the real thread
12045ffd83dbSDimitry Andric           // list.
12050b57cec5SDimitry Andric           new_thread_list = real_thread_list;
12060b57cec5SDimitry Andric         }
12070b57cec5SDimitry Andric 
12080b57cec5SDimitry Andric         m_thread_list_real.Update(real_thread_list);
12090b57cec5SDimitry Andric         m_thread_list.Update(new_thread_list);
12100b57cec5SDimitry Andric         m_thread_list.SetStopID(stop_id);
12110b57cec5SDimitry Andric 
12120b57cec5SDimitry Andric         if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
12130b57cec5SDimitry Andric           // Clear any extended threads that we may have accumulated previously
12140b57cec5SDimitry Andric           m_extended_thread_list.Clear();
12150b57cec5SDimitry Andric           m_extended_thread_stop_id = GetLastNaturalStopID();
12160b57cec5SDimitry Andric 
12170b57cec5SDimitry Andric           m_queue_list.Clear();
12180b57cec5SDimitry Andric           m_queue_list_stop_id = GetLastNaturalStopID();
12190b57cec5SDimitry Andric         }
12200b57cec5SDimitry Andric       }
12215ffd83dbSDimitry Andric       // Now update the plan stack map.
12225ffd83dbSDimitry Andric       // If we do have an OS plugin, any absent real threads in the
12235ffd83dbSDimitry Andric       // m_thread_list have already been removed from the ThreadPlanStackMap.
12245ffd83dbSDimitry Andric       // So any remaining threads are OS Plugin threads, and those we want to
12255ffd83dbSDimitry Andric       // preserve in case they show up again.
12265ffd83dbSDimitry Andric       m_thread_plans.Update(m_thread_list, clear_unused_threads);
12270b57cec5SDimitry Andric     }
12280b57cec5SDimitry Andric   }
12290b57cec5SDimitry Andric }
12300b57cec5SDimitry Andric 
FindThreadPlans(lldb::tid_t tid)12315ffd83dbSDimitry Andric ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
12325ffd83dbSDimitry Andric   return m_thread_plans.Find(tid);
12335ffd83dbSDimitry Andric }
12345ffd83dbSDimitry Andric 
PruneThreadPlansForTID(lldb::tid_t tid)12355ffd83dbSDimitry Andric bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
12365ffd83dbSDimitry Andric   return m_thread_plans.PrunePlansForTID(tid);
12375ffd83dbSDimitry Andric }
12385ffd83dbSDimitry Andric 
PruneThreadPlans()12395ffd83dbSDimitry Andric void Process::PruneThreadPlans() {
12405ffd83dbSDimitry Andric   m_thread_plans.Update(GetThreadList(), true, false);
12415ffd83dbSDimitry Andric }
12425ffd83dbSDimitry Andric 
DumpThreadPlansForTID(Stream & strm,lldb::tid_t tid,lldb::DescriptionLevel desc_level,bool internal,bool condense_trivial,bool skip_unreported_plans)12435ffd83dbSDimitry Andric bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
12445ffd83dbSDimitry Andric                                     lldb::DescriptionLevel desc_level,
12455ffd83dbSDimitry Andric                                     bool internal, bool condense_trivial,
12465ffd83dbSDimitry Andric                                     bool skip_unreported_plans) {
12475ffd83dbSDimitry Andric   return m_thread_plans.DumpPlansForTID(
12485ffd83dbSDimitry Andric       strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
12495ffd83dbSDimitry Andric }
DumpThreadPlans(Stream & strm,lldb::DescriptionLevel desc_level,bool internal,bool condense_trivial,bool skip_unreported_plans)12505ffd83dbSDimitry Andric void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
12515ffd83dbSDimitry Andric                               bool internal, bool condense_trivial,
12525ffd83dbSDimitry Andric                               bool skip_unreported_plans) {
12535ffd83dbSDimitry Andric   m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
12545ffd83dbSDimitry Andric                            skip_unreported_plans);
12555ffd83dbSDimitry Andric }
12565ffd83dbSDimitry Andric 
UpdateQueueListIfNeeded()12570b57cec5SDimitry Andric void Process::UpdateQueueListIfNeeded() {
12580b57cec5SDimitry Andric   if (m_system_runtime_up) {
12590b57cec5SDimitry Andric     if (m_queue_list.GetSize() == 0 ||
12600b57cec5SDimitry Andric         m_queue_list_stop_id != GetLastNaturalStopID()) {
12610b57cec5SDimitry Andric       const StateType state = GetPrivateState();
12620b57cec5SDimitry Andric       if (StateIsStoppedState(state, true)) {
12630b57cec5SDimitry Andric         m_system_runtime_up->PopulateQueueList(m_queue_list);
12640b57cec5SDimitry Andric         m_queue_list_stop_id = GetLastNaturalStopID();
12650b57cec5SDimitry Andric       }
12660b57cec5SDimitry Andric     }
12670b57cec5SDimitry Andric   }
12680b57cec5SDimitry Andric }
12690b57cec5SDimitry Andric 
CreateOSPluginThread(lldb::tid_t tid,lldb::addr_t context)12700b57cec5SDimitry Andric ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
12710b57cec5SDimitry Andric   OperatingSystem *os = GetOperatingSystem();
12720b57cec5SDimitry Andric   if (os)
12730b57cec5SDimitry Andric     return os->CreateThread(tid, context);
12740b57cec5SDimitry Andric   return ThreadSP();
12750b57cec5SDimitry Andric }
12760b57cec5SDimitry Andric 
GetNextThreadIndexID(uint64_t thread_id)12770b57cec5SDimitry Andric uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
12780b57cec5SDimitry Andric   return AssignIndexIDToThread(thread_id);
12790b57cec5SDimitry Andric }
12800b57cec5SDimitry Andric 
HasAssignedIndexIDToThread(uint64_t thread_id)12810b57cec5SDimitry Andric bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
12820b57cec5SDimitry Andric   return (m_thread_id_to_index_id_map.find(thread_id) !=
12830b57cec5SDimitry Andric           m_thread_id_to_index_id_map.end());
12840b57cec5SDimitry Andric }
12850b57cec5SDimitry Andric 
AssignIndexIDToThread(uint64_t thread_id)12860b57cec5SDimitry Andric uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
12870b57cec5SDimitry Andric   uint32_t result = 0;
12880b57cec5SDimitry Andric   std::map<uint64_t, uint32_t>::iterator iterator =
12890b57cec5SDimitry Andric       m_thread_id_to_index_id_map.find(thread_id);
12900b57cec5SDimitry Andric   if (iterator == m_thread_id_to_index_id_map.end()) {
12910b57cec5SDimitry Andric     result = ++m_thread_index_id;
12920b57cec5SDimitry Andric     m_thread_id_to_index_id_map[thread_id] = result;
12930b57cec5SDimitry Andric   } else {
12940b57cec5SDimitry Andric     result = iterator->second;
12950b57cec5SDimitry Andric   }
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric   return result;
12980b57cec5SDimitry Andric }
12990b57cec5SDimitry Andric 
GetState()13000b57cec5SDimitry Andric StateType Process::GetState() {
1301bdd1243dSDimitry Andric   if (CurrentThreadIsPrivateStateThread())
1302bdd1243dSDimitry Andric     return m_private_state.GetValue();
1303bdd1243dSDimitry Andric   else
13040b57cec5SDimitry Andric     return m_public_state.GetValue();
13050b57cec5SDimitry Andric }
13060b57cec5SDimitry Andric 
SetPublicState(StateType new_state,bool restarted)13070b57cec5SDimitry Andric void Process::SetPublicState(StateType new_state, bool restarted) {
1308349cc55cSDimitry Andric   const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1309349cc55cSDimitry Andric   if (new_state_is_stopped) {
1310349cc55cSDimitry Andric     // This will only set the time if the public stop time has no value, so
1311349cc55cSDimitry Andric     // it is ok to call this multiple times. With a public stop we can't look
1312349cc55cSDimitry Andric     // at the stop ID because many private stops might have happened, so we
1313349cc55cSDimitry Andric     // can't check for a stop ID of zero. This allows the "statistics" command
1314349cc55cSDimitry Andric     // to dump the time it takes to reach somewhere in your code, like a
1315349cc55cSDimitry Andric     // breakpoint you set.
1316349cc55cSDimitry Andric     GetTarget().GetStatistics().SetFirstPublicStopTime();
1317349cc55cSDimitry Andric   }
1318349cc55cSDimitry Andric 
131981ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::State | LLDBLog::Process));
1320fe013be4SDimitry Andric   LLDB_LOGF(log, "(plugin = %s, state = %s, restarted = %i)",
1321fe013be4SDimitry Andric            GetPluginName().data(), StateAsCString(new_state), restarted);
13220b57cec5SDimitry Andric   const StateType old_state = m_public_state.GetValue();
13230b57cec5SDimitry Andric   m_public_state.SetValue(new_state);
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric   // On the transition from Run to Stopped, we unlock the writer end of the run
13260b57cec5SDimitry Andric   // lock.  The lock gets locked in Resume, which is the public API to tell the
13270b57cec5SDimitry Andric   // program to run.
13280b57cec5SDimitry Andric   if (!StateChangedIsExternallyHijacked()) {
13290b57cec5SDimitry Andric     if (new_state == eStateDetached) {
13309dba64beSDimitry Andric       LLDB_LOGF(log,
1331fe013be4SDimitry Andric                "(plugin = %s, state = %s) -- unlocking run lock for detach",
1332fe013be4SDimitry Andric                GetPluginName().data(), StateAsCString(new_state));
13330b57cec5SDimitry Andric       m_public_run_lock.SetStopped();
13340b57cec5SDimitry Andric     } else {
13350b57cec5SDimitry Andric       const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
13360b57cec5SDimitry Andric       if ((old_state_is_stopped != new_state_is_stopped)) {
13370b57cec5SDimitry Andric         if (new_state_is_stopped && !restarted) {
1338fe013be4SDimitry Andric           LLDB_LOGF(log, "(plugin = %s, state = %s) -- unlocking run lock",
1339fe013be4SDimitry Andric                    GetPluginName().data(), StateAsCString(new_state));
13400b57cec5SDimitry Andric           m_public_run_lock.SetStopped();
13410b57cec5SDimitry Andric         }
13420b57cec5SDimitry Andric       }
13430b57cec5SDimitry Andric     }
13440b57cec5SDimitry Andric   }
13450b57cec5SDimitry Andric }
13460b57cec5SDimitry Andric 
Resume()13470b57cec5SDimitry Andric Status Process::Resume() {
134881ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::State | LLDBLog::Process));
1349fe013be4SDimitry Andric   LLDB_LOGF(log, "(plugin = %s) -- locking run lock", GetPluginName().data());
13500b57cec5SDimitry Andric   if (!m_public_run_lock.TrySetRunning()) {
13510b57cec5SDimitry Andric     Status error("Resume request failed - process still running.");
1352fe013be4SDimitry Andric     LLDB_LOGF(log, "(plugin = %s) -- TrySetRunning failed, not resuming.",
1353fe013be4SDimitry Andric              GetPluginName().data());
13540b57cec5SDimitry Andric     return error;
13550b57cec5SDimitry Andric   }
13560b57cec5SDimitry Andric   Status error = PrivateResume();
13570b57cec5SDimitry Andric   if (!error.Success()) {
13580b57cec5SDimitry Andric     // Undo running state change
13590b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
13600b57cec5SDimitry Andric   }
13610b57cec5SDimitry Andric   return error;
13620b57cec5SDimitry Andric }
13630b57cec5SDimitry Andric 
ResumeSynchronous(Stream * stream)13640b57cec5SDimitry Andric Status Process::ResumeSynchronous(Stream *stream) {
136581ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::State | LLDBLog::Process));
13669dba64beSDimitry Andric   LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
13670b57cec5SDimitry Andric   if (!m_public_run_lock.TrySetRunning()) {
13680b57cec5SDimitry Andric     Status error("Resume request failed - process still running.");
13699dba64beSDimitry Andric     LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
13700b57cec5SDimitry Andric     return error;
13710b57cec5SDimitry Andric   }
13720b57cec5SDimitry Andric 
13730b57cec5SDimitry Andric   ListenerSP listener_sp(
1374fe013be4SDimitry Andric       Listener::MakeListener(ResumeSynchronousHijackListenerName.data()));
13750b57cec5SDimitry Andric   HijackProcessEvents(listener_sp);
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   Status error = PrivateResume();
13780b57cec5SDimitry Andric   if (error.Success()) {
1379bdd1243dSDimitry Andric     StateType state =
1380fe013be4SDimitry Andric         WaitForProcessToStop(std::nullopt, nullptr, true, listener_sp, stream,
1381fe013be4SDimitry Andric                              true /* use_run_lock */, SelectMostRelevantFrame);
13820b57cec5SDimitry Andric     const bool must_be_alive =
13830b57cec5SDimitry Andric         false; // eStateExited is ok, so this must be false
13840b57cec5SDimitry Andric     if (!StateIsStoppedState(state, must_be_alive))
13850b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
13860b57cec5SDimitry Andric           "process not in stopped state after synchronous resume: %s",
13870b57cec5SDimitry Andric           StateAsCString(state));
13880b57cec5SDimitry Andric   } else {
13890b57cec5SDimitry Andric     // Undo running state change
13900b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
13910b57cec5SDimitry Andric   }
13920b57cec5SDimitry Andric 
13930b57cec5SDimitry Andric   // Undo the hijacking of process events...
13940b57cec5SDimitry Andric   RestoreProcessEvents();
13950b57cec5SDimitry Andric 
13960b57cec5SDimitry Andric   return error;
13970b57cec5SDimitry Andric }
13980b57cec5SDimitry Andric 
StateChangedIsExternallyHijacked()13990b57cec5SDimitry Andric bool Process::StateChangedIsExternallyHijacked() {
14000b57cec5SDimitry Andric   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1401fe013be4SDimitry Andric     llvm::StringRef hijacking_name = GetHijackingListenerName();
1402fe013be4SDimitry Andric     if (!hijacking_name.starts_with("lldb.internal"))
14030b57cec5SDimitry Andric       return true;
14040b57cec5SDimitry Andric   }
14050b57cec5SDimitry Andric   return false;
14060b57cec5SDimitry Andric }
14070b57cec5SDimitry Andric 
StateChangedIsHijackedForSynchronousResume()14080b57cec5SDimitry Andric bool Process::StateChangedIsHijackedForSynchronousResume() {
14090b57cec5SDimitry Andric   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1410fe013be4SDimitry Andric     llvm::StringRef hijacking_name = GetHijackingListenerName();
1411fe013be4SDimitry Andric     if (hijacking_name == ResumeSynchronousHijackListenerName)
14120b57cec5SDimitry Andric       return true;
14130b57cec5SDimitry Andric   }
14140b57cec5SDimitry Andric   return false;
14150b57cec5SDimitry Andric }
14160b57cec5SDimitry Andric 
GetPrivateState()14170b57cec5SDimitry Andric StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
14180b57cec5SDimitry Andric 
SetPrivateState(StateType new_state)14190b57cec5SDimitry Andric void Process::SetPrivateState(StateType new_state) {
1420c9157d92SDimitry Andric   // Use m_destructing not m_finalizing here.  If we are finalizing a process
1421c9157d92SDimitry Andric   // that we haven't started tearing down, we'd like to be able to nicely
1422c9157d92SDimitry Andric   // detach if asked, but that requires the event system be live.  That will
1423c9157d92SDimitry Andric   // not be true for an in-the-middle-of-being-destructed Process, since the
1424c9157d92SDimitry Andric   // event system relies on Process::shared_from_this, which may have already
1425c9157d92SDimitry Andric   // been destroyed.
1426c9157d92SDimitry Andric   if (m_destructing)
14270b57cec5SDimitry Andric     return;
14280b57cec5SDimitry Andric 
142981ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::State | LLDBLog::Process | LLDBLog::Unwind));
14300b57cec5SDimitry Andric   bool state_changed = false;
14310b57cec5SDimitry Andric 
1432fe013be4SDimitry Andric   LLDB_LOGF(log, "(plugin = %s, state = %s)", GetPluginName().data(),
1433fe013be4SDimitry Andric            StateAsCString(new_state));
14340b57cec5SDimitry Andric 
14350b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
14360b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   const StateType old_state = m_private_state.GetValueNoLock();
14390b57cec5SDimitry Andric   state_changed = old_state != new_state;
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric   const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
14420b57cec5SDimitry Andric   const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
14430b57cec5SDimitry Andric   if (old_state_is_stopped != new_state_is_stopped) {
14440b57cec5SDimitry Andric     if (new_state_is_stopped)
14450b57cec5SDimitry Andric       m_private_run_lock.SetStopped();
14460b57cec5SDimitry Andric     else
14470b57cec5SDimitry Andric       m_private_run_lock.SetRunning();
14480b57cec5SDimitry Andric   }
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   if (state_changed) {
14510b57cec5SDimitry Andric     m_private_state.SetValueNoLock(new_state);
14520b57cec5SDimitry Andric     EventSP event_sp(
14530b57cec5SDimitry Andric         new Event(eBroadcastBitStateChanged,
14540b57cec5SDimitry Andric                   new ProcessEventData(shared_from_this(), new_state)));
14550b57cec5SDimitry Andric     if (StateIsStoppedState(new_state, false)) {
14560b57cec5SDimitry Andric       // Note, this currently assumes that all threads in the list stop when
14570b57cec5SDimitry Andric       // the process stops.  In the future we will want to support a debugging
14580b57cec5SDimitry Andric       // model where some threads continue to run while others are stopped.
14590b57cec5SDimitry Andric       // When that happens we will either need a way for the thread list to
14600b57cec5SDimitry Andric       // identify which threads are stopping or create a special thread list
14610b57cec5SDimitry Andric       // containing only threads which actually stopped.
14620b57cec5SDimitry Andric       //
14630b57cec5SDimitry Andric       // The process plugin is responsible for managing the actual behavior of
14640b57cec5SDimitry Andric       // the threads and should have stopped any threads that are going to stop
14650b57cec5SDimitry Andric       // before we get here.
14660b57cec5SDimitry Andric       m_thread_list.DidStop();
14670b57cec5SDimitry Andric 
1468349cc55cSDimitry Andric       if (m_mod_id.BumpStopID() == 0)
1469349cc55cSDimitry Andric         GetTarget().GetStatistics().SetFirstPrivateStopTime();
1470349cc55cSDimitry Andric 
14710b57cec5SDimitry Andric       if (!m_mod_id.IsLastResumeForUserExpression())
14720b57cec5SDimitry Andric         m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
14730b57cec5SDimitry Andric       m_memory_cache.Clear();
1474fe013be4SDimitry Andric       LLDB_LOGF(log, "(plugin = %s, state = %s, stop_id = %u",
1475fe013be4SDimitry Andric                GetPluginName().data(), StateAsCString(new_state),
1476fe013be4SDimitry Andric                m_mod_id.GetStopID());
14770b57cec5SDimitry Andric     }
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric     m_private_state_broadcaster.BroadcastEvent(event_sp);
14800b57cec5SDimitry Andric   } else {
1481fe013be4SDimitry Andric     LLDB_LOGF(log, "(plugin = %s, state = %s) state didn't change. Ignoring...",
1482fe013be4SDimitry Andric              GetPluginName().data(), StateAsCString(new_state));
14830b57cec5SDimitry Andric   }
14840b57cec5SDimitry Andric }
14850b57cec5SDimitry Andric 
SetRunningUserExpression(bool on)14860b57cec5SDimitry Andric void Process::SetRunningUserExpression(bool on) {
14870b57cec5SDimitry Andric   m_mod_id.SetRunningUserExpression(on);
14880b57cec5SDimitry Andric }
14890b57cec5SDimitry Andric 
SetRunningUtilityFunction(bool on)14900b57cec5SDimitry Andric void Process::SetRunningUtilityFunction(bool on) {
14910b57cec5SDimitry Andric   m_mod_id.SetRunningUtilityFunction(on);
14920b57cec5SDimitry Andric }
14930b57cec5SDimitry Andric 
GetImageInfoAddress()14940b57cec5SDimitry Andric addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
14950b57cec5SDimitry Andric 
GetABI()14960b57cec5SDimitry Andric const lldb::ABISP &Process::GetABI() {
14970b57cec5SDimitry Andric   if (!m_abi_sp)
14980b57cec5SDimitry Andric     m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
14990b57cec5SDimitry Andric   return m_abi_sp;
15000b57cec5SDimitry Andric }
15010b57cec5SDimitry Andric 
GetLanguageRuntimes()1502480093f4SDimitry Andric std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
15030b57cec5SDimitry Andric   std::vector<LanguageRuntime *> language_runtimes;
15040b57cec5SDimitry Andric 
15050b57cec5SDimitry Andric   if (m_finalizing)
15060b57cec5SDimitry Andric     return language_runtimes;
15070b57cec5SDimitry Andric 
15080b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
15090b57cec5SDimitry Andric   // Before we pass off a copy of the language runtimes, we must make sure that
15100b57cec5SDimitry Andric   // our collection is properly populated. It's possible that some of the
15110b57cec5SDimitry Andric   // language runtimes were not loaded yet, either because nobody requested it
15120b57cec5SDimitry Andric   // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
15130b57cec5SDimitry Andric   // hadn't been loaded).
15140b57cec5SDimitry Andric   for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1515480093f4SDimitry Andric     if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
15160b57cec5SDimitry Andric       language_runtimes.emplace_back(runtime);
15170b57cec5SDimitry Andric   }
15180b57cec5SDimitry Andric 
15190b57cec5SDimitry Andric   return language_runtimes;
15200b57cec5SDimitry Andric }
15210b57cec5SDimitry Andric 
GetLanguageRuntime(lldb::LanguageType language)1522480093f4SDimitry Andric LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
15230b57cec5SDimitry Andric   if (m_finalizing)
15240b57cec5SDimitry Andric     return nullptr;
15250b57cec5SDimitry Andric 
15260b57cec5SDimitry Andric   LanguageRuntime *runtime = nullptr;
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
15290b57cec5SDimitry Andric   LanguageRuntimeCollection::iterator pos;
15300b57cec5SDimitry Andric   pos = m_language_runtimes.find(language);
1531480093f4SDimitry Andric   if (pos == m_language_runtimes.end() || !pos->second) {
15320b57cec5SDimitry Andric     lldb::LanguageRuntimeSP runtime_sp(
15330b57cec5SDimitry Andric         LanguageRuntime::FindPlugin(this, language));
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric     m_language_runtimes[language] = runtime_sp;
15360b57cec5SDimitry Andric     runtime = runtime_sp.get();
15370b57cec5SDimitry Andric   } else
15380b57cec5SDimitry Andric     runtime = pos->second.get();
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric   if (runtime)
15410b57cec5SDimitry Andric     // It's possible that a language runtime can support multiple LanguageTypes,
15420b57cec5SDimitry Andric     // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
15430b57cec5SDimitry Andric     // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
15440b57cec5SDimitry Andric     // primary language type and make sure that our runtime supports it.
15450b57cec5SDimitry Andric     assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
15460b57cec5SDimitry Andric 
15470b57cec5SDimitry Andric   return runtime;
15480b57cec5SDimitry Andric }
15490b57cec5SDimitry Andric 
IsPossibleDynamicValue(ValueObject & in_value)15500b57cec5SDimitry Andric bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
15510b57cec5SDimitry Andric   if (m_finalizing)
15520b57cec5SDimitry Andric     return false;
15530b57cec5SDimitry Andric 
15540b57cec5SDimitry Andric   if (in_value.IsDynamic())
15550b57cec5SDimitry Andric     return false;
15560b57cec5SDimitry Andric   LanguageType known_type = in_value.GetObjectRuntimeLanguage();
15570b57cec5SDimitry Andric 
15580b57cec5SDimitry Andric   if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
15590b57cec5SDimitry Andric     LanguageRuntime *runtime = GetLanguageRuntime(known_type);
15600b57cec5SDimitry Andric     return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
15610b57cec5SDimitry Andric   }
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric   for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
15640b57cec5SDimitry Andric     if (runtime->CouldHaveDynamicValue(in_value))
15650b57cec5SDimitry Andric       return true;
15660b57cec5SDimitry Andric   }
15670b57cec5SDimitry Andric 
15680b57cec5SDimitry Andric   return false;
15690b57cec5SDimitry Andric }
15700b57cec5SDimitry Andric 
SetDynamicCheckers(DynamicCheckerFunctions * dynamic_checkers)15710b57cec5SDimitry Andric void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
15720b57cec5SDimitry Andric   m_dynamic_checkers_up.reset(dynamic_checkers);
15730b57cec5SDimitry Andric }
15740b57cec5SDimitry Andric 
GetBreakpointSiteList()1575c9157d92SDimitry Andric StopPointSiteList<BreakpointSite> &Process::GetBreakpointSiteList() {
15760b57cec5SDimitry Andric   return m_breakpoint_site_list;
15770b57cec5SDimitry Andric }
15780b57cec5SDimitry Andric 
1579c9157d92SDimitry Andric const StopPointSiteList<BreakpointSite> &
GetBreakpointSiteList() const1580c9157d92SDimitry Andric Process::GetBreakpointSiteList() const {
15810b57cec5SDimitry Andric   return m_breakpoint_site_list;
15820b57cec5SDimitry Andric }
15830b57cec5SDimitry Andric 
DisableAllBreakpointSites()15840b57cec5SDimitry Andric void Process::DisableAllBreakpointSites() {
15850b57cec5SDimitry Andric   m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
15860b57cec5SDimitry Andric     //        bp_site->SetEnabled(true);
15870b57cec5SDimitry Andric     DisableBreakpointSite(bp_site);
15880b57cec5SDimitry Andric   });
15890b57cec5SDimitry Andric }
15900b57cec5SDimitry Andric 
ClearBreakpointSiteByID(lldb::user_id_t break_id)15910b57cec5SDimitry Andric Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
15920b57cec5SDimitry Andric   Status error(DisableBreakpointSiteByID(break_id));
15930b57cec5SDimitry Andric 
15940b57cec5SDimitry Andric   if (error.Success())
15950b57cec5SDimitry Andric     m_breakpoint_site_list.Remove(break_id);
15960b57cec5SDimitry Andric 
15970b57cec5SDimitry Andric   return error;
15980b57cec5SDimitry Andric }
15990b57cec5SDimitry Andric 
DisableBreakpointSiteByID(lldb::user_id_t break_id)16000b57cec5SDimitry Andric Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
16010b57cec5SDimitry Andric   Status error;
16020b57cec5SDimitry Andric   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
16030b57cec5SDimitry Andric   if (bp_site_sp) {
16040b57cec5SDimitry Andric     if (bp_site_sp->IsEnabled())
16050b57cec5SDimitry Andric       error = DisableBreakpointSite(bp_site_sp.get());
16060b57cec5SDimitry Andric   } else {
16070b57cec5SDimitry Andric     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
16080b57cec5SDimitry Andric                                    break_id);
16090b57cec5SDimitry Andric   }
16100b57cec5SDimitry Andric 
16110b57cec5SDimitry Andric   return error;
16120b57cec5SDimitry Andric }
16130b57cec5SDimitry Andric 
EnableBreakpointSiteByID(lldb::user_id_t break_id)16140b57cec5SDimitry Andric Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
16150b57cec5SDimitry Andric   Status error;
16160b57cec5SDimitry Andric   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
16170b57cec5SDimitry Andric   if (bp_site_sp) {
16180b57cec5SDimitry Andric     if (!bp_site_sp->IsEnabled())
16190b57cec5SDimitry Andric       error = EnableBreakpointSite(bp_site_sp.get());
16200b57cec5SDimitry Andric   } else {
16210b57cec5SDimitry Andric     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
16220b57cec5SDimitry Andric                                    break_id);
16230b57cec5SDimitry Andric   }
16240b57cec5SDimitry Andric   return error;
16250b57cec5SDimitry Andric }
16260b57cec5SDimitry Andric 
16270b57cec5SDimitry Andric lldb::break_id_t
CreateBreakpointSite(const BreakpointLocationSP & constituent,bool use_hardware)1628c9157d92SDimitry Andric Process::CreateBreakpointSite(const BreakpointLocationSP &constituent,
16290b57cec5SDimitry Andric                               bool use_hardware) {
16300b57cec5SDimitry Andric   addr_t load_addr = LLDB_INVALID_ADDRESS;
16310b57cec5SDimitry Andric 
16320b57cec5SDimitry Andric   bool show_error = true;
16330b57cec5SDimitry Andric   switch (GetState()) {
16340b57cec5SDimitry Andric   case eStateInvalid:
16350b57cec5SDimitry Andric   case eStateUnloaded:
16360b57cec5SDimitry Andric   case eStateConnected:
16370b57cec5SDimitry Andric   case eStateAttaching:
16380b57cec5SDimitry Andric   case eStateLaunching:
16390b57cec5SDimitry Andric   case eStateDetached:
16400b57cec5SDimitry Andric   case eStateExited:
16410b57cec5SDimitry Andric     show_error = false;
16420b57cec5SDimitry Andric     break;
16430b57cec5SDimitry Andric 
16440b57cec5SDimitry Andric   case eStateStopped:
16450b57cec5SDimitry Andric   case eStateRunning:
16460b57cec5SDimitry Andric   case eStateStepping:
16470b57cec5SDimitry Andric   case eStateCrashed:
16480b57cec5SDimitry Andric   case eStateSuspended:
16490b57cec5SDimitry Andric     show_error = IsAlive();
16500b57cec5SDimitry Andric     break;
16510b57cec5SDimitry Andric   }
16520b57cec5SDimitry Andric 
16530b57cec5SDimitry Andric   // Reset the IsIndirect flag here, in case the location changes from pointing
16540b57cec5SDimitry Andric   // to a indirect symbol to a regular symbol.
1655c9157d92SDimitry Andric   constituent->SetIsIndirect(false);
16560b57cec5SDimitry Andric 
1657c9157d92SDimitry Andric   if (constituent->ShouldResolveIndirectFunctions()) {
1658c9157d92SDimitry Andric     Symbol *symbol = constituent->GetAddress().CalculateSymbolContextSymbol();
16590b57cec5SDimitry Andric     if (symbol && symbol->IsIndirect()) {
16600b57cec5SDimitry Andric       Status error;
16610b57cec5SDimitry Andric       Address symbol_address = symbol->GetAddress();
16620b57cec5SDimitry Andric       load_addr = ResolveIndirectFunction(&symbol_address, error);
16630b57cec5SDimitry Andric       if (!error.Success() && show_error) {
16649dba64beSDimitry Andric         GetTarget().GetDebugger().GetErrorStream().Printf(
16650b57cec5SDimitry Andric             "warning: failed to resolve indirect function at 0x%" PRIx64
16660b57cec5SDimitry Andric             " for breakpoint %i.%i: %s\n",
16670b57cec5SDimitry Andric             symbol->GetLoadAddress(&GetTarget()),
1668c9157d92SDimitry Andric             constituent->GetBreakpoint().GetID(), constituent->GetID(),
16690b57cec5SDimitry Andric             error.AsCString() ? error.AsCString() : "unknown error");
16700b57cec5SDimitry Andric         return LLDB_INVALID_BREAK_ID;
16710b57cec5SDimitry Andric       }
16720b57cec5SDimitry Andric       Address resolved_address(load_addr);
16730b57cec5SDimitry Andric       load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1674c9157d92SDimitry Andric       constituent->SetIsIndirect(true);
16750b57cec5SDimitry Andric     } else
1676c9157d92SDimitry Andric       load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
16770b57cec5SDimitry Andric   } else
1678c9157d92SDimitry Andric     load_addr = constituent->GetAddress().GetOpcodeLoadAddress(&GetTarget());
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric   if (load_addr != LLDB_INVALID_ADDRESS) {
16810b57cec5SDimitry Andric     BreakpointSiteSP bp_site_sp;
16820b57cec5SDimitry Andric 
1683c9157d92SDimitry Andric     // Look up this breakpoint site.  If it exists, then add this new
1684c9157d92SDimitry Andric     // constituent, otherwise create a new breakpoint site and add it.
16850b57cec5SDimitry Andric 
16860b57cec5SDimitry Andric     bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
16870b57cec5SDimitry Andric 
16880b57cec5SDimitry Andric     if (bp_site_sp) {
1689c9157d92SDimitry Andric       bp_site_sp->AddConstituent(constituent);
1690c9157d92SDimitry Andric       constituent->SetBreakpointSite(bp_site_sp);
16910b57cec5SDimitry Andric       return bp_site_sp->GetID();
16920b57cec5SDimitry Andric     } else {
1693c9157d92SDimitry Andric       bp_site_sp.reset(
1694c9157d92SDimitry Andric           new BreakpointSite(constituent, load_addr, use_hardware));
16950b57cec5SDimitry Andric       if (bp_site_sp) {
16960b57cec5SDimitry Andric         Status error = EnableBreakpointSite(bp_site_sp.get());
16970b57cec5SDimitry Andric         if (error.Success()) {
1698c9157d92SDimitry Andric           constituent->SetBreakpointSite(bp_site_sp);
16990b57cec5SDimitry Andric           return m_breakpoint_site_list.Add(bp_site_sp);
17000b57cec5SDimitry Andric         } else {
17010b57cec5SDimitry Andric           if (show_error || use_hardware) {
17020b57cec5SDimitry Andric             // Report error for setting breakpoint...
17039dba64beSDimitry Andric             GetTarget().GetDebugger().GetErrorStream().Printf(
17040b57cec5SDimitry Andric                 "warning: failed to set breakpoint site at 0x%" PRIx64
17050b57cec5SDimitry Andric                 " for breakpoint %i.%i: %s\n",
1706c9157d92SDimitry Andric                 load_addr, constituent->GetBreakpoint().GetID(),
1707c9157d92SDimitry Andric                 constituent->GetID(),
17080b57cec5SDimitry Andric                 error.AsCString() ? error.AsCString() : "unknown error");
17090b57cec5SDimitry Andric           }
17100b57cec5SDimitry Andric         }
17110b57cec5SDimitry Andric       }
17120b57cec5SDimitry Andric     }
17130b57cec5SDimitry Andric   }
17140b57cec5SDimitry Andric   // We failed to enable the breakpoint
17150b57cec5SDimitry Andric   return LLDB_INVALID_BREAK_ID;
17160b57cec5SDimitry Andric }
17170b57cec5SDimitry Andric 
RemoveConstituentFromBreakpointSite(lldb::user_id_t constituent_id,lldb::user_id_t constituent_loc_id,BreakpointSiteSP & bp_site_sp)1718c9157d92SDimitry Andric void Process::RemoveConstituentFromBreakpointSite(
1719c9157d92SDimitry Andric     lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,
17200b57cec5SDimitry Andric     BreakpointSiteSP &bp_site_sp) {
1721c9157d92SDimitry Andric   uint32_t num_constituents =
1722c9157d92SDimitry Andric       bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);
1723c9157d92SDimitry Andric   if (num_constituents == 0) {
17240b57cec5SDimitry Andric     // Don't try to disable the site if we don't have a live process anymore.
17250b57cec5SDimitry Andric     if (IsAlive())
17260b57cec5SDimitry Andric       DisableBreakpointSite(bp_site_sp.get());
17270b57cec5SDimitry Andric     m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
17280b57cec5SDimitry Andric   }
17290b57cec5SDimitry Andric }
17300b57cec5SDimitry Andric 
RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr,size_t size,uint8_t * buf) const17310b57cec5SDimitry Andric size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
17320b57cec5SDimitry Andric                                                   uint8_t *buf) const {
17330b57cec5SDimitry Andric   size_t bytes_removed = 0;
1734c9157d92SDimitry Andric   StopPointSiteList<BreakpointSite> bp_sites_in_range;
17350b57cec5SDimitry Andric 
17360b57cec5SDimitry Andric   if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
17370b57cec5SDimitry Andric                                          bp_sites_in_range)) {
17380b57cec5SDimitry Andric     bp_sites_in_range.ForEach([bp_addr, size,
17390b57cec5SDimitry Andric                                buf](BreakpointSite *bp_site) -> void {
17400b57cec5SDimitry Andric       if (bp_site->GetType() == BreakpointSite::eSoftware) {
17410b57cec5SDimitry Andric         addr_t intersect_addr;
17420b57cec5SDimitry Andric         size_t intersect_size;
17430b57cec5SDimitry Andric         size_t opcode_offset;
17440b57cec5SDimitry Andric         if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
17450b57cec5SDimitry Andric                                      &intersect_size, &opcode_offset)) {
17460b57cec5SDimitry Andric           assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
17470b57cec5SDimitry Andric           assert(bp_addr < intersect_addr + intersect_size &&
17480b57cec5SDimitry Andric                  intersect_addr + intersect_size <= bp_addr + size);
17490b57cec5SDimitry Andric           assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
17500b57cec5SDimitry Andric           size_t buf_offset = intersect_addr - bp_addr;
17510b57cec5SDimitry Andric           ::memcpy(buf + buf_offset,
17520b57cec5SDimitry Andric                    bp_site->GetSavedOpcodeBytes() + opcode_offset,
17530b57cec5SDimitry Andric                    intersect_size);
17540b57cec5SDimitry Andric         }
17550b57cec5SDimitry Andric       }
17560b57cec5SDimitry Andric     });
17570b57cec5SDimitry Andric   }
17580b57cec5SDimitry Andric   return bytes_removed;
17590b57cec5SDimitry Andric }
17600b57cec5SDimitry Andric 
GetSoftwareBreakpointTrapOpcode(BreakpointSite * bp_site)17610b57cec5SDimitry Andric size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
17620b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
17630b57cec5SDimitry Andric   if (platform_sp)
17640b57cec5SDimitry Andric     return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
17650b57cec5SDimitry Andric   return 0;
17660b57cec5SDimitry Andric }
17670b57cec5SDimitry Andric 
EnableSoftwareBreakpoint(BreakpointSite * bp_site)17680b57cec5SDimitry Andric Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
17690b57cec5SDimitry Andric   Status error;
17700b57cec5SDimitry Andric   assert(bp_site != nullptr);
177181ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Breakpoints);
17720b57cec5SDimitry Andric   const addr_t bp_addr = bp_site->GetLoadAddress();
17739dba64beSDimitry Andric   LLDB_LOGF(
17749dba64beSDimitry Andric       log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
17750b57cec5SDimitry Andric       bp_site->GetID(), (uint64_t)bp_addr);
17760b57cec5SDimitry Andric   if (bp_site->IsEnabled()) {
17779dba64beSDimitry Andric     LLDB_LOGF(
17789dba64beSDimitry Andric         log,
17790b57cec5SDimitry Andric         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
17800b57cec5SDimitry Andric         " -- already enabled",
17810b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr);
17820b57cec5SDimitry Andric     return error;
17830b57cec5SDimitry Andric   }
17840b57cec5SDimitry Andric 
17850b57cec5SDimitry Andric   if (bp_addr == LLDB_INVALID_ADDRESS) {
17860b57cec5SDimitry Andric     error.SetErrorString("BreakpointSite contains an invalid load address.");
17870b57cec5SDimitry Andric     return error;
17880b57cec5SDimitry Andric   }
17890b57cec5SDimitry Andric   // Ask the lldb::Process subclass to fill in the correct software breakpoint
17900b57cec5SDimitry Andric   // trap for the breakpoint site
17910b57cec5SDimitry Andric   const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
17920b57cec5SDimitry Andric 
17930b57cec5SDimitry Andric   if (bp_opcode_size == 0) {
17940b57cec5SDimitry Andric     error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
17950b57cec5SDimitry Andric                                    "returned zero, unable to get breakpoint "
17960b57cec5SDimitry Andric                                    "trap for address 0x%" PRIx64,
17970b57cec5SDimitry Andric                                    bp_addr);
17980b57cec5SDimitry Andric   } else {
17990b57cec5SDimitry Andric     const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
18000b57cec5SDimitry Andric 
18010b57cec5SDimitry Andric     if (bp_opcode_bytes == nullptr) {
18020b57cec5SDimitry Andric       error.SetErrorString(
18030b57cec5SDimitry Andric           "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
18040b57cec5SDimitry Andric       return error;
18050b57cec5SDimitry Andric     }
18060b57cec5SDimitry Andric 
18070b57cec5SDimitry Andric     // Save the original opcode by reading it
18080b57cec5SDimitry Andric     if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
18090b57cec5SDimitry Andric                      error) == bp_opcode_size) {
18100b57cec5SDimitry Andric       // Write a software breakpoint in place of the original opcode
18110b57cec5SDimitry Andric       if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
18120b57cec5SDimitry Andric           bp_opcode_size) {
18130b57cec5SDimitry Andric         uint8_t verify_bp_opcode_bytes[64];
18140b57cec5SDimitry Andric         if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
18150b57cec5SDimitry Andric                          error) == bp_opcode_size) {
18160b57cec5SDimitry Andric           if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
18170b57cec5SDimitry Andric                        bp_opcode_size) == 0) {
18180b57cec5SDimitry Andric             bp_site->SetEnabled(true);
18190b57cec5SDimitry Andric             bp_site->SetType(BreakpointSite::eSoftware);
18209dba64beSDimitry Andric             LLDB_LOGF(log,
18219dba64beSDimitry Andric                       "Process::EnableSoftwareBreakpoint (site_id = %d) "
18220b57cec5SDimitry Andric                       "addr = 0x%" PRIx64 " -- SUCCESS",
18230b57cec5SDimitry Andric                       bp_site->GetID(), (uint64_t)bp_addr);
18240b57cec5SDimitry Andric           } else
18250b57cec5SDimitry Andric             error.SetErrorString(
18260b57cec5SDimitry Andric                 "failed to verify the breakpoint trap in memory.");
18270b57cec5SDimitry Andric         } else
18280b57cec5SDimitry Andric           error.SetErrorString(
18290b57cec5SDimitry Andric               "Unable to read memory to verify breakpoint trap.");
18300b57cec5SDimitry Andric       } else
18310b57cec5SDimitry Andric         error.SetErrorString("Unable to write breakpoint trap to memory.");
18320b57cec5SDimitry Andric     } else
18330b57cec5SDimitry Andric       error.SetErrorString("Unable to read memory at breakpoint address.");
18340b57cec5SDimitry Andric   }
18350b57cec5SDimitry Andric   if (log && error.Fail())
18369dba64beSDimitry Andric     LLDB_LOGF(
18379dba64beSDimitry Andric         log,
18380b57cec5SDimitry Andric         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
18390b57cec5SDimitry Andric         " -- FAILED: %s",
18400b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
18410b57cec5SDimitry Andric   return error;
18420b57cec5SDimitry Andric }
18430b57cec5SDimitry Andric 
DisableSoftwareBreakpoint(BreakpointSite * bp_site)18440b57cec5SDimitry Andric Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
18450b57cec5SDimitry Andric   Status error;
18460b57cec5SDimitry Andric   assert(bp_site != nullptr);
184781ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Breakpoints);
18480b57cec5SDimitry Andric   addr_t bp_addr = bp_site->GetLoadAddress();
18490b57cec5SDimitry Andric   lldb::user_id_t breakID = bp_site->GetID();
18509dba64beSDimitry Andric   LLDB_LOGF(log,
18519dba64beSDimitry Andric             "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
18520b57cec5SDimitry Andric             ") addr = 0x%" PRIx64,
18530b57cec5SDimitry Andric             breakID, (uint64_t)bp_addr);
18540b57cec5SDimitry Andric 
18550b57cec5SDimitry Andric   if (bp_site->IsHardware()) {
18560b57cec5SDimitry Andric     error.SetErrorString("Breakpoint site is a hardware breakpoint.");
18570b57cec5SDimitry Andric   } else if (bp_site->IsEnabled()) {
18580b57cec5SDimitry Andric     const size_t break_op_size = bp_site->GetByteSize();
18590b57cec5SDimitry Andric     const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
18600b57cec5SDimitry Andric     if (break_op_size > 0) {
18610b57cec5SDimitry Andric       // Clear a software breakpoint instruction
18620b57cec5SDimitry Andric       uint8_t curr_break_op[8];
18630b57cec5SDimitry Andric       assert(break_op_size <= sizeof(curr_break_op));
18640b57cec5SDimitry Andric       bool break_op_found = false;
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric       // Read the breakpoint opcode
18670b57cec5SDimitry Andric       if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
18680b57cec5SDimitry Andric           break_op_size) {
18690b57cec5SDimitry Andric         bool verify = false;
18700b57cec5SDimitry Andric         // Make sure the breakpoint opcode exists at this address
18710b57cec5SDimitry Andric         if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
18720b57cec5SDimitry Andric           break_op_found = true;
18730b57cec5SDimitry Andric           // We found a valid breakpoint opcode at this address, now restore
18740b57cec5SDimitry Andric           // the saved opcode.
18750b57cec5SDimitry Andric           if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
18760b57cec5SDimitry Andric                             break_op_size, error) == break_op_size) {
18770b57cec5SDimitry Andric             verify = true;
18780b57cec5SDimitry Andric           } else
18790b57cec5SDimitry Andric             error.SetErrorString(
18800b57cec5SDimitry Andric                 "Memory write failed when restoring original opcode.");
18810b57cec5SDimitry Andric         } else {
18820b57cec5SDimitry Andric           error.SetErrorString(
18830b57cec5SDimitry Andric               "Original breakpoint trap is no longer in memory.");
18840b57cec5SDimitry Andric           // Set verify to true and so we can check if the original opcode has
18850b57cec5SDimitry Andric           // already been restored
18860b57cec5SDimitry Andric           verify = true;
18870b57cec5SDimitry Andric         }
18880b57cec5SDimitry Andric 
18890b57cec5SDimitry Andric         if (verify) {
18900b57cec5SDimitry Andric           uint8_t verify_opcode[8];
18910b57cec5SDimitry Andric           assert(break_op_size < sizeof(verify_opcode));
18920b57cec5SDimitry Andric           // Verify that our original opcode made it back to the inferior
18930b57cec5SDimitry Andric           if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
18940b57cec5SDimitry Andric               break_op_size) {
18950b57cec5SDimitry Andric             // compare the memory we just read with the original opcode
18960b57cec5SDimitry Andric             if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
18970b57cec5SDimitry Andric                          break_op_size) == 0) {
18980b57cec5SDimitry Andric               // SUCCESS
18990b57cec5SDimitry Andric               bp_site->SetEnabled(false);
19009dba64beSDimitry Andric               LLDB_LOGF(log,
19019dba64beSDimitry Andric                         "Process::DisableSoftwareBreakpoint (site_id = %d) "
19020b57cec5SDimitry Andric                         "addr = 0x%" PRIx64 " -- SUCCESS",
19030b57cec5SDimitry Andric                         bp_site->GetID(), (uint64_t)bp_addr);
19040b57cec5SDimitry Andric               return error;
19050b57cec5SDimitry Andric             } else {
19060b57cec5SDimitry Andric               if (break_op_found)
19070b57cec5SDimitry Andric                 error.SetErrorString("Failed to restore original opcode.");
19080b57cec5SDimitry Andric             }
19090b57cec5SDimitry Andric           } else
19100b57cec5SDimitry Andric             error.SetErrorString("Failed to read memory to verify that "
19110b57cec5SDimitry Andric                                  "breakpoint trap was restored.");
19120b57cec5SDimitry Andric         }
19130b57cec5SDimitry Andric       } else
19140b57cec5SDimitry Andric         error.SetErrorString(
19150b57cec5SDimitry Andric             "Unable to read memory that should contain the breakpoint trap.");
19160b57cec5SDimitry Andric     }
19170b57cec5SDimitry Andric   } else {
19189dba64beSDimitry Andric     LLDB_LOGF(
19199dba64beSDimitry Andric         log,
19200b57cec5SDimitry Andric         "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
19210b57cec5SDimitry Andric         " -- already disabled",
19220b57cec5SDimitry Andric         bp_site->GetID(), (uint64_t)bp_addr);
19230b57cec5SDimitry Andric     return error;
19240b57cec5SDimitry Andric   }
19250b57cec5SDimitry Andric 
19269dba64beSDimitry Andric   LLDB_LOGF(
19279dba64beSDimitry Andric       log,
19280b57cec5SDimitry Andric       "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
19290b57cec5SDimitry Andric       " -- FAILED: %s",
19300b57cec5SDimitry Andric       bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
19310b57cec5SDimitry Andric   return error;
19320b57cec5SDimitry Andric }
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric // Uncomment to verify memory caching works after making changes to caching
19350b57cec5SDimitry Andric // code
19360b57cec5SDimitry Andric //#define VERIFY_MEMORY_READS
19370b57cec5SDimitry Andric 
ReadMemory(addr_t addr,void * buf,size_t size,Status & error)19380b57cec5SDimitry Andric size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
193981ad6265SDimitry Andric   if (ABISP abi_sp = GetABI())
194081ad6265SDimitry Andric     addr = abi_sp->FixAnyAddress(addr);
194181ad6265SDimitry Andric 
19420b57cec5SDimitry Andric   error.Clear();
19430b57cec5SDimitry Andric   if (!GetDisableMemoryCache()) {
19440b57cec5SDimitry Andric #if defined(VERIFY_MEMORY_READS)
19450b57cec5SDimitry Andric     // Memory caching is enabled, with debug verification
19460b57cec5SDimitry Andric 
19470b57cec5SDimitry Andric     if (buf && size) {
19480b57cec5SDimitry Andric       // Uncomment the line below to make sure memory caching is working.
19490b57cec5SDimitry Andric       // I ran this through the test suite and got no assertions, so I am
19500b57cec5SDimitry Andric       // pretty confident this is working well. If any changes are made to
19510b57cec5SDimitry Andric       // memory caching, uncomment the line below and test your changes!
19520b57cec5SDimitry Andric 
19530b57cec5SDimitry Andric       // Verify all memory reads by using the cache first, then redundantly
19540b57cec5SDimitry Andric       // reading the same memory from the inferior and comparing to make sure
19550b57cec5SDimitry Andric       // everything is exactly the same.
19560b57cec5SDimitry Andric       std::string verify_buf(size, '\0');
19570b57cec5SDimitry Andric       assert(verify_buf.size() == size);
19580b57cec5SDimitry Andric       const size_t cache_bytes_read =
19590b57cec5SDimitry Andric           m_memory_cache.Read(this, addr, buf, size, error);
19600b57cec5SDimitry Andric       Status verify_error;
19610b57cec5SDimitry Andric       const size_t verify_bytes_read =
19620b57cec5SDimitry Andric           ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
19630b57cec5SDimitry Andric                                  verify_buf.size(), verify_error);
19640b57cec5SDimitry Andric       assert(cache_bytes_read == verify_bytes_read);
19650b57cec5SDimitry Andric       assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
19660b57cec5SDimitry Andric       assert(verify_error.Success() == error.Success());
19670b57cec5SDimitry Andric       return cache_bytes_read;
19680b57cec5SDimitry Andric     }
19690b57cec5SDimitry Andric     return 0;
19700b57cec5SDimitry Andric #else  // !defined(VERIFY_MEMORY_READS)
19710b57cec5SDimitry Andric     // Memory caching is enabled, without debug verification
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric     return m_memory_cache.Read(addr, buf, size, error);
19740b57cec5SDimitry Andric #endif // defined (VERIFY_MEMORY_READS)
19750b57cec5SDimitry Andric   } else {
19760b57cec5SDimitry Andric     // Memory caching is disabled
19770b57cec5SDimitry Andric 
19780b57cec5SDimitry Andric     return ReadMemoryFromInferior(addr, buf, size, error);
19790b57cec5SDimitry Andric   }
19800b57cec5SDimitry Andric }
19810b57cec5SDimitry Andric 
ReadCStringFromMemory(addr_t addr,std::string & out_str,Status & error)19820b57cec5SDimitry Andric size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
19830b57cec5SDimitry Andric                                       Status &error) {
19840b57cec5SDimitry Andric   char buf[256];
19850b57cec5SDimitry Andric   out_str.clear();
19860b57cec5SDimitry Andric   addr_t curr_addr = addr;
19870b57cec5SDimitry Andric   while (true) {
19880b57cec5SDimitry Andric     size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
19890b57cec5SDimitry Andric     if (length == 0)
19900b57cec5SDimitry Andric       break;
19910b57cec5SDimitry Andric     out_str.append(buf, length);
19920b57cec5SDimitry Andric     // If we got "length - 1" bytes, we didn't get the whole C string, we need
19930b57cec5SDimitry Andric     // to read some more characters
19940b57cec5SDimitry Andric     if (length == sizeof(buf) - 1)
19950b57cec5SDimitry Andric       curr_addr += length;
19960b57cec5SDimitry Andric     else
19970b57cec5SDimitry Andric       break;
19980b57cec5SDimitry Andric   }
19990b57cec5SDimitry Andric   return out_str.size();
20000b57cec5SDimitry Andric }
20010b57cec5SDimitry Andric 
20020b57cec5SDimitry Andric // Deprecated in favor of ReadStringFromMemory which has wchar support and
20030b57cec5SDimitry Andric // correct code to find null terminators.
ReadCStringFromMemory(addr_t addr,char * dst,size_t dst_max_len,Status & result_error)20040b57cec5SDimitry Andric size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
20050b57cec5SDimitry Andric                                       size_t dst_max_len,
20060b57cec5SDimitry Andric                                       Status &result_error) {
20070b57cec5SDimitry Andric   size_t total_cstr_len = 0;
20080b57cec5SDimitry Andric   if (dst && dst_max_len) {
20090b57cec5SDimitry Andric     result_error.Clear();
20100b57cec5SDimitry Andric     // NULL out everything just to be safe
20110b57cec5SDimitry Andric     memset(dst, 0, dst_max_len);
20120b57cec5SDimitry Andric     Status error;
20130b57cec5SDimitry Andric     addr_t curr_addr = addr;
20140b57cec5SDimitry Andric     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
20150b57cec5SDimitry Andric     size_t bytes_left = dst_max_len - 1;
20160b57cec5SDimitry Andric     char *curr_dst = dst;
20170b57cec5SDimitry Andric 
20180b57cec5SDimitry Andric     while (bytes_left > 0) {
20190b57cec5SDimitry Andric       addr_t cache_line_bytes_left =
20200b57cec5SDimitry Andric           cache_line_size - (curr_addr % cache_line_size);
20210b57cec5SDimitry Andric       addr_t bytes_to_read =
20220b57cec5SDimitry Andric           std::min<addr_t>(bytes_left, cache_line_bytes_left);
20230b57cec5SDimitry Andric       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
20240b57cec5SDimitry Andric 
20250b57cec5SDimitry Andric       if (bytes_read == 0) {
20260b57cec5SDimitry Andric         result_error = error;
20270b57cec5SDimitry Andric         dst[total_cstr_len] = '\0';
20280b57cec5SDimitry Andric         break;
20290b57cec5SDimitry Andric       }
20300b57cec5SDimitry Andric       const size_t len = strlen(curr_dst);
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric       total_cstr_len += len;
20330b57cec5SDimitry Andric 
20340b57cec5SDimitry Andric       if (len < bytes_to_read)
20350b57cec5SDimitry Andric         break;
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric       curr_dst += bytes_read;
20380b57cec5SDimitry Andric       curr_addr += bytes_read;
20390b57cec5SDimitry Andric       bytes_left -= bytes_read;
20400b57cec5SDimitry Andric     }
20410b57cec5SDimitry Andric   } else {
20420b57cec5SDimitry Andric     if (dst == nullptr)
20430b57cec5SDimitry Andric       result_error.SetErrorString("invalid arguments");
20440b57cec5SDimitry Andric     else
20450b57cec5SDimitry Andric       result_error.Clear();
20460b57cec5SDimitry Andric   }
20470b57cec5SDimitry Andric   return total_cstr_len;
20480b57cec5SDimitry Andric }
20490b57cec5SDimitry Andric 
ReadMemoryFromInferior(addr_t addr,void * buf,size_t size,Status & error)20500b57cec5SDimitry Andric size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
20510b57cec5SDimitry Andric                                        Status &error) {
2052fe6060f1SDimitry Andric   LLDB_SCOPED_TIMER();
2053fe6060f1SDimitry Andric 
205481ad6265SDimitry Andric   if (ABISP abi_sp = GetABI())
205581ad6265SDimitry Andric     addr = abi_sp->FixAnyAddress(addr);
205681ad6265SDimitry Andric 
20570b57cec5SDimitry Andric   if (buf == nullptr || size == 0)
20580b57cec5SDimitry Andric     return 0;
20590b57cec5SDimitry Andric 
20600b57cec5SDimitry Andric   size_t bytes_read = 0;
20610b57cec5SDimitry Andric   uint8_t *bytes = (uint8_t *)buf;
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   while (bytes_read < size) {
20640b57cec5SDimitry Andric     const size_t curr_size = size - bytes_read;
20650b57cec5SDimitry Andric     const size_t curr_bytes_read =
20660b57cec5SDimitry Andric         DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
20670b57cec5SDimitry Andric     bytes_read += curr_bytes_read;
20680b57cec5SDimitry Andric     if (curr_bytes_read == curr_size || curr_bytes_read == 0)
20690b57cec5SDimitry Andric       break;
20700b57cec5SDimitry Andric   }
20710b57cec5SDimitry Andric 
20720b57cec5SDimitry Andric   // Replace any software breakpoint opcodes that fall into this range back
20730b57cec5SDimitry Andric   // into "buf" before we return
20740b57cec5SDimitry Andric   if (bytes_read > 0)
20750b57cec5SDimitry Andric     RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
20760b57cec5SDimitry Andric   return bytes_read;
20770b57cec5SDimitry Andric }
20780b57cec5SDimitry Andric 
ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,size_t integer_byte_size,uint64_t fail_value,Status & error)20790b57cec5SDimitry Andric uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
20800b57cec5SDimitry Andric                                                 size_t integer_byte_size,
20810b57cec5SDimitry Andric                                                 uint64_t fail_value,
20820b57cec5SDimitry Andric                                                 Status &error) {
20830b57cec5SDimitry Andric   Scalar scalar;
20840b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
20850b57cec5SDimitry Andric                                   error))
20860b57cec5SDimitry Andric     return scalar.ULongLong(fail_value);
20870b57cec5SDimitry Andric   return fail_value;
20880b57cec5SDimitry Andric }
20890b57cec5SDimitry Andric 
ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,size_t integer_byte_size,int64_t fail_value,Status & error)20900b57cec5SDimitry Andric int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
20910b57cec5SDimitry Andric                                              size_t integer_byte_size,
20920b57cec5SDimitry Andric                                              int64_t fail_value,
20930b57cec5SDimitry Andric                                              Status &error) {
20940b57cec5SDimitry Andric   Scalar scalar;
20950b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
20960b57cec5SDimitry Andric                                   error))
20970b57cec5SDimitry Andric     return scalar.SLongLong(fail_value);
20980b57cec5SDimitry Andric   return fail_value;
20990b57cec5SDimitry Andric }
21000b57cec5SDimitry Andric 
ReadPointerFromMemory(lldb::addr_t vm_addr,Status & error)21010b57cec5SDimitry Andric addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
21020b57cec5SDimitry Andric   Scalar scalar;
21030b57cec5SDimitry Andric   if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
21040b57cec5SDimitry Andric                                   error))
21050b57cec5SDimitry Andric     return scalar.ULongLong(LLDB_INVALID_ADDRESS);
21060b57cec5SDimitry Andric   return LLDB_INVALID_ADDRESS;
21070b57cec5SDimitry Andric }
21080b57cec5SDimitry Andric 
WritePointerToMemory(lldb::addr_t vm_addr,lldb::addr_t ptr_value,Status & error)21090b57cec5SDimitry Andric bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
21100b57cec5SDimitry Andric                                    Status &error) {
21110b57cec5SDimitry Andric   Scalar scalar;
21120b57cec5SDimitry Andric   const uint32_t addr_byte_size = GetAddressByteSize();
21130b57cec5SDimitry Andric   if (addr_byte_size <= 4)
21140b57cec5SDimitry Andric     scalar = (uint32_t)ptr_value;
21150b57cec5SDimitry Andric   else
21160b57cec5SDimitry Andric     scalar = ptr_value;
21170b57cec5SDimitry Andric   return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
21180b57cec5SDimitry Andric          addr_byte_size;
21190b57cec5SDimitry Andric }
21200b57cec5SDimitry Andric 
WriteMemoryPrivate(addr_t addr,const void * buf,size_t size,Status & error)21210b57cec5SDimitry Andric size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
21220b57cec5SDimitry Andric                                    Status &error) {
21230b57cec5SDimitry Andric   size_t bytes_written = 0;
21240b57cec5SDimitry Andric   const uint8_t *bytes = (const uint8_t *)buf;
21250b57cec5SDimitry Andric 
21260b57cec5SDimitry Andric   while (bytes_written < size) {
21270b57cec5SDimitry Andric     const size_t curr_size = size - bytes_written;
21280b57cec5SDimitry Andric     const size_t curr_bytes_written = DoWriteMemory(
21290b57cec5SDimitry Andric         addr + bytes_written, bytes + bytes_written, curr_size, error);
21300b57cec5SDimitry Andric     bytes_written += curr_bytes_written;
21310b57cec5SDimitry Andric     if (curr_bytes_written == curr_size || curr_bytes_written == 0)
21320b57cec5SDimitry Andric       break;
21330b57cec5SDimitry Andric   }
21340b57cec5SDimitry Andric   return bytes_written;
21350b57cec5SDimitry Andric }
21360b57cec5SDimitry Andric 
WriteMemory(addr_t addr,const void * buf,size_t size,Status & error)21370b57cec5SDimitry Andric size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
21380b57cec5SDimitry Andric                             Status &error) {
213981ad6265SDimitry Andric   if (ABISP abi_sp = GetABI())
214081ad6265SDimitry Andric     addr = abi_sp->FixAnyAddress(addr);
214181ad6265SDimitry Andric 
21420b57cec5SDimitry Andric #if defined(ENABLE_MEMORY_CACHING)
21430b57cec5SDimitry Andric   m_memory_cache.Flush(addr, size);
21440b57cec5SDimitry Andric #endif
21450b57cec5SDimitry Andric 
21460b57cec5SDimitry Andric   if (buf == nullptr || size == 0)
21470b57cec5SDimitry Andric     return 0;
21480b57cec5SDimitry Andric 
21490b57cec5SDimitry Andric   m_mod_id.BumpMemoryID();
21500b57cec5SDimitry Andric 
21510b57cec5SDimitry Andric   // We need to write any data that would go where any current software traps
21520b57cec5SDimitry Andric   // (enabled software breakpoints) any software traps (breakpoints) that we
21530b57cec5SDimitry Andric   // may have placed in our tasks memory.
21540b57cec5SDimitry Andric 
2155c9157d92SDimitry Andric   StopPointSiteList<BreakpointSite> bp_sites_in_range;
21560b57cec5SDimitry Andric   if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
21570b57cec5SDimitry Andric     return WriteMemoryPrivate(addr, buf, size, error);
21580b57cec5SDimitry Andric 
21590b57cec5SDimitry Andric   // No breakpoint sites overlap
21600b57cec5SDimitry Andric   if (bp_sites_in_range.IsEmpty())
21610b57cec5SDimitry Andric     return WriteMemoryPrivate(addr, buf, size, error);
21620b57cec5SDimitry Andric 
21630b57cec5SDimitry Andric   const uint8_t *ubuf = (const uint8_t *)buf;
21640b57cec5SDimitry Andric   uint64_t bytes_written = 0;
21650b57cec5SDimitry Andric 
21660b57cec5SDimitry Andric   bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
21670b57cec5SDimitry Andric                              &error](BreakpointSite *bp) -> void {
21680b57cec5SDimitry Andric     if (error.Fail())
21690b57cec5SDimitry Andric       return;
21700b57cec5SDimitry Andric 
2171e8d8bef9SDimitry Andric     if (bp->GetType() != BreakpointSite::eSoftware)
2172e8d8bef9SDimitry Andric       return;
2173e8d8bef9SDimitry Andric 
21740b57cec5SDimitry Andric     addr_t intersect_addr;
21750b57cec5SDimitry Andric     size_t intersect_size;
21760b57cec5SDimitry Andric     size_t opcode_offset;
21770b57cec5SDimitry Andric     const bool intersects = bp->IntersectsRange(
21780b57cec5SDimitry Andric         addr, size, &intersect_addr, &intersect_size, &opcode_offset);
21790b57cec5SDimitry Andric     UNUSED_IF_ASSERT_DISABLED(intersects);
21800b57cec5SDimitry Andric     assert(intersects);
21810b57cec5SDimitry Andric     assert(addr <= intersect_addr && intersect_addr < addr + size);
21820b57cec5SDimitry Andric     assert(addr < intersect_addr + intersect_size &&
21830b57cec5SDimitry Andric            intersect_addr + intersect_size <= addr + size);
21840b57cec5SDimitry Andric     assert(opcode_offset + intersect_size <= bp->GetByteSize());
21850b57cec5SDimitry Andric 
21860b57cec5SDimitry Andric     // Check for bytes before this breakpoint
21870b57cec5SDimitry Andric     const addr_t curr_addr = addr + bytes_written;
21880b57cec5SDimitry Andric     if (intersect_addr > curr_addr) {
21890b57cec5SDimitry Andric       // There are some bytes before this breakpoint that we need to just
21900b57cec5SDimitry Andric       // write to memory
21910b57cec5SDimitry Andric       size_t curr_size = intersect_addr - curr_addr;
21920b57cec5SDimitry Andric       size_t curr_bytes_written =
21930b57cec5SDimitry Andric           WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
21940b57cec5SDimitry Andric       bytes_written += curr_bytes_written;
21950b57cec5SDimitry Andric       if (curr_bytes_written != curr_size) {
21960b57cec5SDimitry Andric         // We weren't able to write all of the requested bytes, we are
21970b57cec5SDimitry Andric         // done looping and will return the number of bytes that we have
21980b57cec5SDimitry Andric         // written so far.
21990b57cec5SDimitry Andric         if (error.Success())
22000b57cec5SDimitry Andric           error.SetErrorToGenericError();
22010b57cec5SDimitry Andric       }
22020b57cec5SDimitry Andric     }
22030b57cec5SDimitry Andric     // Now write any bytes that would cover up any software breakpoints
22040b57cec5SDimitry Andric     // directly into the breakpoint opcode buffer
22050b57cec5SDimitry Andric     ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
22060b57cec5SDimitry Andric              intersect_size);
22070b57cec5SDimitry Andric     bytes_written += intersect_size;
22080b57cec5SDimitry Andric   });
22090b57cec5SDimitry Andric 
22100b57cec5SDimitry Andric   // Write any remaining bytes after the last breakpoint if we have any left
22110b57cec5SDimitry Andric   if (bytes_written < size)
22120b57cec5SDimitry Andric     bytes_written +=
22130b57cec5SDimitry Andric         WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
22140b57cec5SDimitry Andric                            size - bytes_written, error);
22150b57cec5SDimitry Andric 
22160b57cec5SDimitry Andric   return bytes_written;
22170b57cec5SDimitry Andric }
22180b57cec5SDimitry Andric 
WriteScalarToMemory(addr_t addr,const Scalar & scalar,size_t byte_size,Status & error)22190b57cec5SDimitry Andric size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
22200b57cec5SDimitry Andric                                     size_t byte_size, Status &error) {
22210b57cec5SDimitry Andric   if (byte_size == UINT32_MAX)
22220b57cec5SDimitry Andric     byte_size = scalar.GetByteSize();
22230b57cec5SDimitry Andric   if (byte_size > 0) {
22240b57cec5SDimitry Andric     uint8_t buf[32];
22250b57cec5SDimitry Andric     const size_t mem_size =
22260b57cec5SDimitry Andric         scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
22270b57cec5SDimitry Andric     if (mem_size > 0)
22280b57cec5SDimitry Andric       return WriteMemory(addr, buf, mem_size, error);
22290b57cec5SDimitry Andric     else
22300b57cec5SDimitry Andric       error.SetErrorString("failed to get scalar as memory data");
22310b57cec5SDimitry Andric   } else {
22320b57cec5SDimitry Andric     error.SetErrorString("invalid scalar value");
22330b57cec5SDimitry Andric   }
22340b57cec5SDimitry Andric   return 0;
22350b57cec5SDimitry Andric }
22360b57cec5SDimitry Andric 
ReadScalarIntegerFromMemory(addr_t addr,uint32_t byte_size,bool is_signed,Scalar & scalar,Status & error)22370b57cec5SDimitry Andric size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
22380b57cec5SDimitry Andric                                             bool is_signed, Scalar &scalar,
22390b57cec5SDimitry Andric                                             Status &error) {
22400b57cec5SDimitry Andric   uint64_t uval = 0;
22410b57cec5SDimitry Andric   if (byte_size == 0) {
22420b57cec5SDimitry Andric     error.SetErrorString("byte size is zero");
22430b57cec5SDimitry Andric   } else if (byte_size & (byte_size - 1)) {
22440b57cec5SDimitry Andric     error.SetErrorStringWithFormat("byte size %u is not a power of 2",
22450b57cec5SDimitry Andric                                    byte_size);
22460b57cec5SDimitry Andric   } else if (byte_size <= sizeof(uval)) {
22470b57cec5SDimitry Andric     const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
22480b57cec5SDimitry Andric     if (bytes_read == byte_size) {
22490b57cec5SDimitry Andric       DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
22500b57cec5SDimitry Andric                          GetAddressByteSize());
22510b57cec5SDimitry Andric       lldb::offset_t offset = 0;
22520b57cec5SDimitry Andric       if (byte_size <= 4)
22530b57cec5SDimitry Andric         scalar = data.GetMaxU32(&offset, byte_size);
22540b57cec5SDimitry Andric       else
22550b57cec5SDimitry Andric         scalar = data.GetMaxU64(&offset, byte_size);
22560b57cec5SDimitry Andric       if (is_signed)
22570b57cec5SDimitry Andric         scalar.SignExtend(byte_size * 8);
22580b57cec5SDimitry Andric       return bytes_read;
22590b57cec5SDimitry Andric     }
22600b57cec5SDimitry Andric   } else {
22610b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
22620b57cec5SDimitry Andric         "byte size of %u is too large for integer scalar type", byte_size);
22630b57cec5SDimitry Andric   }
22640b57cec5SDimitry Andric   return 0;
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric 
WriteObjectFile(std::vector<ObjectFile::LoadableData> entries)22670b57cec5SDimitry Andric Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
22680b57cec5SDimitry Andric   Status error;
22690b57cec5SDimitry Andric   for (const auto &Entry : entries) {
22700b57cec5SDimitry Andric     WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
22710b57cec5SDimitry Andric                 error);
22720b57cec5SDimitry Andric     if (!error.Success())
22730b57cec5SDimitry Andric       break;
22740b57cec5SDimitry Andric   }
22750b57cec5SDimitry Andric   return error;
22760b57cec5SDimitry Andric }
22770b57cec5SDimitry Andric 
22780b57cec5SDimitry Andric #define USE_ALLOCATE_MEMORY_CACHE 1
AllocateMemory(size_t size,uint32_t permissions,Status & error)22790b57cec5SDimitry Andric addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
22800b57cec5SDimitry Andric                                Status &error) {
22810b57cec5SDimitry Andric   if (GetPrivateState() != eStateStopped) {
22820b57cec5SDimitry Andric     error.SetErrorToGenericError();
22830b57cec5SDimitry Andric     return LLDB_INVALID_ADDRESS;
22840b57cec5SDimitry Andric   }
22850b57cec5SDimitry Andric 
22860b57cec5SDimitry Andric #if defined(USE_ALLOCATE_MEMORY_CACHE)
22870b57cec5SDimitry Andric   return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
22880b57cec5SDimitry Andric #else
22890b57cec5SDimitry Andric   addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
229081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
22919dba64beSDimitry Andric   LLDB_LOGF(log,
22929dba64beSDimitry Andric             "Process::AllocateMemory(size=%" PRIu64
22930b57cec5SDimitry Andric             ", permissions=%s) => 0x%16.16" PRIx64
22940b57cec5SDimitry Andric             " (m_stop_id = %u m_memory_id = %u)",
22950b57cec5SDimitry Andric             (uint64_t)size, GetPermissionsAsCString(permissions),
22960b57cec5SDimitry Andric             (uint64_t)allocated_addr, m_mod_id.GetStopID(),
22970b57cec5SDimitry Andric             m_mod_id.GetMemoryID());
22980b57cec5SDimitry Andric   return allocated_addr;
22990b57cec5SDimitry Andric #endif
23000b57cec5SDimitry Andric }
23010b57cec5SDimitry Andric 
CallocateMemory(size_t size,uint32_t permissions,Status & error)23020b57cec5SDimitry Andric addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
23030b57cec5SDimitry Andric                                 Status &error) {
23040b57cec5SDimitry Andric   addr_t return_addr = AllocateMemory(size, permissions, error);
23050b57cec5SDimitry Andric   if (error.Success()) {
23060b57cec5SDimitry Andric     std::string buffer(size, 0);
23070b57cec5SDimitry Andric     WriteMemory(return_addr, buffer.c_str(), size, error);
23080b57cec5SDimitry Andric   }
23090b57cec5SDimitry Andric   return return_addr;
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
CanJIT()23120b57cec5SDimitry Andric bool Process::CanJIT() {
23130b57cec5SDimitry Andric   if (m_can_jit == eCanJITDontKnow) {
231481ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
23150b57cec5SDimitry Andric     Status err;
23160b57cec5SDimitry Andric 
23170b57cec5SDimitry Andric     uint64_t allocated_memory = AllocateMemory(
23180b57cec5SDimitry Andric         8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
23190b57cec5SDimitry Andric         err);
23200b57cec5SDimitry Andric 
23210b57cec5SDimitry Andric     if (err.Success()) {
23220b57cec5SDimitry Andric       m_can_jit = eCanJITYes;
23239dba64beSDimitry Andric       LLDB_LOGF(log,
23249dba64beSDimitry Andric                 "Process::%s pid %" PRIu64
23250b57cec5SDimitry Andric                 " allocation test passed, CanJIT () is true",
23260b57cec5SDimitry Andric                 __FUNCTION__, GetID());
23270b57cec5SDimitry Andric     } else {
23280b57cec5SDimitry Andric       m_can_jit = eCanJITNo;
23299dba64beSDimitry Andric       LLDB_LOGF(log,
23309dba64beSDimitry Andric                 "Process::%s pid %" PRIu64
23310b57cec5SDimitry Andric                 " allocation test failed, CanJIT () is false: %s",
23320b57cec5SDimitry Andric                 __FUNCTION__, GetID(), err.AsCString());
23330b57cec5SDimitry Andric     }
23340b57cec5SDimitry Andric 
23350b57cec5SDimitry Andric     DeallocateMemory(allocated_memory);
23360b57cec5SDimitry Andric   }
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric   return m_can_jit == eCanJITYes;
23390b57cec5SDimitry Andric }
23400b57cec5SDimitry Andric 
SetCanJIT(bool can_jit)23410b57cec5SDimitry Andric void Process::SetCanJIT(bool can_jit) {
23420b57cec5SDimitry Andric   m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
23430b57cec5SDimitry Andric }
23440b57cec5SDimitry Andric 
SetCanRunCode(bool can_run_code)23450b57cec5SDimitry Andric void Process::SetCanRunCode(bool can_run_code) {
23460b57cec5SDimitry Andric   SetCanJIT(can_run_code);
23470b57cec5SDimitry Andric   m_can_interpret_function_calls = can_run_code;
23480b57cec5SDimitry Andric }
23490b57cec5SDimitry Andric 
DeallocateMemory(addr_t ptr)23500b57cec5SDimitry Andric Status Process::DeallocateMemory(addr_t ptr) {
23510b57cec5SDimitry Andric   Status error;
23520b57cec5SDimitry Andric #if defined(USE_ALLOCATE_MEMORY_CACHE)
23530b57cec5SDimitry Andric   if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
23540b57cec5SDimitry Andric     error.SetErrorStringWithFormat(
23550b57cec5SDimitry Andric         "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
23560b57cec5SDimitry Andric   }
23570b57cec5SDimitry Andric #else
23580b57cec5SDimitry Andric   error = DoDeallocateMemory(ptr);
23590b57cec5SDimitry Andric 
236081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
23619dba64beSDimitry Andric   LLDB_LOGF(log,
23629dba64beSDimitry Andric             "Process::DeallocateMemory(addr=0x%16.16" PRIx64
23630b57cec5SDimitry Andric             ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
23640b57cec5SDimitry Andric             ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
23650b57cec5SDimitry Andric             m_mod_id.GetMemoryID());
23660b57cec5SDimitry Andric #endif
23670b57cec5SDimitry Andric   return error;
23680b57cec5SDimitry Andric }
23690b57cec5SDimitry Andric 
GetWatchpointReportedAfter()2370fe013be4SDimitry Andric bool Process::GetWatchpointReportedAfter() {
2371fe013be4SDimitry Andric   if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2372fe013be4SDimitry Andric     return *subclass_override;
2373fe013be4SDimitry Andric 
2374fe013be4SDimitry Andric   bool reported_after = true;
2375fe013be4SDimitry Andric   const ArchSpec &arch = GetTarget().GetArchitecture();
2376fe013be4SDimitry Andric   if (!arch.IsValid())
2377fe013be4SDimitry Andric     return reported_after;
2378fe013be4SDimitry Andric   llvm::Triple triple = arch.GetTriple();
2379fe013be4SDimitry Andric 
2380fe013be4SDimitry Andric   if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2381fe013be4SDimitry Andric       triple.isAArch64() || triple.isArmMClass() || triple.isARM())
2382fe013be4SDimitry Andric     reported_after = false;
2383fe013be4SDimitry Andric 
2384fe013be4SDimitry Andric   return reported_after;
2385fe013be4SDimitry Andric }
2386fe013be4SDimitry Andric 
ReadModuleFromMemory(const FileSpec & file_spec,lldb::addr_t header_addr,size_t size_to_read)23870b57cec5SDimitry Andric ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
23880b57cec5SDimitry Andric                                        lldb::addr_t header_addr,
23890b57cec5SDimitry Andric                                        size_t size_to_read) {
239081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Host);
23910b57cec5SDimitry Andric   if (log) {
23929dba64beSDimitry Andric     LLDB_LOGF(log,
23939dba64beSDimitry Andric               "Process::ReadModuleFromMemory reading %s binary from memory",
23940b57cec5SDimitry Andric               file_spec.GetPath().c_str());
23950b57cec5SDimitry Andric   }
23960b57cec5SDimitry Andric   ModuleSP module_sp(new Module(file_spec, ArchSpec()));
23970b57cec5SDimitry Andric   if (module_sp) {
23980b57cec5SDimitry Andric     Status error;
23990b57cec5SDimitry Andric     ObjectFile *objfile = module_sp->GetMemoryObjectFile(
24000b57cec5SDimitry Andric         shared_from_this(), header_addr, error, size_to_read);
24010b57cec5SDimitry Andric     if (objfile)
24020b57cec5SDimitry Andric       return module_sp;
24030b57cec5SDimitry Andric   }
24040b57cec5SDimitry Andric   return ModuleSP();
24050b57cec5SDimitry Andric }
24060b57cec5SDimitry Andric 
GetLoadAddressPermissions(lldb::addr_t load_addr,uint32_t & permissions)24070b57cec5SDimitry Andric bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
24080b57cec5SDimitry Andric                                         uint32_t &permissions) {
24090b57cec5SDimitry Andric   MemoryRegionInfo range_info;
24100b57cec5SDimitry Andric   permissions = 0;
24110b57cec5SDimitry Andric   Status error(GetMemoryRegionInfo(load_addr, range_info));
24120b57cec5SDimitry Andric   if (!error.Success())
24130b57cec5SDimitry Andric     return false;
24140b57cec5SDimitry Andric   if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
24150b57cec5SDimitry Andric       range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
24160b57cec5SDimitry Andric       range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
24170b57cec5SDimitry Andric     return false;
24180b57cec5SDimitry Andric   }
2419c9157d92SDimitry Andric   permissions = range_info.GetLLDBPermissions();
24200b57cec5SDimitry Andric   return true;
24210b57cec5SDimitry Andric }
24220b57cec5SDimitry Andric 
EnableWatchpoint(WatchpointSP wp_sp,bool notify)2423c9157d92SDimitry Andric Status Process::EnableWatchpoint(WatchpointSP wp_sp, bool notify) {
24240b57cec5SDimitry Andric   Status error;
24250b57cec5SDimitry Andric   error.SetErrorString("watchpoints are not supported");
24260b57cec5SDimitry Andric   return error;
24270b57cec5SDimitry Andric }
24280b57cec5SDimitry Andric 
DisableWatchpoint(WatchpointSP wp_sp,bool notify)2429c9157d92SDimitry Andric Status Process::DisableWatchpoint(WatchpointSP wp_sp, bool notify) {
24300b57cec5SDimitry Andric   Status error;
24310b57cec5SDimitry Andric   error.SetErrorString("watchpoints are not supported");
24320b57cec5SDimitry Andric   return error;
24330b57cec5SDimitry Andric }
24340b57cec5SDimitry Andric 
24350b57cec5SDimitry Andric StateType
WaitForProcessStopPrivate(EventSP & event_sp,const Timeout<std::micro> & timeout)24360b57cec5SDimitry Andric Process::WaitForProcessStopPrivate(EventSP &event_sp,
24370b57cec5SDimitry Andric                                    const Timeout<std::micro> &timeout) {
24380b57cec5SDimitry Andric   StateType state;
24390b57cec5SDimitry Andric 
24400b57cec5SDimitry Andric   while (true) {
24410b57cec5SDimitry Andric     event_sp.reset();
24420b57cec5SDimitry Andric     state = GetStateChangedEventsPrivate(event_sp, timeout);
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric     if (StateIsStoppedState(state, false))
24450b57cec5SDimitry Andric       break;
24460b57cec5SDimitry Andric 
24470b57cec5SDimitry Andric     // If state is invalid, then we timed out
24480b57cec5SDimitry Andric     if (state == eStateInvalid)
24490b57cec5SDimitry Andric       break;
24500b57cec5SDimitry Andric 
24510b57cec5SDimitry Andric     if (event_sp)
24520b57cec5SDimitry Andric       HandlePrivateEvent(event_sp);
24530b57cec5SDimitry Andric   }
24540b57cec5SDimitry Andric   return state;
24550b57cec5SDimitry Andric }
24560b57cec5SDimitry Andric 
LoadOperatingSystemPlugin(bool flush)24570b57cec5SDimitry Andric void Process::LoadOperatingSystemPlugin(bool flush) {
2458fe013be4SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
24590b57cec5SDimitry Andric   if (flush)
24600b57cec5SDimitry Andric     m_thread_list.Clear();
24610b57cec5SDimitry Andric   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
24620b57cec5SDimitry Andric   if (flush)
24630b57cec5SDimitry Andric     Flush();
24640b57cec5SDimitry Andric }
24650b57cec5SDimitry Andric 
Launch(ProcessLaunchInfo & launch_info)24660b57cec5SDimitry Andric Status Process::Launch(ProcessLaunchInfo &launch_info) {
246781ad6265SDimitry Andric   StateType state_after_launch = eStateInvalid;
246881ad6265SDimitry Andric   EventSP first_stop_event_sp;
246981ad6265SDimitry Andric   Status status =
247081ad6265SDimitry Andric       LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
247181ad6265SDimitry Andric   if (status.Fail())
247281ad6265SDimitry Andric     return status;
247381ad6265SDimitry Andric 
247481ad6265SDimitry Andric   if (state_after_launch != eStateStopped &&
247581ad6265SDimitry Andric       state_after_launch != eStateCrashed)
247681ad6265SDimitry Andric     return Status();
247781ad6265SDimitry Andric 
247881ad6265SDimitry Andric   // Note, the stop event was consumed above, but not handled. This
247981ad6265SDimitry Andric   // was done to give DidLaunch a chance to run. The target is either
248081ad6265SDimitry Andric   // stopped or crashed. Directly set the state.  This is done to
248181ad6265SDimitry Andric   // prevent a stop message with a bunch of spurious output on thread
248281ad6265SDimitry Andric   // status, as well as not pop a ProcessIOHandler.
248381ad6265SDimitry Andric   SetPublicState(state_after_launch, false);
248481ad6265SDimitry Andric 
248581ad6265SDimitry Andric   if (PrivateStateThreadIsValid())
248681ad6265SDimitry Andric     ResumePrivateStateThread();
248781ad6265SDimitry Andric   else
248881ad6265SDimitry Andric     StartPrivateStateThread();
248981ad6265SDimitry Andric 
249081ad6265SDimitry Andric   // Target was stopped at entry as was intended. Need to notify the
249181ad6265SDimitry Andric   // listeners about it.
249281ad6265SDimitry Andric   if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
249381ad6265SDimitry Andric     HandlePrivateEvent(first_stop_event_sp);
249481ad6265SDimitry Andric 
249581ad6265SDimitry Andric   return Status();
249681ad6265SDimitry Andric }
249781ad6265SDimitry Andric 
LaunchPrivate(ProcessLaunchInfo & launch_info,StateType & state,EventSP & event_sp)249881ad6265SDimitry Andric Status Process::LaunchPrivate(ProcessLaunchInfo &launch_info, StateType &state,
249981ad6265SDimitry Andric                               EventSP &event_sp) {
25000b57cec5SDimitry Andric   Status error;
25010b57cec5SDimitry Andric   m_abi_sp.reset();
25020b57cec5SDimitry Andric   m_dyld_up.reset();
25030b57cec5SDimitry Andric   m_jit_loaders_up.reset();
25040b57cec5SDimitry Andric   m_system_runtime_up.reset();
25050b57cec5SDimitry Andric   m_os_up.reset();
2506c9157d92SDimitry Andric 
2507c9157d92SDimitry Andric   {
2508c9157d92SDimitry Andric     std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
25090b57cec5SDimitry Andric     m_process_input_reader.reset();
2510c9157d92SDimitry Andric   }
25110b57cec5SDimitry Andric 
25120b57cec5SDimitry Andric   Module *exe_module = GetTarget().GetExecutableModulePointer();
2513349cc55cSDimitry Andric 
2514349cc55cSDimitry Andric   // The "remote executable path" is hooked up to the local Executable
2515349cc55cSDimitry Andric   // module.  But we should be able to debug a remote process even if the
2516349cc55cSDimitry Andric   // executable module only exists on the remote.  However, there needs to
2517349cc55cSDimitry Andric   // be a way to express this path, without actually having a module.
2518349cc55cSDimitry Andric   // The way to do that is to set the ExecutableFile in the LaunchInfo.
2519349cc55cSDimitry Andric   // Figure that out here:
2520349cc55cSDimitry Andric 
2521349cc55cSDimitry Andric   FileSpec exe_spec_to_use;
25220b57cec5SDimitry Andric   if (!exe_module) {
2523fe013be4SDimitry Andric     if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
25240b57cec5SDimitry Andric       error.SetErrorString("executable module does not exist");
25250b57cec5SDimitry Andric       return error;
25260b57cec5SDimitry Andric     }
2527349cc55cSDimitry Andric     exe_spec_to_use = launch_info.GetExecutableFile();
2528349cc55cSDimitry Andric   } else
2529349cc55cSDimitry Andric     exe_spec_to_use = exe_module->GetFileSpec();
25300b57cec5SDimitry Andric 
2531349cc55cSDimitry Andric   if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
25320b57cec5SDimitry Andric     // Install anything that might need to be installed prior to launching.
25330b57cec5SDimitry Andric     // For host systems, this will do nothing, but if we are connected to a
25340b57cec5SDimitry Andric     // remote platform it will install any needed binaries
25350b57cec5SDimitry Andric     error = GetTarget().Install(&launch_info);
25360b57cec5SDimitry Andric     if (error.Fail())
25370b57cec5SDimitry Andric       return error;
2538349cc55cSDimitry Andric   }
253981ad6265SDimitry Andric 
2540fe6060f1SDimitry Andric   // Listen and queue events that are broadcasted during the process launch.
2541fe6060f1SDimitry Andric   ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2542fe6060f1SDimitry Andric   HijackProcessEvents(listener_sp);
2543fe6060f1SDimitry Andric   auto on_exit = llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2544fe6060f1SDimitry Andric 
25450b57cec5SDimitry Andric   if (PrivateStateThreadIsValid())
25460b57cec5SDimitry Andric     PausePrivateStateThread();
25470b57cec5SDimitry Andric 
25480b57cec5SDimitry Andric   error = WillLaunch(exe_module);
254981ad6265SDimitry Andric   if (error.Fail()) {
255081ad6265SDimitry Andric     std::string local_exec_file_path = exe_spec_to_use.GetPath();
255181ad6265SDimitry Andric     return Status("file doesn't exist: '%s'", local_exec_file_path.c_str());
255281ad6265SDimitry Andric   }
255381ad6265SDimitry Andric 
25540b57cec5SDimitry Andric   const bool restarted = false;
25550b57cec5SDimitry Andric   SetPublicState(eStateLaunching, restarted);
25560b57cec5SDimitry Andric   m_should_detach = false;
25570b57cec5SDimitry Andric 
25580b57cec5SDimitry Andric   if (m_public_run_lock.TrySetRunning()) {
25590b57cec5SDimitry Andric     // Now launch using these arguments.
25600b57cec5SDimitry Andric     error = DoLaunch(exe_module, launch_info);
25610b57cec5SDimitry Andric   } else {
25620b57cec5SDimitry Andric     // This shouldn't happen
25630b57cec5SDimitry Andric     error.SetErrorString("failed to acquire process run lock");
25640b57cec5SDimitry Andric   }
25650b57cec5SDimitry Andric 
25660b57cec5SDimitry Andric   if (error.Fail()) {
25670b57cec5SDimitry Andric     if (GetID() != LLDB_INVALID_PROCESS_ID) {
25680b57cec5SDimitry Andric       SetID(LLDB_INVALID_PROCESS_ID);
25690b57cec5SDimitry Andric       const char *error_string = error.AsCString();
25700b57cec5SDimitry Andric       if (error_string == nullptr)
25710b57cec5SDimitry Andric         error_string = "launch failed";
25720b57cec5SDimitry Andric       SetExitStatus(-1, error_string);
25730b57cec5SDimitry Andric     }
257481ad6265SDimitry Andric     return error;
257581ad6265SDimitry Andric   }
25760b57cec5SDimitry Andric 
25770b57cec5SDimitry Andric   // Now wait for the process to launch and return control to us, and then
25780b57cec5SDimitry Andric   // call DidLaunch:
257981ad6265SDimitry Andric   state = WaitForProcessStopPrivate(event_sp, seconds(10));
25800b57cec5SDimitry Andric 
25810b57cec5SDimitry Andric   if (state == eStateInvalid || !event_sp) {
25820b57cec5SDimitry Andric     // We were able to launch the process, but we failed to catch the
25830b57cec5SDimitry Andric     // initial stop.
25840b57cec5SDimitry Andric     error.SetErrorString("failed to catch stop after launch");
258581ad6265SDimitry Andric     SetExitStatus(0, error.AsCString());
25860b57cec5SDimitry Andric     Destroy(false);
258781ad6265SDimitry Andric     return error;
258881ad6265SDimitry Andric   }
258981ad6265SDimitry Andric 
259081ad6265SDimitry Andric   if (state == eStateExited) {
259181ad6265SDimitry Andric     // We exited while trying to launch somehow.  Don't call DidLaunch
259281ad6265SDimitry Andric     // as that's not likely to work, and return an invalid pid.
259381ad6265SDimitry Andric     HandlePrivateEvent(event_sp);
259481ad6265SDimitry Andric     return Status();
259581ad6265SDimitry Andric   }
259681ad6265SDimitry Andric 
259781ad6265SDimitry Andric   if (state == eStateStopped || state == eStateCrashed) {
25980b57cec5SDimitry Andric     DidLaunch();
25990b57cec5SDimitry Andric 
260081ad6265SDimitry Andric     // Now that we know the process type, update its signal responses from the
260181ad6265SDimitry Andric     // ones stored in the Target:
260281ad6265SDimitry Andric     if (m_unix_signals_sp) {
260381ad6265SDimitry Andric       StreamSP warning_strm = GetTarget().GetDebugger().GetAsyncErrorStream();
260481ad6265SDimitry Andric       GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp, warning_strm);
260581ad6265SDimitry Andric     }
260681ad6265SDimitry Andric 
26070b57cec5SDimitry Andric     DynamicLoader *dyld = GetDynamicLoader();
26080b57cec5SDimitry Andric     if (dyld)
26090b57cec5SDimitry Andric       dyld->DidLaunch();
26100b57cec5SDimitry Andric 
26110b57cec5SDimitry Andric     GetJITLoaders().DidLaunch();
26120b57cec5SDimitry Andric 
26130b57cec5SDimitry Andric     SystemRuntime *system_runtime = GetSystemRuntime();
26140b57cec5SDimitry Andric     if (system_runtime)
26150b57cec5SDimitry Andric       system_runtime->DidLaunch();
26160b57cec5SDimitry Andric 
26170b57cec5SDimitry Andric     if (!m_os_up)
26180b57cec5SDimitry Andric       LoadOperatingSystemPlugin(false);
26190b57cec5SDimitry Andric 
26200b57cec5SDimitry Andric     // We successfully launched the process and stopped, now it the
26210b57cec5SDimitry Andric     // right time to set up signal filters before resuming.
26220b57cec5SDimitry Andric     UpdateAutomaticSignalFiltering();
262381ad6265SDimitry Andric     return Status();
26240b57cec5SDimitry Andric   }
26250b57cec5SDimitry Andric 
262681ad6265SDimitry Andric   return Status("Unexpected process state after the launch: %s, expected %s, "
262781ad6265SDimitry Andric                 "%s, %s or %s",
262881ad6265SDimitry Andric                 StateAsCString(state), StateAsCString(eStateInvalid),
262981ad6265SDimitry Andric                 StateAsCString(eStateExited), StateAsCString(eStateStopped),
263081ad6265SDimitry Andric                 StateAsCString(eStateCrashed));
26310b57cec5SDimitry Andric }
26320b57cec5SDimitry Andric 
LoadCore()26330b57cec5SDimitry Andric Status Process::LoadCore() {
26340b57cec5SDimitry Andric   Status error = DoLoadCore();
26350b57cec5SDimitry Andric   if (error.Success()) {
26360b57cec5SDimitry Andric     ListenerSP listener_sp(
26370b57cec5SDimitry Andric         Listener::MakeListener("lldb.process.load_core_listener"));
26380b57cec5SDimitry Andric     HijackProcessEvents(listener_sp);
26390b57cec5SDimitry Andric 
26400b57cec5SDimitry Andric     if (PrivateStateThreadIsValid())
26410b57cec5SDimitry Andric       ResumePrivateStateThread();
26420b57cec5SDimitry Andric     else
26430b57cec5SDimitry Andric       StartPrivateStateThread();
26440b57cec5SDimitry Andric 
26450b57cec5SDimitry Andric     DynamicLoader *dyld = GetDynamicLoader();
26460b57cec5SDimitry Andric     if (dyld)
26470b57cec5SDimitry Andric       dyld->DidAttach();
26480b57cec5SDimitry Andric 
26490b57cec5SDimitry Andric     GetJITLoaders().DidAttach();
26500b57cec5SDimitry Andric 
26510b57cec5SDimitry Andric     SystemRuntime *system_runtime = GetSystemRuntime();
26520b57cec5SDimitry Andric     if (system_runtime)
26530b57cec5SDimitry Andric       system_runtime->DidAttach();
26540b57cec5SDimitry Andric 
26550b57cec5SDimitry Andric     if (!m_os_up)
26560b57cec5SDimitry Andric       LoadOperatingSystemPlugin(false);
26570b57cec5SDimitry Andric 
26580b57cec5SDimitry Andric     // We successfully loaded a core file, now pretend we stopped so we can
26590b57cec5SDimitry Andric     // show all of the threads in the core file and explore the crashed state.
26600b57cec5SDimitry Andric     SetPrivateState(eStateStopped);
26610b57cec5SDimitry Andric 
26620b57cec5SDimitry Andric     // Wait for a stopped event since we just posted one above...
26630b57cec5SDimitry Andric     lldb::EventSP event_sp;
26640b57cec5SDimitry Andric     StateType state =
2665fe013be4SDimitry Andric         WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
2666fe013be4SDimitry Andric                              nullptr, true, SelectMostRelevantFrame);
26670b57cec5SDimitry Andric 
26680b57cec5SDimitry Andric     if (!StateIsStoppedState(state, false)) {
266981ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Process);
26709dba64beSDimitry Andric       LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
26710b57cec5SDimitry Andric                 StateAsCString(state));
26720b57cec5SDimitry Andric       error.SetErrorString(
26730b57cec5SDimitry Andric           "Did not get stopped event after loading the core file.");
26740b57cec5SDimitry Andric     }
26750b57cec5SDimitry Andric     RestoreProcessEvents();
26760b57cec5SDimitry Andric   }
26770b57cec5SDimitry Andric   return error;
26780b57cec5SDimitry Andric }
26790b57cec5SDimitry Andric 
GetDynamicLoader()26800b57cec5SDimitry Andric DynamicLoader *Process::GetDynamicLoader() {
26810b57cec5SDimitry Andric   if (!m_dyld_up)
2682349cc55cSDimitry Andric     m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
26830b57cec5SDimitry Andric   return m_dyld_up.get();
26840b57cec5SDimitry Andric }
26850b57cec5SDimitry Andric 
SetDynamicLoader(DynamicLoaderUP dyld_up)2686bdd1243dSDimitry Andric void Process::SetDynamicLoader(DynamicLoaderUP dyld_up) {
2687bdd1243dSDimitry Andric   m_dyld_up = std::move(dyld_up);
2688bdd1243dSDimitry Andric }
2689bdd1243dSDimitry Andric 
GetAuxvData()26900b57cec5SDimitry Andric DataExtractor Process::GetAuxvData() { return DataExtractor(); }
26910b57cec5SDimitry Andric 
SaveCore(llvm::StringRef outfile)2692349cc55cSDimitry Andric llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
2693349cc55cSDimitry Andric   return false;
2694349cc55cSDimitry Andric }
2695349cc55cSDimitry Andric 
GetJITLoaders()26960b57cec5SDimitry Andric JITLoaderList &Process::GetJITLoaders() {
26970b57cec5SDimitry Andric   if (!m_jit_loaders_up) {
26985ffd83dbSDimitry Andric     m_jit_loaders_up = std::make_unique<JITLoaderList>();
26990b57cec5SDimitry Andric     JITLoader::LoadPlugins(this, *m_jit_loaders_up);
27000b57cec5SDimitry Andric   }
27010b57cec5SDimitry Andric   return *m_jit_loaders_up;
27020b57cec5SDimitry Andric }
27030b57cec5SDimitry Andric 
GetSystemRuntime()27040b57cec5SDimitry Andric SystemRuntime *Process::GetSystemRuntime() {
27050b57cec5SDimitry Andric   if (!m_system_runtime_up)
27060b57cec5SDimitry Andric     m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
27070b57cec5SDimitry Andric   return m_system_runtime_up.get();
27080b57cec5SDimitry Andric }
27090b57cec5SDimitry Andric 
AttachCompletionHandler(Process * process,uint32_t exec_count)27100b57cec5SDimitry Andric Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
27110b57cec5SDimitry Andric                                                           uint32_t exec_count)
27120b57cec5SDimitry Andric     : NextEventAction(process), m_exec_count(exec_count) {
271381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
27149dba64beSDimitry Andric   LLDB_LOGF(
27159dba64beSDimitry Andric       log,
27160b57cec5SDimitry Andric       "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
27170b57cec5SDimitry Andric       __FUNCTION__, static_cast<void *>(process), exec_count);
27180b57cec5SDimitry Andric }
27190b57cec5SDimitry Andric 
27200b57cec5SDimitry Andric Process::NextEventAction::EventActionResult
PerformAction(lldb::EventSP & event_sp)27210b57cec5SDimitry Andric Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
272281ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
27230b57cec5SDimitry Andric 
27240b57cec5SDimitry Andric   StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
27259dba64beSDimitry Andric   LLDB_LOGF(log,
27260b57cec5SDimitry Andric             "Process::AttachCompletionHandler::%s called with state %s (%d)",
27270b57cec5SDimitry Andric             __FUNCTION__, StateAsCString(state), static_cast<int>(state));
27280b57cec5SDimitry Andric 
27290b57cec5SDimitry Andric   switch (state) {
27300b57cec5SDimitry Andric   case eStateAttaching:
27310b57cec5SDimitry Andric     return eEventActionSuccess;
27320b57cec5SDimitry Andric 
27330b57cec5SDimitry Andric   case eStateRunning:
27340b57cec5SDimitry Andric   case eStateConnected:
27350b57cec5SDimitry Andric     return eEventActionRetry;
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric   case eStateStopped:
27380b57cec5SDimitry Andric   case eStateCrashed:
27390b57cec5SDimitry Andric     // During attach, prior to sending the eStateStopped event,
27400b57cec5SDimitry Andric     // lldb_private::Process subclasses must set the new process ID.
27410b57cec5SDimitry Andric     assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
27420b57cec5SDimitry Andric     // We don't want these events to be reported, so go set the
27430b57cec5SDimitry Andric     // ShouldReportStop here:
27440b57cec5SDimitry Andric     m_process->GetThreadList().SetShouldReportStop(eVoteNo);
27450b57cec5SDimitry Andric 
27460b57cec5SDimitry Andric     if (m_exec_count > 0) {
27470b57cec5SDimitry Andric       --m_exec_count;
27480b57cec5SDimitry Andric 
27499dba64beSDimitry Andric       LLDB_LOGF(log,
27509dba64beSDimitry Andric                 "Process::AttachCompletionHandler::%s state %s: reduced "
27510b57cec5SDimitry Andric                 "remaining exec count to %" PRIu32 ", requesting resume",
27520b57cec5SDimitry Andric                 __FUNCTION__, StateAsCString(state), m_exec_count);
27530b57cec5SDimitry Andric 
27540b57cec5SDimitry Andric       RequestResume();
27550b57cec5SDimitry Andric       return eEventActionRetry;
27560b57cec5SDimitry Andric     } else {
27579dba64beSDimitry Andric       LLDB_LOGF(log,
27589dba64beSDimitry Andric                 "Process::AttachCompletionHandler::%s state %s: no more "
27590b57cec5SDimitry Andric                 "execs expected to start, continuing with attach",
27600b57cec5SDimitry Andric                 __FUNCTION__, StateAsCString(state));
27610b57cec5SDimitry Andric 
27620b57cec5SDimitry Andric       m_process->CompleteAttach();
27630b57cec5SDimitry Andric       return eEventActionSuccess;
27640b57cec5SDimitry Andric     }
27650b57cec5SDimitry Andric     break;
27660b57cec5SDimitry Andric 
27670b57cec5SDimitry Andric   default:
27680b57cec5SDimitry Andric   case eStateExited:
27690b57cec5SDimitry Andric   case eStateInvalid:
27700b57cec5SDimitry Andric     break;
27710b57cec5SDimitry Andric   }
27720b57cec5SDimitry Andric 
27730b57cec5SDimitry Andric   m_exit_string.assign("No valid Process");
27740b57cec5SDimitry Andric   return eEventActionExit;
27750b57cec5SDimitry Andric }
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric Process::NextEventAction::EventActionResult
HandleBeingInterrupted()27780b57cec5SDimitry Andric Process::AttachCompletionHandler::HandleBeingInterrupted() {
27790b57cec5SDimitry Andric   return eEventActionSuccess;
27800b57cec5SDimitry Andric }
27810b57cec5SDimitry Andric 
GetExitString()27820b57cec5SDimitry Andric const char *Process::AttachCompletionHandler::GetExitString() {
27830b57cec5SDimitry Andric   return m_exit_string.c_str();
27840b57cec5SDimitry Andric }
27850b57cec5SDimitry Andric 
GetListenerForProcess(Debugger & debugger)27860b57cec5SDimitry Andric ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
27870b57cec5SDimitry Andric   if (m_listener_sp)
27880b57cec5SDimitry Andric     return m_listener_sp;
27890b57cec5SDimitry Andric   else
27900b57cec5SDimitry Andric     return debugger.GetListener();
27910b57cec5SDimitry Andric }
27920b57cec5SDimitry Andric 
WillLaunch(Module * module)2793bdd1243dSDimitry Andric Status Process::WillLaunch(Module *module) {
2794bdd1243dSDimitry Andric   return DoWillLaunch(module);
2795bdd1243dSDimitry Andric }
2796bdd1243dSDimitry Andric 
WillAttachToProcessWithID(lldb::pid_t pid)2797bdd1243dSDimitry Andric Status Process::WillAttachToProcessWithID(lldb::pid_t pid) {
2798bdd1243dSDimitry Andric   return DoWillAttachToProcessWithID(pid);
2799bdd1243dSDimitry Andric }
2800bdd1243dSDimitry Andric 
WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)2801bdd1243dSDimitry Andric Status Process::WillAttachToProcessWithName(const char *process_name,
2802bdd1243dSDimitry Andric                                             bool wait_for_launch) {
2803bdd1243dSDimitry Andric   return DoWillAttachToProcessWithName(process_name, wait_for_launch);
2804bdd1243dSDimitry Andric }
2805bdd1243dSDimitry Andric 
Attach(ProcessAttachInfo & attach_info)28060b57cec5SDimitry Andric Status Process::Attach(ProcessAttachInfo &attach_info) {
28070b57cec5SDimitry Andric   m_abi_sp.reset();
2808c9157d92SDimitry Andric   {
2809c9157d92SDimitry Andric     std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
28100b57cec5SDimitry Andric     m_process_input_reader.reset();
2811c9157d92SDimitry Andric   }
28120b57cec5SDimitry Andric   m_dyld_up.reset();
28130b57cec5SDimitry Andric   m_jit_loaders_up.reset();
28140b57cec5SDimitry Andric   m_system_runtime_up.reset();
28150b57cec5SDimitry Andric   m_os_up.reset();
28160b57cec5SDimitry Andric 
28170b57cec5SDimitry Andric   lldb::pid_t attach_pid = attach_info.GetProcessID();
28180b57cec5SDimitry Andric   Status error;
28190b57cec5SDimitry Andric   if (attach_pid == LLDB_INVALID_PROCESS_ID) {
28200b57cec5SDimitry Andric     char process_name[PATH_MAX];
28210b57cec5SDimitry Andric 
28220b57cec5SDimitry Andric     if (attach_info.GetExecutableFile().GetPath(process_name,
28230b57cec5SDimitry Andric                                                 sizeof(process_name))) {
28240b57cec5SDimitry Andric       const bool wait_for_launch = attach_info.GetWaitForLaunch();
28250b57cec5SDimitry Andric 
28260b57cec5SDimitry Andric       if (wait_for_launch) {
28270b57cec5SDimitry Andric         error = WillAttachToProcessWithName(process_name, wait_for_launch);
28280b57cec5SDimitry Andric         if (error.Success()) {
28290b57cec5SDimitry Andric           if (m_public_run_lock.TrySetRunning()) {
28300b57cec5SDimitry Andric             m_should_detach = true;
28310b57cec5SDimitry Andric             const bool restarted = false;
28320b57cec5SDimitry Andric             SetPublicState(eStateAttaching, restarted);
28330b57cec5SDimitry Andric             // Now attach using these arguments.
28340b57cec5SDimitry Andric             error = DoAttachToProcessWithName(process_name, attach_info);
28350b57cec5SDimitry Andric           } else {
28360b57cec5SDimitry Andric             // This shouldn't happen
28370b57cec5SDimitry Andric             error.SetErrorString("failed to acquire process run lock");
28380b57cec5SDimitry Andric           }
28390b57cec5SDimitry Andric 
28400b57cec5SDimitry Andric           if (error.Fail()) {
28410b57cec5SDimitry Andric             if (GetID() != LLDB_INVALID_PROCESS_ID) {
28420b57cec5SDimitry Andric               SetID(LLDB_INVALID_PROCESS_ID);
28430b57cec5SDimitry Andric               if (error.AsCString() == nullptr)
28440b57cec5SDimitry Andric                 error.SetErrorString("attach failed");
28450b57cec5SDimitry Andric 
28460b57cec5SDimitry Andric               SetExitStatus(-1, error.AsCString());
28470b57cec5SDimitry Andric             }
28480b57cec5SDimitry Andric           } else {
28490b57cec5SDimitry Andric             SetNextEventAction(new Process::AttachCompletionHandler(
28500b57cec5SDimitry Andric                 this, attach_info.GetResumeCount()));
28510b57cec5SDimitry Andric             StartPrivateStateThread();
28520b57cec5SDimitry Andric           }
28530b57cec5SDimitry Andric           return error;
28540b57cec5SDimitry Andric         }
28550b57cec5SDimitry Andric       } else {
28560b57cec5SDimitry Andric         ProcessInstanceInfoList process_infos;
28570b57cec5SDimitry Andric         PlatformSP platform_sp(GetTarget().GetPlatform());
28580b57cec5SDimitry Andric 
28590b57cec5SDimitry Andric         if (platform_sp) {
28600b57cec5SDimitry Andric           ProcessInstanceInfoMatch match_info;
28610b57cec5SDimitry Andric           match_info.GetProcessInfo() = attach_info;
28620b57cec5SDimitry Andric           match_info.SetNameMatchType(NameMatch::Equals);
28630b57cec5SDimitry Andric           platform_sp->FindProcesses(match_info, process_infos);
28645ffd83dbSDimitry Andric           const uint32_t num_matches = process_infos.size();
28650b57cec5SDimitry Andric           if (num_matches == 1) {
28665ffd83dbSDimitry Andric             attach_pid = process_infos[0].GetProcessID();
28670b57cec5SDimitry Andric             // Fall through and attach using the above process ID
28680b57cec5SDimitry Andric           } else {
28690b57cec5SDimitry Andric             match_info.GetProcessInfo().GetExecutableFile().GetPath(
28700b57cec5SDimitry Andric                 process_name, sizeof(process_name));
28710b57cec5SDimitry Andric             if (num_matches > 1) {
28720b57cec5SDimitry Andric               StreamString s;
28730b57cec5SDimitry Andric               ProcessInstanceInfo::DumpTableHeader(s, true, false);
28740b57cec5SDimitry Andric               for (size_t i = 0; i < num_matches; i++) {
28755ffd83dbSDimitry Andric                 process_infos[i].DumpAsTableRow(
28760b57cec5SDimitry Andric                     s, platform_sp->GetUserIDResolver(), true, false);
28770b57cec5SDimitry Andric               }
28780b57cec5SDimitry Andric               error.SetErrorStringWithFormat(
28790b57cec5SDimitry Andric                   "more than one process named %s:\n%s", process_name,
28800b57cec5SDimitry Andric                   s.GetData());
28810b57cec5SDimitry Andric             } else
28820b57cec5SDimitry Andric               error.SetErrorStringWithFormat(
28830b57cec5SDimitry Andric                   "could not find a process named %s", process_name);
28840b57cec5SDimitry Andric           }
28850b57cec5SDimitry Andric         } else {
28860b57cec5SDimitry Andric           error.SetErrorString(
28870b57cec5SDimitry Andric               "invalid platform, can't find processes by name");
28880b57cec5SDimitry Andric           return error;
28890b57cec5SDimitry Andric         }
28900b57cec5SDimitry Andric       }
28910b57cec5SDimitry Andric     } else {
28920b57cec5SDimitry Andric       error.SetErrorString("invalid process name");
28930b57cec5SDimitry Andric     }
28940b57cec5SDimitry Andric   }
28950b57cec5SDimitry Andric 
28960b57cec5SDimitry Andric   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
28970b57cec5SDimitry Andric     error = WillAttachToProcessWithID(attach_pid);
28980b57cec5SDimitry Andric     if (error.Success()) {
28990b57cec5SDimitry Andric 
29000b57cec5SDimitry Andric       if (m_public_run_lock.TrySetRunning()) {
29010b57cec5SDimitry Andric         // Now attach using these arguments.
29020b57cec5SDimitry Andric         m_should_detach = true;
29030b57cec5SDimitry Andric         const bool restarted = false;
29040b57cec5SDimitry Andric         SetPublicState(eStateAttaching, restarted);
29050b57cec5SDimitry Andric         error = DoAttachToProcessWithID(attach_pid, attach_info);
29060b57cec5SDimitry Andric       } else {
29070b57cec5SDimitry Andric         // This shouldn't happen
29080b57cec5SDimitry Andric         error.SetErrorString("failed to acquire process run lock");
29090b57cec5SDimitry Andric       }
29100b57cec5SDimitry Andric 
29110b57cec5SDimitry Andric       if (error.Success()) {
29120b57cec5SDimitry Andric         SetNextEventAction(new Process::AttachCompletionHandler(
29130b57cec5SDimitry Andric             this, attach_info.GetResumeCount()));
29140b57cec5SDimitry Andric         StartPrivateStateThread();
29150b57cec5SDimitry Andric       } else {
29160b57cec5SDimitry Andric         if (GetID() != LLDB_INVALID_PROCESS_ID)
29170b57cec5SDimitry Andric           SetID(LLDB_INVALID_PROCESS_ID);
29180b57cec5SDimitry Andric 
29190b57cec5SDimitry Andric         const char *error_string = error.AsCString();
29200b57cec5SDimitry Andric         if (error_string == nullptr)
29210b57cec5SDimitry Andric           error_string = "attach failed";
29220b57cec5SDimitry Andric 
29230b57cec5SDimitry Andric         SetExitStatus(-1, error_string);
29240b57cec5SDimitry Andric       }
29250b57cec5SDimitry Andric     }
29260b57cec5SDimitry Andric   }
29270b57cec5SDimitry Andric   return error;
29280b57cec5SDimitry Andric }
29290b57cec5SDimitry Andric 
CompleteAttach()29300b57cec5SDimitry Andric void Process::CompleteAttach() {
293181ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::Process | LLDBLog::Target));
29329dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric   // Let the process subclass figure out at much as it can about the process
29350b57cec5SDimitry Andric   // before we go looking for a dynamic loader plug-in.
29360b57cec5SDimitry Andric   ArchSpec process_arch;
29370b57cec5SDimitry Andric   DidAttach(process_arch);
29380b57cec5SDimitry Andric 
29390b57cec5SDimitry Andric   if (process_arch.IsValid()) {
29400b57cec5SDimitry Andric     GetTarget().SetArchitecture(process_arch);
29410b57cec5SDimitry Andric     if (log) {
29420b57cec5SDimitry Andric       const char *triple_str = process_arch.GetTriple().getTriple().c_str();
29439dba64beSDimitry Andric       LLDB_LOGF(log,
29449dba64beSDimitry Andric                 "Process::%s replacing process architecture with DidAttach() "
29450b57cec5SDimitry Andric                 "architecture: %s",
29460b57cec5SDimitry Andric                 __FUNCTION__, triple_str ? triple_str : "<null>");
29470b57cec5SDimitry Andric     }
29480b57cec5SDimitry Andric   }
29490b57cec5SDimitry Andric 
29500b57cec5SDimitry Andric   // We just attached.  If we have a platform, ask it for the process
29510b57cec5SDimitry Andric   // architecture, and if it isn't the same as the one we've already set,
29520b57cec5SDimitry Andric   // switch architectures.
29530b57cec5SDimitry Andric   PlatformSP platform_sp(GetTarget().GetPlatform());
29540b57cec5SDimitry Andric   assert(platform_sp);
295581ad6265SDimitry Andric   ArchSpec process_host_arch = GetSystemArchitecture();
29560b57cec5SDimitry Andric   if (platform_sp) {
29570b57cec5SDimitry Andric     const ArchSpec &target_arch = GetTarget().GetArchitecture();
2958bdd1243dSDimitry Andric     if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
2959bdd1243dSDimitry Andric                                      target_arch, process_host_arch,
2960bdd1243dSDimitry Andric                                      ArchSpec::CompatibleMatch, nullptr)) {
29610b57cec5SDimitry Andric       ArchSpec platform_arch;
296281ad6265SDimitry Andric       platform_sp = GetTarget().GetDebugger().GetPlatformList().GetOrCreate(
296381ad6265SDimitry Andric           target_arch, process_host_arch, &platform_arch);
29640b57cec5SDimitry Andric       if (platform_sp) {
29650b57cec5SDimitry Andric         GetTarget().SetPlatform(platform_sp);
29660b57cec5SDimitry Andric         GetTarget().SetArchitecture(platform_arch);
296781ad6265SDimitry Andric         LLDB_LOG(log,
296881ad6265SDimitry Andric                  "switching platform to {0} and architecture to {1} based on "
296981ad6265SDimitry Andric                  "info from attach",
297081ad6265SDimitry Andric                  platform_sp->GetName(), platform_arch.GetTriple().getTriple());
29710b57cec5SDimitry Andric       }
29720b57cec5SDimitry Andric     } else if (!process_arch.IsValid()) {
29730b57cec5SDimitry Andric       ProcessInstanceInfo process_info;
29740b57cec5SDimitry Andric       GetProcessInfo(process_info);
29750b57cec5SDimitry Andric       const ArchSpec &process_arch = process_info.GetArchitecture();
2976fe6060f1SDimitry Andric       const ArchSpec &target_arch = GetTarget().GetArchitecture();
29770b57cec5SDimitry Andric       if (process_arch.IsValid() &&
2978fe6060f1SDimitry Andric           target_arch.IsCompatibleMatch(process_arch) &&
2979fe6060f1SDimitry Andric           !target_arch.IsExactMatch(process_arch)) {
29800b57cec5SDimitry Andric         GetTarget().SetArchitecture(process_arch);
29819dba64beSDimitry Andric         LLDB_LOGF(log,
29829dba64beSDimitry Andric                   "Process::%s switching architecture to %s based on info "
29830b57cec5SDimitry Andric                   "the platform retrieved for pid %" PRIu64,
29849dba64beSDimitry Andric                   __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
29859dba64beSDimitry Andric                   GetID());
29860b57cec5SDimitry Andric       }
29870b57cec5SDimitry Andric     }
29880b57cec5SDimitry Andric   }
298981ad6265SDimitry Andric   // Now that we know the process type, update its signal responses from the
299081ad6265SDimitry Andric   // ones stored in the Target:
299181ad6265SDimitry Andric   if (m_unix_signals_sp) {
299281ad6265SDimitry Andric     StreamSP warning_strm = GetTarget().GetDebugger().GetAsyncErrorStream();
299381ad6265SDimitry Andric     GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp, warning_strm);
299481ad6265SDimitry Andric   }
29950b57cec5SDimitry Andric 
29960b57cec5SDimitry Andric   // We have completed the attach, now it is time to find the dynamic loader
29970b57cec5SDimitry Andric   // plug-in
29980b57cec5SDimitry Andric   DynamicLoader *dyld = GetDynamicLoader();
29990b57cec5SDimitry Andric   if (dyld) {
30000b57cec5SDimitry Andric     dyld->DidAttach();
30010b57cec5SDimitry Andric     if (log) {
30020b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3003349cc55cSDimitry Andric       LLDB_LOG(log,
3004349cc55cSDimitry Andric                "after DynamicLoader::DidAttach(), target "
3005349cc55cSDimitry Andric                "executable is {0} (using {1} plugin)",
3006349cc55cSDimitry Andric                exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3007349cc55cSDimitry Andric                dyld->GetPluginName());
30080b57cec5SDimitry Andric     }
30090b57cec5SDimitry Andric   }
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric   GetJITLoaders().DidAttach();
30120b57cec5SDimitry Andric 
30130b57cec5SDimitry Andric   SystemRuntime *system_runtime = GetSystemRuntime();
30140b57cec5SDimitry Andric   if (system_runtime) {
30150b57cec5SDimitry Andric     system_runtime->DidAttach();
30160b57cec5SDimitry Andric     if (log) {
30170b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3018349cc55cSDimitry Andric       LLDB_LOG(log,
3019349cc55cSDimitry Andric                "after SystemRuntime::DidAttach(), target "
3020349cc55cSDimitry Andric                "executable is {0} (using {1} plugin)",
3021349cc55cSDimitry Andric                exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3022349cc55cSDimitry Andric                system_runtime->GetPluginName());
30230b57cec5SDimitry Andric     }
30240b57cec5SDimitry Andric   }
30250b57cec5SDimitry Andric 
30260b57cec5SDimitry Andric   if (!m_os_up) {
30270b57cec5SDimitry Andric     LoadOperatingSystemPlugin(false);
30280b57cec5SDimitry Andric     if (m_os_up) {
30290b57cec5SDimitry Andric       // Somebody might have gotten threads before now, but we need to force the
30300b57cec5SDimitry Andric       // update after we've loaded the OperatingSystem plugin or it won't get a
30310b57cec5SDimitry Andric       // chance to process the threads.
30320b57cec5SDimitry Andric       m_thread_list.Clear();
30330b57cec5SDimitry Andric       UpdateThreadListIfNeeded();
30340b57cec5SDimitry Andric     }
30350b57cec5SDimitry Andric   }
30360b57cec5SDimitry Andric   // Figure out which one is the executable, and set that in our target:
30370b57cec5SDimitry Andric   ModuleSP new_executable_module_sp;
3038e8d8bef9SDimitry Andric   for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
30390b57cec5SDimitry Andric     if (module_sp && module_sp->IsExecutable()) {
30400b57cec5SDimitry Andric       if (GetTarget().GetExecutableModulePointer() != module_sp.get())
30410b57cec5SDimitry Andric         new_executable_module_sp = module_sp;
30420b57cec5SDimitry Andric       break;
30430b57cec5SDimitry Andric     }
30440b57cec5SDimitry Andric   }
30450b57cec5SDimitry Andric   if (new_executable_module_sp) {
30460b57cec5SDimitry Andric     GetTarget().SetExecutableModule(new_executable_module_sp,
30470b57cec5SDimitry Andric                                     eLoadDependentsNo);
30480b57cec5SDimitry Andric     if (log) {
30490b57cec5SDimitry Andric       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
30509dba64beSDimitry Andric       LLDB_LOGF(
30519dba64beSDimitry Andric           log,
30520b57cec5SDimitry Andric           "Process::%s after looping through modules, target executable is %s",
30530b57cec5SDimitry Andric           __FUNCTION__,
30540b57cec5SDimitry Andric           exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
30550b57cec5SDimitry Andric                         : "<none>");
30560b57cec5SDimitry Andric     }
30570b57cec5SDimitry Andric   }
30580b57cec5SDimitry Andric }
30590b57cec5SDimitry Andric 
ConnectRemote(llvm::StringRef remote_url)30605ffd83dbSDimitry Andric Status Process::ConnectRemote(llvm::StringRef remote_url) {
30610b57cec5SDimitry Andric   m_abi_sp.reset();
3062c9157d92SDimitry Andric   {
3063c9157d92SDimitry Andric     std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
30640b57cec5SDimitry Andric     m_process_input_reader.reset();
3065c9157d92SDimitry Andric   }
30660b57cec5SDimitry Andric 
30670b57cec5SDimitry Andric   // Find the process and its architecture.  Make sure it matches the
30680b57cec5SDimitry Andric   // architecture of the current Target, and if not adjust it.
30690b57cec5SDimitry Andric 
30705ffd83dbSDimitry Andric   Status error(DoConnectRemote(remote_url));
30710b57cec5SDimitry Andric   if (error.Success()) {
30720b57cec5SDimitry Andric     if (GetID() != LLDB_INVALID_PROCESS_ID) {
30730b57cec5SDimitry Andric       EventSP event_sp;
3074bdd1243dSDimitry Andric       StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
30750b57cec5SDimitry Andric 
30760b57cec5SDimitry Andric       if (state == eStateStopped || state == eStateCrashed) {
30770b57cec5SDimitry Andric         // If we attached and actually have a process on the other end, then
30780b57cec5SDimitry Andric         // this ended up being the equivalent of an attach.
30790b57cec5SDimitry Andric         CompleteAttach();
30800b57cec5SDimitry Andric 
30810b57cec5SDimitry Andric         // This delays passing the stopped event to listeners till
30820b57cec5SDimitry Andric         // CompleteAttach gets a chance to complete...
30830b57cec5SDimitry Andric         HandlePrivateEvent(event_sp);
30840b57cec5SDimitry Andric       }
30850b57cec5SDimitry Andric     }
30860b57cec5SDimitry Andric 
30870b57cec5SDimitry Andric     if (PrivateStateThreadIsValid())
30880b57cec5SDimitry Andric       ResumePrivateStateThread();
30890b57cec5SDimitry Andric     else
30900b57cec5SDimitry Andric       StartPrivateStateThread();
30910b57cec5SDimitry Andric   }
30920b57cec5SDimitry Andric   return error;
30930b57cec5SDimitry Andric }
30940b57cec5SDimitry Andric 
PrivateResume()30950b57cec5SDimitry Andric Status Process::PrivateResume() {
309681ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::Process | LLDBLog::Step));
30979dba64beSDimitry Andric   LLDB_LOGF(log,
30989dba64beSDimitry Andric             "Process::PrivateResume() m_stop_id = %u, public state: %s "
30990b57cec5SDimitry Andric             "private state: %s",
31000b57cec5SDimitry Andric             m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
31010b57cec5SDimitry Andric             StateAsCString(m_private_state.GetValue()));
31020b57cec5SDimitry Andric 
31030b57cec5SDimitry Andric   // If signals handing status changed we might want to update our signal
31040b57cec5SDimitry Andric   // filters before resuming.
31050b57cec5SDimitry Andric   UpdateAutomaticSignalFiltering();
31060b57cec5SDimitry Andric 
31070b57cec5SDimitry Andric   Status error(WillResume());
31080b57cec5SDimitry Andric   // Tell the process it is about to resume before the thread list
31090b57cec5SDimitry Andric   if (error.Success()) {
31100b57cec5SDimitry Andric     // Now let the thread list know we are about to resume so it can let all of
31110b57cec5SDimitry Andric     // our threads know that they are about to be resumed. Threads will each be
31120b57cec5SDimitry Andric     // called with Thread::WillResume(StateType) where StateType contains the
31130b57cec5SDimitry Andric     // state that they are supposed to have when the process is resumed
31140b57cec5SDimitry Andric     // (suspended/running/stepping). Threads should also check their resume
31150b57cec5SDimitry Andric     // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
31160b57cec5SDimitry Andric     // start back up with a signal.
31170b57cec5SDimitry Andric     if (m_thread_list.WillResume()) {
31180b57cec5SDimitry Andric       // Last thing, do the PreResumeActions.
31190b57cec5SDimitry Andric       if (!RunPreResumeActions()) {
3120e8d8bef9SDimitry Andric         error.SetErrorString(
31210b57cec5SDimitry Andric             "Process::PrivateResume PreResumeActions failed, not resuming.");
31220b57cec5SDimitry Andric       } else {
31230b57cec5SDimitry Andric         m_mod_id.BumpResumeID();
31240b57cec5SDimitry Andric         error = DoResume();
31250b57cec5SDimitry Andric         if (error.Success()) {
31260b57cec5SDimitry Andric           DidResume();
31270b57cec5SDimitry Andric           m_thread_list.DidResume();
31289dba64beSDimitry Andric           LLDB_LOGF(log, "Process thinks the process has resumed.");
31290b57cec5SDimitry Andric         } else {
31309dba64beSDimitry Andric           LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
31310b57cec5SDimitry Andric           return error;
31320b57cec5SDimitry Andric         }
31330b57cec5SDimitry Andric       }
31340b57cec5SDimitry Andric     } else {
31350b57cec5SDimitry Andric       // Somebody wanted to run without running (e.g. we were faking a step
31360b57cec5SDimitry Andric       // from one frame of a set of inlined frames that share the same PC to
31370b57cec5SDimitry Andric       // another.)  So generate a continue & a stopped event, and let the world
31380b57cec5SDimitry Andric       // handle them.
31399dba64beSDimitry Andric       LLDB_LOGF(log,
31400b57cec5SDimitry Andric                 "Process::PrivateResume() asked to simulate a start & stop.");
31410b57cec5SDimitry Andric 
31420b57cec5SDimitry Andric       SetPrivateState(eStateRunning);
31430b57cec5SDimitry Andric       SetPrivateState(eStateStopped);
31440b57cec5SDimitry Andric     }
31459dba64beSDimitry Andric   } else
31469dba64beSDimitry Andric     LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
31470b57cec5SDimitry Andric               error.AsCString("<unknown error>"));
31480b57cec5SDimitry Andric   return error;
31490b57cec5SDimitry Andric }
31500b57cec5SDimitry Andric 
Halt(bool clear_thread_plans,bool use_run_lock)31510b57cec5SDimitry Andric Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
31520b57cec5SDimitry Andric   if (!StateIsRunningState(m_public_state.GetValue()))
31530b57cec5SDimitry Andric     return Status("Process is not running.");
31540b57cec5SDimitry Andric 
31550b57cec5SDimitry Andric   // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
31560b57cec5SDimitry Andric   // case it was already set and some thread plan logic calls halt on its own.
31570b57cec5SDimitry Andric   m_clear_thread_plans_on_stop |= clear_thread_plans;
31580b57cec5SDimitry Andric 
31590b57cec5SDimitry Andric   ListenerSP halt_listener_sp(
31600b57cec5SDimitry Andric       Listener::MakeListener("lldb.process.halt_listener"));
31610b57cec5SDimitry Andric   HijackProcessEvents(halt_listener_sp);
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric   EventSP event_sp;
31640b57cec5SDimitry Andric 
31650b57cec5SDimitry Andric   SendAsyncInterrupt();
31660b57cec5SDimitry Andric 
31670b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateAttaching) {
31680b57cec5SDimitry Andric     // Don't hijack and eat the eStateExited as the code that was doing the
31690b57cec5SDimitry Andric     // attach will be waiting for this event...
31700b57cec5SDimitry Andric     RestoreProcessEvents();
31710b57cec5SDimitry Andric     Destroy(false);
3172c9157d92SDimitry Andric     SetExitStatus(SIGKILL, "Cancelled async attach.");
31730b57cec5SDimitry Andric     return Status();
31740b57cec5SDimitry Andric   }
31750b57cec5SDimitry Andric 
3176fe6060f1SDimitry Andric   // Wait for the process halt timeout seconds for the process to stop.
3177fe013be4SDimitry Andric   // If we are going to use the run lock, that means we're stopping out to the
3178fe013be4SDimitry Andric   // user, so we should also select the most relevant frame.
3179fe013be4SDimitry Andric   SelectMostRelevant select_most_relevant =
3180fe013be4SDimitry Andric       use_run_lock ? SelectMostRelevantFrame : DoNoSelectMostRelevantFrame;
3181fe013be4SDimitry Andric   StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3182fe013be4SDimitry Andric                                          halt_listener_sp, nullptr,
3183fe013be4SDimitry Andric                                          use_run_lock, select_most_relevant);
31840b57cec5SDimitry Andric   RestoreProcessEvents();
31850b57cec5SDimitry Andric 
31860b57cec5SDimitry Andric   if (state == eStateInvalid || !event_sp) {
31870b57cec5SDimitry Andric     // We timed out and didn't get a stop event...
31880b57cec5SDimitry Andric     return Status("Halt timed out. State = %s", StateAsCString(GetState()));
31890b57cec5SDimitry Andric   }
31900b57cec5SDimitry Andric 
31910b57cec5SDimitry Andric   BroadcastEvent(event_sp);
31920b57cec5SDimitry Andric 
31930b57cec5SDimitry Andric   return Status();
31940b57cec5SDimitry Andric }
31950b57cec5SDimitry Andric 
StopForDestroyOrDetach(lldb::EventSP & exit_event_sp)31960b57cec5SDimitry Andric Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
31970b57cec5SDimitry Andric   Status error;
31980b57cec5SDimitry Andric 
31990b57cec5SDimitry Andric   // Check both the public & private states here.  If we're hung evaluating an
32000b57cec5SDimitry Andric   // expression, for instance, then the public state will be stopped, but we
32010b57cec5SDimitry Andric   // still need to interrupt.
32020b57cec5SDimitry Andric   if (m_public_state.GetValue() == eStateRunning ||
32030b57cec5SDimitry Andric       m_private_state.GetValue() == eStateRunning) {
320481ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
32059dba64beSDimitry Andric     LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
32060b57cec5SDimitry Andric 
32070b57cec5SDimitry Andric     ListenerSP listener_sp(
32080b57cec5SDimitry Andric         Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
32090b57cec5SDimitry Andric     HijackProcessEvents(listener_sp);
32100b57cec5SDimitry Andric 
32110b57cec5SDimitry Andric     SendAsyncInterrupt();
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric     // Consume the interrupt event.
3214fe6060f1SDimitry Andric     StateType state = WaitForProcessToStop(GetInterruptTimeout(),
3215fe6060f1SDimitry Andric                                            &exit_event_sp, true, listener_sp);
32160b57cec5SDimitry Andric 
32170b57cec5SDimitry Andric     RestoreProcessEvents();
32180b57cec5SDimitry Andric 
32190b57cec5SDimitry Andric     // If the process exited while we were waiting for it to stop, put the
32200b57cec5SDimitry Andric     // exited event into the shared pointer passed in and return.  Our caller
32210b57cec5SDimitry Andric     // doesn't need to do anything else, since they don't have a process
32220b57cec5SDimitry Andric     // anymore...
32230b57cec5SDimitry Andric 
32240b57cec5SDimitry Andric     if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
32259dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
32260b57cec5SDimitry Andric                 __FUNCTION__);
32270b57cec5SDimitry Andric       return error;
32280b57cec5SDimitry Andric     } else
32290b57cec5SDimitry Andric       exit_event_sp.reset(); // It is ok to consume any non-exit stop events
32300b57cec5SDimitry Andric 
32310b57cec5SDimitry Andric     if (state != eStateStopped) {
32329dba64beSDimitry Andric       LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
32330b57cec5SDimitry Andric                 StateAsCString(state));
32340b57cec5SDimitry Andric       // If we really couldn't stop the process then we should just error out
32350b57cec5SDimitry Andric       // here, but if the lower levels just bobbled sending the event and we
32360b57cec5SDimitry Andric       // really are stopped, then continue on.
32370b57cec5SDimitry Andric       StateType private_state = m_private_state.GetValue();
32380b57cec5SDimitry Andric       if (private_state != eStateStopped) {
32390b57cec5SDimitry Andric         return Status(
32400b57cec5SDimitry Andric             "Attempt to stop the target in order to detach timed out. "
32410b57cec5SDimitry Andric             "State = %s",
32420b57cec5SDimitry Andric             StateAsCString(GetState()));
32430b57cec5SDimitry Andric       }
32440b57cec5SDimitry Andric     }
32450b57cec5SDimitry Andric   }
32460b57cec5SDimitry Andric   return error;
32470b57cec5SDimitry Andric }
32480b57cec5SDimitry Andric 
Detach(bool keep_stopped)32490b57cec5SDimitry Andric Status Process::Detach(bool keep_stopped) {
32500b57cec5SDimitry Andric   EventSP exit_event_sp;
32510b57cec5SDimitry Andric   Status error;
32520b57cec5SDimitry Andric   m_destroy_in_process = true;
32530b57cec5SDimitry Andric 
32540b57cec5SDimitry Andric   error = WillDetach();
32550b57cec5SDimitry Andric 
32560b57cec5SDimitry Andric   if (error.Success()) {
32570b57cec5SDimitry Andric     if (DetachRequiresHalt()) {
32580b57cec5SDimitry Andric       error = StopForDestroyOrDetach(exit_event_sp);
32590b57cec5SDimitry Andric       if (!error.Success()) {
32600b57cec5SDimitry Andric         m_destroy_in_process = false;
32610b57cec5SDimitry Andric         return error;
32620b57cec5SDimitry Andric       } else if (exit_event_sp) {
32630b57cec5SDimitry Andric         // We shouldn't need to do anything else here.  There's no process left
32640b57cec5SDimitry Andric         // to detach from...
32650b57cec5SDimitry Andric         StopPrivateStateThread();
32660b57cec5SDimitry Andric         m_destroy_in_process = false;
32670b57cec5SDimitry Andric         return error;
32680b57cec5SDimitry Andric       }
32690b57cec5SDimitry Andric     }
32700b57cec5SDimitry Andric 
32710b57cec5SDimitry Andric     m_thread_list.DiscardThreadPlans();
32720b57cec5SDimitry Andric     DisableAllBreakpointSites();
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric     error = DoDetach(keep_stopped);
32750b57cec5SDimitry Andric     if (error.Success()) {
32760b57cec5SDimitry Andric       DidDetach();
32770b57cec5SDimitry Andric       StopPrivateStateThread();
32780b57cec5SDimitry Andric     } else {
32790b57cec5SDimitry Andric       return error;
32800b57cec5SDimitry Andric     }
32810b57cec5SDimitry Andric   }
32820b57cec5SDimitry Andric   m_destroy_in_process = false;
32830b57cec5SDimitry Andric 
32840b57cec5SDimitry Andric   // If we exited when we were waiting for a process to stop, then forward the
32850b57cec5SDimitry Andric   // event here so we don't lose the event
32860b57cec5SDimitry Andric   if (exit_event_sp) {
32870b57cec5SDimitry Andric     // Directly broadcast our exited event because we shut down our private
32880b57cec5SDimitry Andric     // state thread above
32890b57cec5SDimitry Andric     BroadcastEvent(exit_event_sp);
32900b57cec5SDimitry Andric   }
32910b57cec5SDimitry Andric 
32920b57cec5SDimitry Andric   // If we have been interrupted (to kill us) in the middle of running, we may
32930b57cec5SDimitry Andric   // not end up propagating the last events through the event system, in which
32940b57cec5SDimitry Andric   // case we might strand the write lock.  Unlock it here so when we do to tear
32950b57cec5SDimitry Andric   // down the process we don't get an error destroying the lock.
32960b57cec5SDimitry Andric 
32970b57cec5SDimitry Andric   m_public_run_lock.SetStopped();
32980b57cec5SDimitry Andric   return error;
32990b57cec5SDimitry Andric }
33000b57cec5SDimitry Andric 
Destroy(bool force_kill)33010b57cec5SDimitry Andric Status Process::Destroy(bool force_kill) {
33025ffd83dbSDimitry Andric   // If we've already called Process::Finalize then there's nothing useful to
33035ffd83dbSDimitry Andric   // be done here.  Finalize has actually called Destroy already.
3304e8d8bef9SDimitry Andric   if (m_finalizing)
33055ffd83dbSDimitry Andric     return {};
3306e8d8bef9SDimitry Andric   return DestroyImpl(force_kill);
3307e8d8bef9SDimitry Andric }
33080b57cec5SDimitry Andric 
DestroyImpl(bool force_kill)3309e8d8bef9SDimitry Andric Status Process::DestroyImpl(bool force_kill) {
33100b57cec5SDimitry Andric   // Tell ourselves we are in the process of destroying the process, so that we
33110b57cec5SDimitry Andric   // don't do any unnecessary work that might hinder the destruction.  Remember
33120b57cec5SDimitry Andric   // to set this back to false when we are done.  That way if the attempt
33130b57cec5SDimitry Andric   // failed and the process stays around for some reason it won't be in a
33140b57cec5SDimitry Andric   // confused state.
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric   if (force_kill)
33170b57cec5SDimitry Andric     m_should_detach = false;
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric   if (GetShouldDetach()) {
33200b57cec5SDimitry Andric     // FIXME: This will have to be a process setting:
33210b57cec5SDimitry Andric     bool keep_stopped = false;
33220b57cec5SDimitry Andric     Detach(keep_stopped);
33230b57cec5SDimitry Andric   }
33240b57cec5SDimitry Andric 
33250b57cec5SDimitry Andric   m_destroy_in_process = true;
33260b57cec5SDimitry Andric 
33270b57cec5SDimitry Andric   Status error(WillDestroy());
33280b57cec5SDimitry Andric   if (error.Success()) {
33290b57cec5SDimitry Andric     EventSP exit_event_sp;
33300b57cec5SDimitry Andric     if (DestroyRequiresHalt()) {
33310b57cec5SDimitry Andric       error = StopForDestroyOrDetach(exit_event_sp);
33320b57cec5SDimitry Andric     }
33330b57cec5SDimitry Andric 
3334fe6060f1SDimitry Andric     if (m_public_state.GetValue() == eStateStopped) {
33350b57cec5SDimitry Andric       // Ditch all thread plans, and remove all our breakpoints: in case we
33360b57cec5SDimitry Andric       // have to restart the target to kill it, we don't want it hitting a
33370b57cec5SDimitry Andric       // breakpoint... Only do this if we've stopped, however, since if we
33380b57cec5SDimitry Andric       // didn't manage to halt it above, then we're not going to have much luck
33390b57cec5SDimitry Andric       // doing this now.
33400b57cec5SDimitry Andric       m_thread_list.DiscardThreadPlans();
33410b57cec5SDimitry Andric       DisableAllBreakpointSites();
33420b57cec5SDimitry Andric     }
33430b57cec5SDimitry Andric 
33440b57cec5SDimitry Andric     error = DoDestroy();
33450b57cec5SDimitry Andric     if (error.Success()) {
33460b57cec5SDimitry Andric       DidDestroy();
33470b57cec5SDimitry Andric       StopPrivateStateThread();
33480b57cec5SDimitry Andric     }
33490b57cec5SDimitry Andric     m_stdio_communication.StopReadThread();
33505ffd83dbSDimitry Andric     m_stdio_communication.Disconnect();
33510b57cec5SDimitry Andric     m_stdin_forward = false;
33520b57cec5SDimitry Andric 
3353c9157d92SDimitry Andric     {
3354c9157d92SDimitry Andric       std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
33550b57cec5SDimitry Andric       if (m_process_input_reader) {
33560b57cec5SDimitry Andric         m_process_input_reader->SetIsDone(true);
33570b57cec5SDimitry Andric         m_process_input_reader->Cancel();
33580b57cec5SDimitry Andric         m_process_input_reader.reset();
33590b57cec5SDimitry Andric       }
3360c9157d92SDimitry Andric     }
33610b57cec5SDimitry Andric 
33620b57cec5SDimitry Andric     // If we exited when we were waiting for a process to stop, then forward
33630b57cec5SDimitry Andric     // the event here so we don't lose the event
33640b57cec5SDimitry Andric     if (exit_event_sp) {
33650b57cec5SDimitry Andric       // Directly broadcast our exited event because we shut down our private
33660b57cec5SDimitry Andric       // state thread above
33670b57cec5SDimitry Andric       BroadcastEvent(exit_event_sp);
33680b57cec5SDimitry Andric     }
33690b57cec5SDimitry Andric 
33700b57cec5SDimitry Andric     // If we have been interrupted (to kill us) in the middle of running, we
33710b57cec5SDimitry Andric     // may not end up propagating the last events through the event system, in
33720b57cec5SDimitry Andric     // which case we might strand the write lock.  Unlock it here so when we do
33730b57cec5SDimitry Andric     // to tear down the process we don't get an error destroying the lock.
33740b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
33750b57cec5SDimitry Andric   }
33760b57cec5SDimitry Andric 
33770b57cec5SDimitry Andric   m_destroy_in_process = false;
33780b57cec5SDimitry Andric 
33790b57cec5SDimitry Andric   return error;
33800b57cec5SDimitry Andric }
33810b57cec5SDimitry Andric 
Signal(int signal)33820b57cec5SDimitry Andric Status Process::Signal(int signal) {
33830b57cec5SDimitry Andric   Status error(WillSignal());
33840b57cec5SDimitry Andric   if (error.Success()) {
33850b57cec5SDimitry Andric     error = DoSignal(signal);
33860b57cec5SDimitry Andric     if (error.Success())
33870b57cec5SDimitry Andric       DidSignal();
33880b57cec5SDimitry Andric   }
33890b57cec5SDimitry Andric   return error;
33900b57cec5SDimitry Andric }
33910b57cec5SDimitry Andric 
SetUnixSignals(UnixSignalsSP && signals_sp)33920b57cec5SDimitry Andric void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
33930b57cec5SDimitry Andric   assert(signals_sp && "null signals_sp");
3394fe013be4SDimitry Andric   m_unix_signals_sp = std::move(signals_sp);
33950b57cec5SDimitry Andric }
33960b57cec5SDimitry Andric 
GetUnixSignals()33970b57cec5SDimitry Andric const lldb::UnixSignalsSP &Process::GetUnixSignals() {
33980b57cec5SDimitry Andric   assert(m_unix_signals_sp && "null m_unix_signals_sp");
33990b57cec5SDimitry Andric   return m_unix_signals_sp;
34000b57cec5SDimitry Andric }
34010b57cec5SDimitry Andric 
GetByteOrder() const34020b57cec5SDimitry Andric lldb::ByteOrder Process::GetByteOrder() const {
34030b57cec5SDimitry Andric   return GetTarget().GetArchitecture().GetByteOrder();
34040b57cec5SDimitry Andric }
34050b57cec5SDimitry Andric 
GetAddressByteSize() const34060b57cec5SDimitry Andric uint32_t Process::GetAddressByteSize() const {
34070b57cec5SDimitry Andric   return GetTarget().GetArchitecture().GetAddressByteSize();
34080b57cec5SDimitry Andric }
34090b57cec5SDimitry Andric 
ShouldBroadcastEvent(Event * event_ptr)34100b57cec5SDimitry Andric bool Process::ShouldBroadcastEvent(Event *event_ptr) {
34110b57cec5SDimitry Andric   const StateType state =
34120b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_ptr);
34130b57cec5SDimitry Andric   bool return_value = true;
341481ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::Events | LLDBLog::Process));
34150b57cec5SDimitry Andric 
34160b57cec5SDimitry Andric   switch (state) {
34170b57cec5SDimitry Andric   case eStateDetached:
34180b57cec5SDimitry Andric   case eStateExited:
34190b57cec5SDimitry Andric   case eStateUnloaded:
34200b57cec5SDimitry Andric     m_stdio_communication.SynchronizeWithReadThread();
34210b57cec5SDimitry Andric     m_stdio_communication.StopReadThread();
34225ffd83dbSDimitry Andric     m_stdio_communication.Disconnect();
34230b57cec5SDimitry Andric     m_stdin_forward = false;
34240b57cec5SDimitry Andric 
3425bdd1243dSDimitry Andric     [[fallthrough]];
34260b57cec5SDimitry Andric   case eStateConnected:
34270b57cec5SDimitry Andric   case eStateAttaching:
34280b57cec5SDimitry Andric   case eStateLaunching:
34290b57cec5SDimitry Andric     // These events indicate changes in the state of the debugging session,
34300b57cec5SDimitry Andric     // always report them.
34310b57cec5SDimitry Andric     return_value = true;
34320b57cec5SDimitry Andric     break;
34330b57cec5SDimitry Andric   case eStateInvalid:
34340b57cec5SDimitry Andric     // We stopped for no apparent reason, don't report it.
34350b57cec5SDimitry Andric     return_value = false;
34360b57cec5SDimitry Andric     break;
34370b57cec5SDimitry Andric   case eStateRunning:
34380b57cec5SDimitry Andric   case eStateStepping:
34390b57cec5SDimitry Andric     // If we've started the target running, we handle the cases where we are
34400b57cec5SDimitry Andric     // already running and where there is a transition from stopped to running
34410b57cec5SDimitry Andric     // differently. running -> running: Automatically suppress extra running
34420b57cec5SDimitry Andric     // events stopped -> running: Report except when there is one or more no
34430b57cec5SDimitry Andric     // votes
34440b57cec5SDimitry Andric     //     and no yes votes.
34450b57cec5SDimitry Andric     SynchronouslyNotifyStateChanged(state);
34460b57cec5SDimitry Andric     if (m_force_next_event_delivery)
34470b57cec5SDimitry Andric       return_value = true;
34480b57cec5SDimitry Andric     else {
34490b57cec5SDimitry Andric       switch (m_last_broadcast_state) {
34500b57cec5SDimitry Andric       case eStateRunning:
34510b57cec5SDimitry Andric       case eStateStepping:
34520b57cec5SDimitry Andric         // We always suppress multiple runnings with no PUBLIC stop in between.
34530b57cec5SDimitry Andric         return_value = false;
34540b57cec5SDimitry Andric         break;
34550b57cec5SDimitry Andric       default:
34560b57cec5SDimitry Andric         // TODO: make this work correctly. For now always report
34570b57cec5SDimitry Andric         // run if we aren't running so we don't miss any running events. If I
34580b57cec5SDimitry Andric         // run the lldb/test/thread/a.out file and break at main.cpp:58, run
34590b57cec5SDimitry Andric         // and hit the breakpoints on multiple threads, then somehow during the
34600b57cec5SDimitry Andric         // stepping over of all breakpoints no run gets reported.
34610b57cec5SDimitry Andric 
34620b57cec5SDimitry Andric         // This is a transition from stop to run.
34630b57cec5SDimitry Andric         switch (m_thread_list.ShouldReportRun(event_ptr)) {
34640b57cec5SDimitry Andric         case eVoteYes:
34650b57cec5SDimitry Andric         case eVoteNoOpinion:
34660b57cec5SDimitry Andric           return_value = true;
34670b57cec5SDimitry Andric           break;
34680b57cec5SDimitry Andric         case eVoteNo:
34690b57cec5SDimitry Andric           return_value = false;
34700b57cec5SDimitry Andric           break;
34710b57cec5SDimitry Andric         }
34720b57cec5SDimitry Andric         break;
34730b57cec5SDimitry Andric       }
34740b57cec5SDimitry Andric     }
34750b57cec5SDimitry Andric     break;
34760b57cec5SDimitry Andric   case eStateStopped:
34770b57cec5SDimitry Andric   case eStateCrashed:
34780b57cec5SDimitry Andric   case eStateSuspended:
34790b57cec5SDimitry Andric     // We've stopped.  First see if we're going to restart the target. If we
34800b57cec5SDimitry Andric     // are going to stop, then we always broadcast the event. If we aren't
34810b57cec5SDimitry Andric     // going to stop, let the thread plans decide if we're going to report this
34820b57cec5SDimitry Andric     // event. If no thread has an opinion, we don't report it.
34830b57cec5SDimitry Andric 
34840b57cec5SDimitry Andric     m_stdio_communication.SynchronizeWithReadThread();
34850b57cec5SDimitry Andric     RefreshStateAfterStop();
34860b57cec5SDimitry Andric     if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
34879dba64beSDimitry Andric       LLDB_LOGF(log,
34889dba64beSDimitry Andric                 "Process::ShouldBroadcastEvent (%p) stopped due to an "
34890b57cec5SDimitry Andric                 "interrupt, state: %s",
34900b57cec5SDimitry Andric                 static_cast<void *>(event_ptr), StateAsCString(state));
34910b57cec5SDimitry Andric       // Even though we know we are going to stop, we should let the threads
34920b57cec5SDimitry Andric       // have a look at the stop, so they can properly set their state.
34930b57cec5SDimitry Andric       m_thread_list.ShouldStop(event_ptr);
34940b57cec5SDimitry Andric       return_value = true;
34950b57cec5SDimitry Andric     } else {
34960b57cec5SDimitry Andric       bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
34970b57cec5SDimitry Andric       bool should_resume = false;
34980b57cec5SDimitry Andric 
34990b57cec5SDimitry Andric       // It makes no sense to ask "ShouldStop" if we've already been
35000b57cec5SDimitry Andric       // restarted... Asking the thread list is also not likely to go well,
35010b57cec5SDimitry Andric       // since we are running again. So in that case just report the event.
35020b57cec5SDimitry Andric 
35030b57cec5SDimitry Andric       if (!was_restarted)
35040b57cec5SDimitry Andric         should_resume = !m_thread_list.ShouldStop(event_ptr);
35050b57cec5SDimitry Andric 
35060b57cec5SDimitry Andric       if (was_restarted || should_resume || m_resume_requested) {
3507fe6060f1SDimitry Andric         Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
35089dba64beSDimitry Andric         LLDB_LOGF(log,
35099dba64beSDimitry Andric                   "Process::ShouldBroadcastEvent: should_resume: %i state: "
3510fe6060f1SDimitry Andric                   "%s was_restarted: %i report_stop_vote: %d.",
35110b57cec5SDimitry Andric                   should_resume, StateAsCString(state), was_restarted,
3512fe6060f1SDimitry Andric                   report_stop_vote);
35130b57cec5SDimitry Andric 
3514fe6060f1SDimitry Andric         switch (report_stop_vote) {
35150b57cec5SDimitry Andric         case eVoteYes:
35160b57cec5SDimitry Andric           return_value = true;
35170b57cec5SDimitry Andric           break;
35180b57cec5SDimitry Andric         case eVoteNoOpinion:
35190b57cec5SDimitry Andric         case eVoteNo:
35200b57cec5SDimitry Andric           return_value = false;
35210b57cec5SDimitry Andric           break;
35220b57cec5SDimitry Andric         }
35230b57cec5SDimitry Andric 
35240b57cec5SDimitry Andric         if (!was_restarted) {
35259dba64beSDimitry Andric           LLDB_LOGF(log,
35269dba64beSDimitry Andric                     "Process::ShouldBroadcastEvent (%p) Restarting process "
35270b57cec5SDimitry Andric                     "from state: %s",
35280b57cec5SDimitry Andric                     static_cast<void *>(event_ptr), StateAsCString(state));
35290b57cec5SDimitry Andric           ProcessEventData::SetRestartedInEvent(event_ptr, true);
35300b57cec5SDimitry Andric           PrivateResume();
35310b57cec5SDimitry Andric         }
35320b57cec5SDimitry Andric       } else {
35330b57cec5SDimitry Andric         return_value = true;
35340b57cec5SDimitry Andric         SynchronouslyNotifyStateChanged(state);
35350b57cec5SDimitry Andric       }
35360b57cec5SDimitry Andric     }
35370b57cec5SDimitry Andric     break;
35380b57cec5SDimitry Andric   }
35390b57cec5SDimitry Andric 
35400b57cec5SDimitry Andric   // Forcing the next event delivery is a one shot deal.  So reset it here.
35410b57cec5SDimitry Andric   m_force_next_event_delivery = false;
35420b57cec5SDimitry Andric 
35430b57cec5SDimitry Andric   // We do some coalescing of events (for instance two consecutive running
35440b57cec5SDimitry Andric   // events get coalesced.) But we only coalesce against events we actually
35450b57cec5SDimitry Andric   // broadcast.  So we use m_last_broadcast_state to track that.  NB - you
35460b57cec5SDimitry Andric   // can't use "m_public_state.GetValue()" for that purpose, as was originally
35470b57cec5SDimitry Andric   // done, because the PublicState reflects the last event pulled off the
35480b57cec5SDimitry Andric   // queue, and there may be several events stacked up on the queue unserviced.
35490b57cec5SDimitry Andric   // So the PublicState may not reflect the last broadcasted event yet.
35500b57cec5SDimitry Andric   // m_last_broadcast_state gets updated here.
35510b57cec5SDimitry Andric 
35520b57cec5SDimitry Andric   if (return_value)
35530b57cec5SDimitry Andric     m_last_broadcast_state = state;
35540b57cec5SDimitry Andric 
35559dba64beSDimitry Andric   LLDB_LOGF(log,
35569dba64beSDimitry Andric             "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
35570b57cec5SDimitry Andric             "broadcast state: %s - %s",
35580b57cec5SDimitry Andric             static_cast<void *>(event_ptr), StateAsCString(state),
35590b57cec5SDimitry Andric             StateAsCString(m_last_broadcast_state),
35600b57cec5SDimitry Andric             return_value ? "YES" : "NO");
35610b57cec5SDimitry Andric   return return_value;
35620b57cec5SDimitry Andric }
35630b57cec5SDimitry Andric 
StartPrivateStateThread(bool is_secondary_thread)35640b57cec5SDimitry Andric bool Process::StartPrivateStateThread(bool is_secondary_thread) {
356581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Events);
35660b57cec5SDimitry Andric 
35670b57cec5SDimitry Andric   bool already_running = PrivateStateThreadIsValid();
35689dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
35690b57cec5SDimitry Andric             already_running ? " already running"
35700b57cec5SDimitry Andric                             : " starting private state thread");
35710b57cec5SDimitry Andric 
35720b57cec5SDimitry Andric   if (!is_secondary_thread && already_running)
35730b57cec5SDimitry Andric     return true;
35740b57cec5SDimitry Andric 
35750b57cec5SDimitry Andric   // Create a thread that watches our internal state and controls which events
35760b57cec5SDimitry Andric   // make it to clients (into the DCProcess event queue).
35770b57cec5SDimitry Andric   char thread_name[1024];
35780b57cec5SDimitry Andric   uint32_t max_len = llvm::get_max_thread_name_length();
35790b57cec5SDimitry Andric   if (max_len > 0 && max_len <= 30) {
35800b57cec5SDimitry Andric     // On platforms with abbreviated thread name lengths, choose thread names
35810b57cec5SDimitry Andric     // that fit within the limit.
35820b57cec5SDimitry Andric     if (already_running)
35830b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
35840b57cec5SDimitry Andric     else
35850b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name), "intern-state");
35860b57cec5SDimitry Andric   } else {
35870b57cec5SDimitry Andric     if (already_running)
35880b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name),
35890b57cec5SDimitry Andric                "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
35900b57cec5SDimitry Andric                GetID());
35910b57cec5SDimitry Andric     else
35920b57cec5SDimitry Andric       snprintf(thread_name, sizeof(thread_name),
35930b57cec5SDimitry Andric                "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
35940b57cec5SDimitry Andric   }
35950b57cec5SDimitry Andric 
35960b57cec5SDimitry Andric   llvm::Expected<HostThread> private_state_thread =
359781ad6265SDimitry Andric       ThreadLauncher::LaunchThread(
359881ad6265SDimitry Andric           thread_name,
359981ad6265SDimitry Andric           [this, is_secondary_thread] {
360081ad6265SDimitry Andric             return RunPrivateStateThread(is_secondary_thread);
360181ad6265SDimitry Andric           },
360281ad6265SDimitry Andric           8 * 1024 * 1024);
36030b57cec5SDimitry Andric   if (!private_state_thread) {
3604fe013be4SDimitry Andric     LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
3605fe013be4SDimitry Andric                    "failed to launch host thread: {0}");
36060b57cec5SDimitry Andric     return false;
36070b57cec5SDimitry Andric   }
36080b57cec5SDimitry Andric 
36090b57cec5SDimitry Andric   assert(private_state_thread->IsJoinable());
36100b57cec5SDimitry Andric   m_private_state_thread = *private_state_thread;
36110b57cec5SDimitry Andric   ResumePrivateStateThread();
36120b57cec5SDimitry Andric   return true;
36130b57cec5SDimitry Andric }
36140b57cec5SDimitry Andric 
PausePrivateStateThread()36150b57cec5SDimitry Andric void Process::PausePrivateStateThread() {
36160b57cec5SDimitry Andric   ControlPrivateStateThread(eBroadcastInternalStateControlPause);
36170b57cec5SDimitry Andric }
36180b57cec5SDimitry Andric 
ResumePrivateStateThread()36190b57cec5SDimitry Andric void Process::ResumePrivateStateThread() {
36200b57cec5SDimitry Andric   ControlPrivateStateThread(eBroadcastInternalStateControlResume);
36210b57cec5SDimitry Andric }
36220b57cec5SDimitry Andric 
StopPrivateStateThread()36230b57cec5SDimitry Andric void Process::StopPrivateStateThread() {
36240b57cec5SDimitry Andric   if (m_private_state_thread.IsJoinable())
36250b57cec5SDimitry Andric     ControlPrivateStateThread(eBroadcastInternalStateControlStop);
36260b57cec5SDimitry Andric   else {
362781ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
36289dba64beSDimitry Andric     LLDB_LOGF(
36299dba64beSDimitry Andric         log,
36300b57cec5SDimitry Andric         "Went to stop the private state thread, but it was already invalid.");
36310b57cec5SDimitry Andric   }
36320b57cec5SDimitry Andric }
36330b57cec5SDimitry Andric 
ControlPrivateStateThread(uint32_t signal)36340b57cec5SDimitry Andric void Process::ControlPrivateStateThread(uint32_t signal) {
363581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
36360b57cec5SDimitry Andric 
36370b57cec5SDimitry Andric   assert(signal == eBroadcastInternalStateControlStop ||
36380b57cec5SDimitry Andric          signal == eBroadcastInternalStateControlPause ||
36390b57cec5SDimitry Andric          signal == eBroadcastInternalStateControlResume);
36400b57cec5SDimitry Andric 
36419dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
36420b57cec5SDimitry Andric 
36430b57cec5SDimitry Andric   // Signal the private state thread
36440b57cec5SDimitry Andric   if (m_private_state_thread.IsJoinable()) {
36450b57cec5SDimitry Andric     // Broadcast the event.
36460b57cec5SDimitry Andric     // It is important to do this outside of the if below, because it's
36470b57cec5SDimitry Andric     // possible that the thread state is invalid but that the thread is waiting
36480b57cec5SDimitry Andric     // on a control event instead of simply being on its way out (this should
36490b57cec5SDimitry Andric     // not happen, but it apparently can).
36509dba64beSDimitry Andric     LLDB_LOGF(log, "Sending control event of type: %d.", signal);
36510b57cec5SDimitry Andric     std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
36520b57cec5SDimitry Andric     m_private_state_control_broadcaster.BroadcastEvent(signal,
36530b57cec5SDimitry Andric                                                        event_receipt_sp);
36540b57cec5SDimitry Andric 
36550b57cec5SDimitry Andric     // Wait for the event receipt or for the private state thread to exit
36560b57cec5SDimitry Andric     bool receipt_received = false;
36570b57cec5SDimitry Andric     if (PrivateStateThreadIsValid()) {
36580b57cec5SDimitry Andric       while (!receipt_received) {
36590b57cec5SDimitry Andric         // Check for a receipt for n seconds and then check if the private
36600b57cec5SDimitry Andric         // state thread is still around.
36610b57cec5SDimitry Andric         receipt_received =
36620b57cec5SDimitry Andric           event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
36630b57cec5SDimitry Andric         if (!receipt_received) {
36640b57cec5SDimitry Andric           // Check if the private state thread is still around. If it isn't
36650b57cec5SDimitry Andric           // then we are done waiting
36660b57cec5SDimitry Andric           if (!PrivateStateThreadIsValid())
36670b57cec5SDimitry Andric             break; // Private state thread exited or is exiting, we are done
36680b57cec5SDimitry Andric         }
36690b57cec5SDimitry Andric       }
36700b57cec5SDimitry Andric     }
36710b57cec5SDimitry Andric 
36720b57cec5SDimitry Andric     if (signal == eBroadcastInternalStateControlStop) {
36730b57cec5SDimitry Andric       thread_result_t result = {};
36740b57cec5SDimitry Andric       m_private_state_thread.Join(&result);
36750b57cec5SDimitry Andric       m_private_state_thread.Reset();
36760b57cec5SDimitry Andric     }
36770b57cec5SDimitry Andric   } else {
36789dba64beSDimitry Andric     LLDB_LOGF(
36799dba64beSDimitry Andric         log,
36800b57cec5SDimitry Andric         "Private state thread already dead, no need to signal it to stop.");
36810b57cec5SDimitry Andric   }
36820b57cec5SDimitry Andric }
36830b57cec5SDimitry Andric 
SendAsyncInterrupt()36840b57cec5SDimitry Andric void Process::SendAsyncInterrupt() {
36850b57cec5SDimitry Andric   if (PrivateStateThreadIsValid())
36860b57cec5SDimitry Andric     m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
36870b57cec5SDimitry Andric                                                nullptr);
36880b57cec5SDimitry Andric   else
36890b57cec5SDimitry Andric     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
36900b57cec5SDimitry Andric }
36910b57cec5SDimitry Andric 
HandlePrivateEvent(EventSP & event_sp)36920b57cec5SDimitry Andric void Process::HandlePrivateEvent(EventSP &event_sp) {
369381ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
36940b57cec5SDimitry Andric   m_resume_requested = false;
36950b57cec5SDimitry Andric 
36960b57cec5SDimitry Andric   const StateType new_state =
36970b57cec5SDimitry Andric       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
36980b57cec5SDimitry Andric 
36990b57cec5SDimitry Andric   // First check to see if anybody wants a shot at this event:
37000b57cec5SDimitry Andric   if (m_next_event_action_up) {
37010b57cec5SDimitry Andric     NextEventAction::EventActionResult action_result =
37020b57cec5SDimitry Andric         m_next_event_action_up->PerformAction(event_sp);
37039dba64beSDimitry Andric     LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric     switch (action_result) {
37060b57cec5SDimitry Andric     case NextEventAction::eEventActionSuccess:
37070b57cec5SDimitry Andric       SetNextEventAction(nullptr);
37080b57cec5SDimitry Andric       break;
37090b57cec5SDimitry Andric 
37100b57cec5SDimitry Andric     case NextEventAction::eEventActionRetry:
37110b57cec5SDimitry Andric       break;
37120b57cec5SDimitry Andric 
37130b57cec5SDimitry Andric     case NextEventAction::eEventActionExit:
37140b57cec5SDimitry Andric       // Handle Exiting Here.  If we already got an exited event, we should
37150b57cec5SDimitry Andric       // just propagate it.  Otherwise, swallow this event, and set our state
37160b57cec5SDimitry Andric       // to exit so the next event will kill us.
37170b57cec5SDimitry Andric       if (new_state != eStateExited) {
37180b57cec5SDimitry Andric         // FIXME: should cons up an exited event, and discard this one.
37190b57cec5SDimitry Andric         SetExitStatus(0, m_next_event_action_up->GetExitString());
37200b57cec5SDimitry Andric         SetNextEventAction(nullptr);
37210b57cec5SDimitry Andric         return;
37220b57cec5SDimitry Andric       }
37230b57cec5SDimitry Andric       SetNextEventAction(nullptr);
37240b57cec5SDimitry Andric       break;
37250b57cec5SDimitry Andric     }
37260b57cec5SDimitry Andric   }
37270b57cec5SDimitry Andric 
37280b57cec5SDimitry Andric   // See if we should broadcast this state to external clients?
37290b57cec5SDimitry Andric   const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
37300b57cec5SDimitry Andric 
37310b57cec5SDimitry Andric   if (should_broadcast) {
37320b57cec5SDimitry Andric     const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
37330b57cec5SDimitry Andric     if (log) {
37349dba64beSDimitry Andric       LLDB_LOGF(log,
37359dba64beSDimitry Andric                 "Process::%s (pid = %" PRIu64
37360b57cec5SDimitry Andric                 ") broadcasting new state %s (old state %s) to %s",
37370b57cec5SDimitry Andric                 __FUNCTION__, GetID(), StateAsCString(new_state),
37380b57cec5SDimitry Andric                 StateAsCString(GetState()),
37390b57cec5SDimitry Andric                 is_hijacked ? "hijacked" : "public");
37400b57cec5SDimitry Andric     }
37410b57cec5SDimitry Andric     Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
37420b57cec5SDimitry Andric     if (StateIsRunningState(new_state)) {
37430b57cec5SDimitry Andric       // Only push the input handler if we aren't fowarding events, as this
37440b57cec5SDimitry Andric       // means the curses GUI is in use... Or don't push it if we are launching
37450b57cec5SDimitry Andric       // since it will come up stopped.
37460b57cec5SDimitry Andric       if (!GetTarget().GetDebugger().IsForwardingEvents() &&
37470b57cec5SDimitry Andric           new_state != eStateLaunching && new_state != eStateAttaching) {
37480b57cec5SDimitry Andric         PushProcessIOHandler();
37490b57cec5SDimitry Andric         m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
37500b57cec5SDimitry Andric                                   eBroadcastAlways);
37519dba64beSDimitry Andric         LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
37520b57cec5SDimitry Andric                   __FUNCTION__, m_iohandler_sync.GetValue());
37530b57cec5SDimitry Andric       }
37540b57cec5SDimitry Andric     } else if (StateIsStoppedState(new_state, false)) {
37550b57cec5SDimitry Andric       if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
37560b57cec5SDimitry Andric         // If the lldb_private::Debugger is handling the events, we don't want
37570b57cec5SDimitry Andric         // to pop the process IOHandler here, we want to do it when we receive
37580b57cec5SDimitry Andric         // the stopped event so we can carefully control when the process
37590b57cec5SDimitry Andric         // IOHandler is popped because when we stop we want to display some
37600b57cec5SDimitry Andric         // text stating how and why we stopped, then maybe some
37610b57cec5SDimitry Andric         // process/thread/frame info, and then we want the "(lldb) " prompt to
37620b57cec5SDimitry Andric         // show up. If we pop the process IOHandler here, then we will cause
37630b57cec5SDimitry Andric         // the command interpreter to become the top IOHandler after the
37640b57cec5SDimitry Andric         // process pops off and it will update its prompt right away... See the
37650b57cec5SDimitry Andric         // Debugger.cpp file where it calls the function as
37660b57cec5SDimitry Andric         // "process_sp->PopProcessIOHandler()" to see where I am talking about.
37670b57cec5SDimitry Andric         // Otherwise we end up getting overlapping "(lldb) " prompts and
37680b57cec5SDimitry Andric         // garbled output.
37690b57cec5SDimitry Andric         //
37700b57cec5SDimitry Andric         // If we aren't handling the events in the debugger (which is indicated
37710b57cec5SDimitry Andric         // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
37720b57cec5SDimitry Andric         // we are hijacked, then we always pop the process IO handler manually.
37730b57cec5SDimitry Andric         // Hijacking happens when the internal process state thread is running
37740b57cec5SDimitry Andric         // thread plans, or when commands want to run in synchronous mode and
37750b57cec5SDimitry Andric         // they call "process->WaitForProcessToStop()". An example of something
37760b57cec5SDimitry Andric         // that will hijack the events is a simple expression:
37770b57cec5SDimitry Andric         //
37780b57cec5SDimitry Andric         //  (lldb) expr (int)puts("hello")
37790b57cec5SDimitry Andric         //
37800b57cec5SDimitry Andric         // This will cause the internal process state thread to resume and halt
37810b57cec5SDimitry Andric         // the process (and _it_ will hijack the eBroadcastBitStateChanged
37820b57cec5SDimitry Andric         // events) and we do need the IO handler to be pushed and popped
37830b57cec5SDimitry Andric         // correctly.
37840b57cec5SDimitry Andric 
37850b57cec5SDimitry Andric         if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
37860b57cec5SDimitry Andric           PopProcessIOHandler();
37870b57cec5SDimitry Andric       }
37880b57cec5SDimitry Andric     }
37890b57cec5SDimitry Andric 
37900b57cec5SDimitry Andric     BroadcastEvent(event_sp);
37910b57cec5SDimitry Andric   } else {
37920b57cec5SDimitry Andric     if (log) {
37939dba64beSDimitry Andric       LLDB_LOGF(
37949dba64beSDimitry Andric           log,
37950b57cec5SDimitry Andric           "Process::%s (pid = %" PRIu64
37960b57cec5SDimitry Andric           ") suppressing state %s (old state %s): should_broadcast == false",
37970b57cec5SDimitry Andric           __FUNCTION__, GetID(), StateAsCString(new_state),
37980b57cec5SDimitry Andric           StateAsCString(GetState()));
37990b57cec5SDimitry Andric     }
38000b57cec5SDimitry Andric   }
38010b57cec5SDimitry Andric }
38020b57cec5SDimitry Andric 
HaltPrivate()38030b57cec5SDimitry Andric Status Process::HaltPrivate() {
38040b57cec5SDimitry Andric   EventSP event_sp;
38050b57cec5SDimitry Andric   Status error(WillHalt());
38060b57cec5SDimitry Andric   if (error.Fail())
38070b57cec5SDimitry Andric     return error;
38080b57cec5SDimitry Andric 
38090b57cec5SDimitry Andric   // Ask the process subclass to actually halt our process
38100b57cec5SDimitry Andric   bool caused_stop;
38110b57cec5SDimitry Andric   error = DoHalt(caused_stop);
38120b57cec5SDimitry Andric 
38130b57cec5SDimitry Andric   DidHalt();
38140b57cec5SDimitry Andric   return error;
38150b57cec5SDimitry Andric }
38160b57cec5SDimitry Andric 
RunPrivateStateThread(bool is_secondary_thread)38170b57cec5SDimitry Andric thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
38180b57cec5SDimitry Andric   bool control_only = true;
38190b57cec5SDimitry Andric 
382081ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
38219dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
38220b57cec5SDimitry Andric             __FUNCTION__, static_cast<void *>(this), GetID());
38230b57cec5SDimitry Andric 
38240b57cec5SDimitry Andric   bool exit_now = false;
38250b57cec5SDimitry Andric   bool interrupt_requested = false;
38260b57cec5SDimitry Andric   while (!exit_now) {
38270b57cec5SDimitry Andric     EventSP event_sp;
3828bdd1243dSDimitry Andric     GetEventsPrivate(event_sp, std::nullopt, control_only);
38290b57cec5SDimitry Andric     if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
38309dba64beSDimitry Andric       LLDB_LOGF(log,
38319dba64beSDimitry Andric                 "Process::%s (arg = %p, pid = %" PRIu64
38320b57cec5SDimitry Andric                 ") got a control event: %d",
38330b57cec5SDimitry Andric                 __FUNCTION__, static_cast<void *>(this), GetID(),
38340b57cec5SDimitry Andric                 event_sp->GetType());
38350b57cec5SDimitry Andric 
38360b57cec5SDimitry Andric       switch (event_sp->GetType()) {
38370b57cec5SDimitry Andric       case eBroadcastInternalStateControlStop:
38380b57cec5SDimitry Andric         exit_now = true;
38390b57cec5SDimitry Andric         break; // doing any internal state management below
38400b57cec5SDimitry Andric 
38410b57cec5SDimitry Andric       case eBroadcastInternalStateControlPause:
38420b57cec5SDimitry Andric         control_only = true;
38430b57cec5SDimitry Andric         break;
38440b57cec5SDimitry Andric 
38450b57cec5SDimitry Andric       case eBroadcastInternalStateControlResume:
38460b57cec5SDimitry Andric         control_only = false;
38470b57cec5SDimitry Andric         break;
38480b57cec5SDimitry Andric       }
38490b57cec5SDimitry Andric 
38500b57cec5SDimitry Andric       continue;
38510b57cec5SDimitry Andric     } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
38520b57cec5SDimitry Andric       if (m_public_state.GetValue() == eStateAttaching) {
38539dba64beSDimitry Andric         LLDB_LOGF(log,
38549dba64beSDimitry Andric                   "Process::%s (arg = %p, pid = %" PRIu64
38550b57cec5SDimitry Andric                   ") woke up with an interrupt while attaching - "
38560b57cec5SDimitry Andric                   "forwarding interrupt.",
38570b57cec5SDimitry Andric                   __FUNCTION__, static_cast<void *>(this), GetID());
3858c9157d92SDimitry Andric         // The server may be spinning waiting for a process to appear, in which
3859c9157d92SDimitry Andric         // case we should tell it to stop doing that.  Normally, we don't NEED
3860c9157d92SDimitry Andric         // to do that because we will next close the communication to the stub
3861c9157d92SDimitry Andric         // and that will get it to shut down.  But there are remote debugging
3862c9157d92SDimitry Andric         // cases where relying on that side-effect causes the shutdown to be
3863c9157d92SDimitry Andric         // flakey, so we should send a positive signal to interrupt the wait.
3864c9157d92SDimitry Andric         Status error = HaltPrivate();
38650b57cec5SDimitry Andric         BroadcastEvent(eBroadcastBitInterrupt, nullptr);
38660b57cec5SDimitry Andric       } else if (StateIsRunningState(m_last_broadcast_state)) {
38679dba64beSDimitry Andric         LLDB_LOGF(log,
38689dba64beSDimitry Andric                   "Process::%s (arg = %p, pid = %" PRIu64
38690b57cec5SDimitry Andric                   ") woke up with an interrupt - Halting.",
38700b57cec5SDimitry Andric                   __FUNCTION__, static_cast<void *>(this), GetID());
38710b57cec5SDimitry Andric         Status error = HaltPrivate();
38720b57cec5SDimitry Andric         if (error.Fail() && log)
38739dba64beSDimitry Andric           LLDB_LOGF(log,
38749dba64beSDimitry Andric                     "Process::%s (arg = %p, pid = %" PRIu64
38750b57cec5SDimitry Andric                     ") failed to halt the process: %s",
38760b57cec5SDimitry Andric                     __FUNCTION__, static_cast<void *>(this), GetID(),
38770b57cec5SDimitry Andric                     error.AsCString());
38780b57cec5SDimitry Andric         // Halt should generate a stopped event. Make a note of the fact that
38790b57cec5SDimitry Andric         // we were doing the interrupt, so we can set the interrupted flag
38800b57cec5SDimitry Andric         // after we receive the event. We deliberately set this to true even if
38810b57cec5SDimitry Andric         // HaltPrivate failed, so that we can interrupt on the next natural
38820b57cec5SDimitry Andric         // stop.
38830b57cec5SDimitry Andric         interrupt_requested = true;
38840b57cec5SDimitry Andric       } else {
38850b57cec5SDimitry Andric         // This can happen when someone (e.g. Process::Halt) sees that we are
38860b57cec5SDimitry Andric         // running and sends an interrupt request, but the process actually
38870b57cec5SDimitry Andric         // stops before we receive it. In that case, we can just ignore the
38880b57cec5SDimitry Andric         // request. We use m_last_broadcast_state, because the Stopped event
38890b57cec5SDimitry Andric         // may not have been popped of the event queue yet, which is when the
38900b57cec5SDimitry Andric         // public state gets updated.
38919dba64beSDimitry Andric         LLDB_LOGF(log,
38920b57cec5SDimitry Andric                   "Process::%s ignoring interrupt as we have already stopped.",
38930b57cec5SDimitry Andric                   __FUNCTION__);
38940b57cec5SDimitry Andric       }
38950b57cec5SDimitry Andric       continue;
38960b57cec5SDimitry Andric     }
38970b57cec5SDimitry Andric 
38980b57cec5SDimitry Andric     const StateType internal_state =
38990b57cec5SDimitry Andric         Process::ProcessEventData::GetStateFromEvent(event_sp.get());
39000b57cec5SDimitry Andric 
39010b57cec5SDimitry Andric     if (internal_state != eStateInvalid) {
39020b57cec5SDimitry Andric       if (m_clear_thread_plans_on_stop &&
39030b57cec5SDimitry Andric           StateIsStoppedState(internal_state, true)) {
39040b57cec5SDimitry Andric         m_clear_thread_plans_on_stop = false;
39050b57cec5SDimitry Andric         m_thread_list.DiscardThreadPlans();
39060b57cec5SDimitry Andric       }
39070b57cec5SDimitry Andric 
39080b57cec5SDimitry Andric       if (interrupt_requested) {
39090b57cec5SDimitry Andric         if (StateIsStoppedState(internal_state, true)) {
39100b57cec5SDimitry Andric           // We requested the interrupt, so mark this as such in the stop event
39110b57cec5SDimitry Andric           // so clients can tell an interrupted process from a natural stop
39120b57cec5SDimitry Andric           ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
39130b57cec5SDimitry Andric           interrupt_requested = false;
39140b57cec5SDimitry Andric         } else if (log) {
39159dba64beSDimitry Andric           LLDB_LOGF(log,
39169dba64beSDimitry Andric                     "Process::%s interrupt_requested, but a non-stopped "
39170b57cec5SDimitry Andric                     "state '%s' received.",
39180b57cec5SDimitry Andric                     __FUNCTION__, StateAsCString(internal_state));
39190b57cec5SDimitry Andric         }
39200b57cec5SDimitry Andric       }
39210b57cec5SDimitry Andric 
39220b57cec5SDimitry Andric       HandlePrivateEvent(event_sp);
39230b57cec5SDimitry Andric     }
39240b57cec5SDimitry Andric 
39250b57cec5SDimitry Andric     if (internal_state == eStateInvalid || internal_state == eStateExited ||
39260b57cec5SDimitry Andric         internal_state == eStateDetached) {
39279dba64beSDimitry Andric       LLDB_LOGF(log,
39289dba64beSDimitry Andric                 "Process::%s (arg = %p, pid = %" PRIu64
39290b57cec5SDimitry Andric                 ") about to exit with internal state %s...",
39300b57cec5SDimitry Andric                 __FUNCTION__, static_cast<void *>(this), GetID(),
39310b57cec5SDimitry Andric                 StateAsCString(internal_state));
39320b57cec5SDimitry Andric 
39330b57cec5SDimitry Andric       break;
39340b57cec5SDimitry Andric     }
39350b57cec5SDimitry Andric   }
39360b57cec5SDimitry Andric 
39370b57cec5SDimitry Andric   // Verify log is still enabled before attempting to write to it...
39389dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
39390b57cec5SDimitry Andric             __FUNCTION__, static_cast<void *>(this), GetID());
39400b57cec5SDimitry Andric 
39410b57cec5SDimitry Andric   // If we are a secondary thread, then the primary thread we are working for
39420b57cec5SDimitry Andric   // will have already acquired the public_run_lock, and isn't done with what
39430b57cec5SDimitry Andric   // it was doing yet, so don't try to change it on the way out.
39440b57cec5SDimitry Andric   if (!is_secondary_thread)
39450b57cec5SDimitry Andric     m_public_run_lock.SetStopped();
39460b57cec5SDimitry Andric   return {};
39470b57cec5SDimitry Andric }
39480b57cec5SDimitry Andric 
39490b57cec5SDimitry Andric // Process Event Data
39500b57cec5SDimitry Andric 
ProcessEventData()3951fe6060f1SDimitry Andric Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp() {}
39520b57cec5SDimitry Andric 
ProcessEventData(const ProcessSP & process_sp,StateType state)39530b57cec5SDimitry Andric Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
39540b57cec5SDimitry Andric                                             StateType state)
395581ad6265SDimitry Andric     : EventData(), m_process_wp(), m_state(state) {
39560b57cec5SDimitry Andric   if (process_sp)
39570b57cec5SDimitry Andric     m_process_wp = process_sp;
39580b57cec5SDimitry Andric }
39590b57cec5SDimitry Andric 
39600b57cec5SDimitry Andric Process::ProcessEventData::~ProcessEventData() = default;
39610b57cec5SDimitry Andric 
GetFlavorString()3962fe013be4SDimitry Andric llvm::StringRef Process::ProcessEventData::GetFlavorString() {
3963fe013be4SDimitry Andric   return "Process::ProcessEventData";
39640b57cec5SDimitry Andric }
39650b57cec5SDimitry Andric 
GetFlavor() const3966fe013be4SDimitry Andric llvm::StringRef Process::ProcessEventData::GetFlavor() const {
39670b57cec5SDimitry Andric   return ProcessEventData::GetFlavorString();
39680b57cec5SDimitry Andric }
39690b57cec5SDimitry Andric 
ShouldStop(Event * event_ptr,bool & found_valid_stopinfo)39705ffd83dbSDimitry Andric bool Process::ProcessEventData::ShouldStop(Event *event_ptr,
39715ffd83dbSDimitry Andric                                            bool &found_valid_stopinfo) {
39725ffd83dbSDimitry Andric   found_valid_stopinfo = false;
39735ffd83dbSDimitry Andric 
39745ffd83dbSDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
39755ffd83dbSDimitry Andric   if (!process_sp)
39765ffd83dbSDimitry Andric     return false;
39775ffd83dbSDimitry Andric 
39785ffd83dbSDimitry Andric   ThreadList &curr_thread_list = process_sp->GetThreadList();
39795ffd83dbSDimitry Andric   uint32_t num_threads = curr_thread_list.GetSize();
39805ffd83dbSDimitry Andric   uint32_t idx;
39815ffd83dbSDimitry Andric 
39825ffd83dbSDimitry Andric   // The actions might change one of the thread's stop_info's opinions about
39835ffd83dbSDimitry Andric   // whether we should stop the process, so we need to query that as we go.
39845ffd83dbSDimitry Andric 
39855ffd83dbSDimitry Andric   // One other complication here, is that we try to catch any case where the
39865ffd83dbSDimitry Andric   // target has run (except for expressions) and immediately exit, but if we
39875ffd83dbSDimitry Andric   // get that wrong (which is possible) then the thread list might have
39885ffd83dbSDimitry Andric   // changed, and that would cause our iteration here to crash.  We could
39895ffd83dbSDimitry Andric   // make a copy of the thread list, but we'd really like to also know if it
39905ffd83dbSDimitry Andric   // has changed at all, so we make up a vector of the thread ID's and check
39915ffd83dbSDimitry Andric   // what we get back against this list & bag out if anything differs.
39925ffd83dbSDimitry Andric   ThreadList not_suspended_thread_list(process_sp.get());
39935ffd83dbSDimitry Andric   std::vector<uint32_t> thread_index_array(num_threads);
39945ffd83dbSDimitry Andric   uint32_t not_suspended_idx = 0;
39955ffd83dbSDimitry Andric   for (idx = 0; idx < num_threads; ++idx) {
39965ffd83dbSDimitry Andric     lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
39975ffd83dbSDimitry Andric 
39985ffd83dbSDimitry Andric     /*
39995ffd83dbSDimitry Andric      Filter out all suspended threads, they could not be the reason
40005ffd83dbSDimitry Andric      of stop and no need to perform any actions on them.
40015ffd83dbSDimitry Andric      */
40025ffd83dbSDimitry Andric     if (thread_sp->GetResumeState() != eStateSuspended) {
40035ffd83dbSDimitry Andric       not_suspended_thread_list.AddThread(thread_sp);
40045ffd83dbSDimitry Andric       thread_index_array[not_suspended_idx] = thread_sp->GetIndexID();
40055ffd83dbSDimitry Andric       not_suspended_idx++;
40065ffd83dbSDimitry Andric     }
40075ffd83dbSDimitry Andric   }
40085ffd83dbSDimitry Andric 
40095ffd83dbSDimitry Andric   // Use this to track whether we should continue from here.  We will only
40105ffd83dbSDimitry Andric   // continue the target running if no thread says we should stop.  Of course
40115ffd83dbSDimitry Andric   // if some thread's PerformAction actually sets the target running, then it
40125ffd83dbSDimitry Andric   // doesn't matter what the other threads say...
40135ffd83dbSDimitry Andric 
40145ffd83dbSDimitry Andric   bool still_should_stop = false;
40155ffd83dbSDimitry Andric 
40165ffd83dbSDimitry Andric   // Sometimes - for instance if we have a bug in the stub we are talking to,
40175ffd83dbSDimitry Andric   // we stop but no thread has a valid stop reason.  In that case we should
40185ffd83dbSDimitry Andric   // just stop, because we have no way of telling what the right thing to do
40195ffd83dbSDimitry Andric   // is, and it's better to let the user decide than continue behind their
40205ffd83dbSDimitry Andric   // backs.
40215ffd83dbSDimitry Andric 
40225ffd83dbSDimitry Andric   for (idx = 0; idx < not_suspended_thread_list.GetSize(); ++idx) {
40235ffd83dbSDimitry Andric     curr_thread_list = process_sp->GetThreadList();
40245ffd83dbSDimitry Andric     if (curr_thread_list.GetSize() != num_threads) {
402581ad6265SDimitry Andric       Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));
40265ffd83dbSDimitry Andric       LLDB_LOGF(
40275ffd83dbSDimitry Andric           log,
40285ffd83dbSDimitry Andric           "Number of threads changed from %u to %u while processing event.",
40295ffd83dbSDimitry Andric           num_threads, curr_thread_list.GetSize());
40305ffd83dbSDimitry Andric       break;
40315ffd83dbSDimitry Andric     }
40325ffd83dbSDimitry Andric 
40335ffd83dbSDimitry Andric     lldb::ThreadSP thread_sp = not_suspended_thread_list.GetThreadAtIndex(idx);
40345ffd83dbSDimitry Andric 
40355ffd83dbSDimitry Andric     if (thread_sp->GetIndexID() != thread_index_array[idx]) {
403681ad6265SDimitry Andric       Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));
40375ffd83dbSDimitry Andric       LLDB_LOGF(log,
40385ffd83dbSDimitry Andric                 "The thread at position %u changed from %u to %u while "
40395ffd83dbSDimitry Andric                 "processing event.",
40405ffd83dbSDimitry Andric                 idx, thread_index_array[idx], thread_sp->GetIndexID());
40415ffd83dbSDimitry Andric       break;
40425ffd83dbSDimitry Andric     }
40435ffd83dbSDimitry Andric 
40445ffd83dbSDimitry Andric     StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
40455ffd83dbSDimitry Andric     if (stop_info_sp && stop_info_sp->IsValid()) {
40465ffd83dbSDimitry Andric       found_valid_stopinfo = true;
40475ffd83dbSDimitry Andric       bool this_thread_wants_to_stop;
40485ffd83dbSDimitry Andric       if (stop_info_sp->GetOverrideShouldStop()) {
40495ffd83dbSDimitry Andric         this_thread_wants_to_stop =
40505ffd83dbSDimitry Andric             stop_info_sp->GetOverriddenShouldStopValue();
40515ffd83dbSDimitry Andric       } else {
40525ffd83dbSDimitry Andric         stop_info_sp->PerformAction(event_ptr);
40535ffd83dbSDimitry Andric         // The stop action might restart the target.  If it does, then we
40545ffd83dbSDimitry Andric         // want to mark that in the event so that whoever is receiving it
40555ffd83dbSDimitry Andric         // will know to wait for the running event and reflect that state
40565ffd83dbSDimitry Andric         // appropriately. We also need to stop processing actions, since they
40575ffd83dbSDimitry Andric         // aren't expecting the target to be running.
40585ffd83dbSDimitry Andric 
40595ffd83dbSDimitry Andric         // FIXME: we might have run.
40605ffd83dbSDimitry Andric         if (stop_info_sp->HasTargetRunSinceMe()) {
40615ffd83dbSDimitry Andric           SetRestarted(true);
40625ffd83dbSDimitry Andric           break;
40635ffd83dbSDimitry Andric         }
40645ffd83dbSDimitry Andric 
40655ffd83dbSDimitry Andric         this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
40665ffd83dbSDimitry Andric       }
40675ffd83dbSDimitry Andric 
40685ffd83dbSDimitry Andric       if (!still_should_stop)
40695ffd83dbSDimitry Andric         still_should_stop = this_thread_wants_to_stop;
40705ffd83dbSDimitry Andric     }
40715ffd83dbSDimitry Andric   }
40725ffd83dbSDimitry Andric 
40735ffd83dbSDimitry Andric   return still_should_stop;
40745ffd83dbSDimitry Andric }
40755ffd83dbSDimitry Andric 
DoOnRemoval(Event * event_ptr)40760b57cec5SDimitry Andric void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
40770b57cec5SDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
40780b57cec5SDimitry Andric 
40790b57cec5SDimitry Andric   if (!process_sp)
40800b57cec5SDimitry Andric     return;
40810b57cec5SDimitry Andric 
40820b57cec5SDimitry Andric   // This function gets called twice for each event, once when the event gets
40830b57cec5SDimitry Andric   // pulled off of the private process event queue, and then any number of
40840b57cec5SDimitry Andric   // times, first when it gets pulled off of the public event queue, then other
40850b57cec5SDimitry Andric   // times when we're pretending that this is where we stopped at the end of
40860b57cec5SDimitry Andric   // expression evaluation.  m_update_state is used to distinguish these three
40870b57cec5SDimitry Andric   // cases; it is 0 when we're just pulling it off for private handling, and >
40880b57cec5SDimitry Andric   // 1 for expression evaluation, and we don't want to do the breakpoint
40890b57cec5SDimitry Andric   // command handling then.
40900b57cec5SDimitry Andric   if (m_update_state != 1)
40910b57cec5SDimitry Andric     return;
40920b57cec5SDimitry Andric 
40930b57cec5SDimitry Andric   process_sp->SetPublicState(
40940b57cec5SDimitry Andric       m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
40950b57cec5SDimitry Andric 
40960b57cec5SDimitry Andric   if (m_state == eStateStopped && !m_restarted) {
40970b57cec5SDimitry Andric     // Let process subclasses know we are about to do a public stop and do
40980b57cec5SDimitry Andric     // anything they might need to in order to speed up register and memory
40990b57cec5SDimitry Andric     // accesses.
41000b57cec5SDimitry Andric     process_sp->WillPublicStop();
41010b57cec5SDimitry Andric   }
41020b57cec5SDimitry Andric 
41030b57cec5SDimitry Andric   // If this is a halt event, even if the halt stopped with some reason other
41040b57cec5SDimitry Andric   // than a plain interrupt (e.g. we had already stopped for a breakpoint when
41050b57cec5SDimitry Andric   // the halt request came through) don't do the StopInfo actions, as they may
41060b57cec5SDimitry Andric   // end up restarting the process.
41070b57cec5SDimitry Andric   if (m_interrupted)
41080b57cec5SDimitry Andric     return;
41090b57cec5SDimitry Andric 
41105ffd83dbSDimitry Andric   // If we're not stopped or have restarted, then skip the StopInfo actions:
41115ffd83dbSDimitry Andric   if (m_state != eStateStopped || m_restarted) {
41125ffd83dbSDimitry Andric     return;
41135ffd83dbSDimitry Andric   }
41140b57cec5SDimitry Andric 
41150b57cec5SDimitry Andric   bool does_anybody_have_an_opinion = false;
41165ffd83dbSDimitry Andric   bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
41170b57cec5SDimitry Andric 
41185ffd83dbSDimitry Andric   if (GetRestarted()) {
41195ffd83dbSDimitry Andric     return;
41200b57cec5SDimitry Andric   }
41210b57cec5SDimitry Andric 
41220b57cec5SDimitry Andric   if (!still_should_stop && does_anybody_have_an_opinion) {
41230b57cec5SDimitry Andric     // We've been asked to continue, so do that here.
41240b57cec5SDimitry Andric     SetRestarted(true);
4125c9157d92SDimitry Andric     // Use the private resume method here, since we aren't changing the run
4126c9157d92SDimitry Andric     // lock state.
41270b57cec5SDimitry Andric     process_sp->PrivateResume();
41280b57cec5SDimitry Andric   } else {
41295ffd83dbSDimitry Andric     bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
41300b57cec5SDimitry Andric                     !process_sp->StateChangedIsHijackedForSynchronousResume();
41310b57cec5SDimitry Andric 
41320b57cec5SDimitry Andric     if (!hijacked) {
41330b57cec5SDimitry Andric       // If we didn't restart, run the Stop Hooks here.
41340b57cec5SDimitry Andric       // Don't do that if state changed events aren't hooked up to the
41350b57cec5SDimitry Andric       // public (or SyncResume) broadcasters.  StopHooks are just for
41360b57cec5SDimitry Andric       // real public stops.  They might also restart the target,
41370b57cec5SDimitry Andric       // so watch for that.
4138e8d8bef9SDimitry Andric       if (process_sp->GetTarget().RunStopHooks())
41390b57cec5SDimitry Andric         SetRestarted(true);
41400b57cec5SDimitry Andric     }
41410b57cec5SDimitry Andric   }
41420b57cec5SDimitry Andric }
41430b57cec5SDimitry Andric 
Dump(Stream * s) const41440b57cec5SDimitry Andric void Process::ProcessEventData::Dump(Stream *s) const {
41450b57cec5SDimitry Andric   ProcessSP process_sp(m_process_wp.lock());
41460b57cec5SDimitry Andric 
41470b57cec5SDimitry Andric   if (process_sp)
41480b57cec5SDimitry Andric     s->Printf(" process = %p (pid = %" PRIu64 "), ",
41490b57cec5SDimitry Andric               static_cast<void *>(process_sp.get()), process_sp->GetID());
41500b57cec5SDimitry Andric   else
41510b57cec5SDimitry Andric     s->PutCString(" process = NULL, ");
41520b57cec5SDimitry Andric 
41530b57cec5SDimitry Andric   s->Printf("state = %s", StateAsCString(GetState()));
41540b57cec5SDimitry Andric }
41550b57cec5SDimitry Andric 
41560b57cec5SDimitry Andric const Process::ProcessEventData *
GetEventDataFromEvent(const Event * event_ptr)41570b57cec5SDimitry Andric Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
41580b57cec5SDimitry Andric   if (event_ptr) {
41590b57cec5SDimitry Andric     const EventData *event_data = event_ptr->GetData();
41600b57cec5SDimitry Andric     if (event_data &&
41610b57cec5SDimitry Andric         event_data->GetFlavor() == ProcessEventData::GetFlavorString())
41620b57cec5SDimitry Andric       return static_cast<const ProcessEventData *>(event_ptr->GetData());
41630b57cec5SDimitry Andric   }
41640b57cec5SDimitry Andric   return nullptr;
41650b57cec5SDimitry Andric }
41660b57cec5SDimitry Andric 
41670b57cec5SDimitry Andric ProcessSP
GetProcessFromEvent(const Event * event_ptr)41680b57cec5SDimitry Andric Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
41690b57cec5SDimitry Andric   ProcessSP process_sp;
41700b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
41710b57cec5SDimitry Andric   if (data)
41720b57cec5SDimitry Andric     process_sp = data->GetProcessSP();
41730b57cec5SDimitry Andric   return process_sp;
41740b57cec5SDimitry Andric }
41750b57cec5SDimitry Andric 
GetStateFromEvent(const Event * event_ptr)41760b57cec5SDimitry Andric StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
41770b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
41780b57cec5SDimitry Andric   if (data == nullptr)
41790b57cec5SDimitry Andric     return eStateInvalid;
41800b57cec5SDimitry Andric   else
41810b57cec5SDimitry Andric     return data->GetState();
41820b57cec5SDimitry Andric }
41830b57cec5SDimitry Andric 
GetRestartedFromEvent(const Event * event_ptr)41840b57cec5SDimitry Andric bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
41850b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
41860b57cec5SDimitry Andric   if (data == nullptr)
41870b57cec5SDimitry Andric     return false;
41880b57cec5SDimitry Andric   else
41890b57cec5SDimitry Andric     return data->GetRestarted();
41900b57cec5SDimitry Andric }
41910b57cec5SDimitry Andric 
SetRestartedInEvent(Event * event_ptr,bool new_value)41920b57cec5SDimitry Andric void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
41930b57cec5SDimitry Andric                                                     bool new_value) {
41940b57cec5SDimitry Andric   ProcessEventData *data =
41950b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
41960b57cec5SDimitry Andric   if (data != nullptr)
41970b57cec5SDimitry Andric     data->SetRestarted(new_value);
41980b57cec5SDimitry Andric }
41990b57cec5SDimitry Andric 
42000b57cec5SDimitry Andric size_t
GetNumRestartedReasons(const Event * event_ptr)42010b57cec5SDimitry Andric Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
42020b57cec5SDimitry Andric   ProcessEventData *data =
42030b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
42040b57cec5SDimitry Andric   if (data != nullptr)
42050b57cec5SDimitry Andric     return data->GetNumRestartedReasons();
42060b57cec5SDimitry Andric   else
42070b57cec5SDimitry Andric     return 0;
42080b57cec5SDimitry Andric }
42090b57cec5SDimitry Andric 
42100b57cec5SDimitry Andric const char *
GetRestartedReasonAtIndex(const Event * event_ptr,size_t idx)42110b57cec5SDimitry Andric Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
42120b57cec5SDimitry Andric                                                      size_t idx) {
42130b57cec5SDimitry Andric   ProcessEventData *data =
42140b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
42150b57cec5SDimitry Andric   if (data != nullptr)
42160b57cec5SDimitry Andric     return data->GetRestartedReasonAtIndex(idx);
42170b57cec5SDimitry Andric   else
42180b57cec5SDimitry Andric     return nullptr;
42190b57cec5SDimitry Andric }
42200b57cec5SDimitry Andric 
AddRestartedReason(Event * event_ptr,const char * reason)42210b57cec5SDimitry Andric void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
42220b57cec5SDimitry Andric                                                    const char *reason) {
42230b57cec5SDimitry Andric   ProcessEventData *data =
42240b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
42250b57cec5SDimitry Andric   if (data != nullptr)
42260b57cec5SDimitry Andric     data->AddRestartedReason(reason);
42270b57cec5SDimitry Andric }
42280b57cec5SDimitry Andric 
GetInterruptedFromEvent(const Event * event_ptr)42290b57cec5SDimitry Andric bool Process::ProcessEventData::GetInterruptedFromEvent(
42300b57cec5SDimitry Andric     const Event *event_ptr) {
42310b57cec5SDimitry Andric   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
42320b57cec5SDimitry Andric   if (data == nullptr)
42330b57cec5SDimitry Andric     return false;
42340b57cec5SDimitry Andric   else
42350b57cec5SDimitry Andric     return data->GetInterrupted();
42360b57cec5SDimitry Andric }
42370b57cec5SDimitry Andric 
SetInterruptedInEvent(Event * event_ptr,bool new_value)42380b57cec5SDimitry Andric void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
42390b57cec5SDimitry Andric                                                       bool new_value) {
42400b57cec5SDimitry Andric   ProcessEventData *data =
42410b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
42420b57cec5SDimitry Andric   if (data != nullptr)
42430b57cec5SDimitry Andric     data->SetInterrupted(new_value);
42440b57cec5SDimitry Andric }
42450b57cec5SDimitry Andric 
SetUpdateStateOnRemoval(Event * event_ptr)42460b57cec5SDimitry Andric bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
42470b57cec5SDimitry Andric   ProcessEventData *data =
42480b57cec5SDimitry Andric       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
42490b57cec5SDimitry Andric   if (data) {
42500b57cec5SDimitry Andric     data->SetUpdateStateOnRemoval();
42510b57cec5SDimitry Andric     return true;
42520b57cec5SDimitry Andric   }
42530b57cec5SDimitry Andric   return false;
42540b57cec5SDimitry Andric }
42550b57cec5SDimitry Andric 
CalculateTarget()42560b57cec5SDimitry Andric lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
42570b57cec5SDimitry Andric 
CalculateExecutionContext(ExecutionContext & exe_ctx)42580b57cec5SDimitry Andric void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
42590b57cec5SDimitry Andric   exe_ctx.SetTargetPtr(&GetTarget());
42600b57cec5SDimitry Andric   exe_ctx.SetProcessPtr(this);
42610b57cec5SDimitry Andric   exe_ctx.SetThreadPtr(nullptr);
42620b57cec5SDimitry Andric   exe_ctx.SetFramePtr(nullptr);
42630b57cec5SDimitry Andric }
42640b57cec5SDimitry Andric 
42650b57cec5SDimitry Andric // uint32_t
42660b57cec5SDimitry Andric // Process::ListProcessesMatchingName (const char *name, StringList &matches,
42670b57cec5SDimitry Andric // std::vector<lldb::pid_t> &pids)
42680b57cec5SDimitry Andric //{
42690b57cec5SDimitry Andric //    return 0;
42700b57cec5SDimitry Andric //}
42710b57cec5SDimitry Andric //
42720b57cec5SDimitry Andric // ArchSpec
42730b57cec5SDimitry Andric // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
42740b57cec5SDimitry Andric //{
42750b57cec5SDimitry Andric //    return Host::GetArchSpecForExistingProcess (pid);
42760b57cec5SDimitry Andric //}
42770b57cec5SDimitry Andric //
42780b57cec5SDimitry Andric // ArchSpec
42790b57cec5SDimitry Andric // Process::GetArchSpecForExistingProcess (const char *process_name)
42800b57cec5SDimitry Andric //{
42810b57cec5SDimitry Andric //    return Host::GetArchSpecForExistingProcess (process_name);
42820b57cec5SDimitry Andric //}
42830b57cec5SDimitry Andric 
AppendSTDOUT(const char * s,size_t len)42840b57cec5SDimitry Andric void Process::AppendSTDOUT(const char *s, size_t len) {
42850b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
42860b57cec5SDimitry Andric   m_stdout_data.append(s, len);
42870b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitSTDOUT,
42880b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
42890b57cec5SDimitry Andric }
42900b57cec5SDimitry Andric 
AppendSTDERR(const char * s,size_t len)42910b57cec5SDimitry Andric void Process::AppendSTDERR(const char *s, size_t len) {
42920b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
42930b57cec5SDimitry Andric   m_stderr_data.append(s, len);
42940b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitSTDERR,
42950b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
42960b57cec5SDimitry Andric }
42970b57cec5SDimitry Andric 
BroadcastAsyncProfileData(const std::string & one_profile_data)42980b57cec5SDimitry Andric void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
42990b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
43000b57cec5SDimitry Andric   m_profile_data.push_back(one_profile_data);
43010b57cec5SDimitry Andric   BroadcastEventIfUnique(eBroadcastBitProfileData,
43020b57cec5SDimitry Andric                          new ProcessEventData(shared_from_this(), GetState()));
43030b57cec5SDimitry Andric }
43040b57cec5SDimitry Andric 
BroadcastStructuredData(const StructuredData::ObjectSP & object_sp,const StructuredDataPluginSP & plugin_sp)43050b57cec5SDimitry Andric void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
43060b57cec5SDimitry Andric                                       const StructuredDataPluginSP &plugin_sp) {
4307*a58f00eaSDimitry Andric   auto data_sp = std::make_shared<EventDataStructuredData>(
4308*a58f00eaSDimitry Andric       shared_from_this(), object_sp, plugin_sp);
4309*a58f00eaSDimitry Andric   BroadcastEvent(eBroadcastBitStructuredData, data_sp);
43100b57cec5SDimitry Andric }
43110b57cec5SDimitry Andric 
43120b57cec5SDimitry Andric StructuredDataPluginSP
GetStructuredDataPlugin(llvm::StringRef type_name) const4313fe013be4SDimitry Andric Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
43140b57cec5SDimitry Andric   auto find_it = m_structured_data_plugin_map.find(type_name);
43150b57cec5SDimitry Andric   if (find_it != m_structured_data_plugin_map.end())
43160b57cec5SDimitry Andric     return find_it->second;
43170b57cec5SDimitry Andric   else
43180b57cec5SDimitry Andric     return StructuredDataPluginSP();
43190b57cec5SDimitry Andric }
43200b57cec5SDimitry Andric 
GetAsyncProfileData(char * buf,size_t buf_size,Status & error)43210b57cec5SDimitry Andric size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
43220b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
43230b57cec5SDimitry Andric   if (m_profile_data.empty())
43240b57cec5SDimitry Andric     return 0;
43250b57cec5SDimitry Andric 
43260b57cec5SDimitry Andric   std::string &one_profile_data = m_profile_data.front();
43270b57cec5SDimitry Andric   size_t bytes_available = one_profile_data.size();
43280b57cec5SDimitry Andric   if (bytes_available > 0) {
432981ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
43309dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
43310b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
43320b57cec5SDimitry Andric     if (bytes_available > buf_size) {
43330b57cec5SDimitry Andric       memcpy(buf, one_profile_data.c_str(), buf_size);
43340b57cec5SDimitry Andric       one_profile_data.erase(0, buf_size);
43350b57cec5SDimitry Andric       bytes_available = buf_size;
43360b57cec5SDimitry Andric     } else {
43370b57cec5SDimitry Andric       memcpy(buf, one_profile_data.c_str(), bytes_available);
43380b57cec5SDimitry Andric       m_profile_data.erase(m_profile_data.begin());
43390b57cec5SDimitry Andric     }
43400b57cec5SDimitry Andric   }
43410b57cec5SDimitry Andric   return bytes_available;
43420b57cec5SDimitry Andric }
43430b57cec5SDimitry Andric 
43440b57cec5SDimitry Andric // Process STDIO
43450b57cec5SDimitry Andric 
GetSTDOUT(char * buf,size_t buf_size,Status & error)43460b57cec5SDimitry Andric size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
43470b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
43480b57cec5SDimitry Andric   size_t bytes_available = m_stdout_data.size();
43490b57cec5SDimitry Andric   if (bytes_available > 0) {
435081ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
43519dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
43520b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
43530b57cec5SDimitry Andric     if (bytes_available > buf_size) {
43540b57cec5SDimitry Andric       memcpy(buf, m_stdout_data.c_str(), buf_size);
43550b57cec5SDimitry Andric       m_stdout_data.erase(0, buf_size);
43560b57cec5SDimitry Andric       bytes_available = buf_size;
43570b57cec5SDimitry Andric     } else {
43580b57cec5SDimitry Andric       memcpy(buf, m_stdout_data.c_str(), bytes_available);
43590b57cec5SDimitry Andric       m_stdout_data.clear();
43600b57cec5SDimitry Andric     }
43610b57cec5SDimitry Andric   }
43620b57cec5SDimitry Andric   return bytes_available;
43630b57cec5SDimitry Andric }
43640b57cec5SDimitry Andric 
GetSTDERR(char * buf,size_t buf_size,Status & error)43650b57cec5SDimitry Andric size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
43660b57cec5SDimitry Andric   std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
43670b57cec5SDimitry Andric   size_t bytes_available = m_stderr_data.size();
43680b57cec5SDimitry Andric   if (bytes_available > 0) {
436981ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
43709dba64beSDimitry Andric     LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
43710b57cec5SDimitry Andric               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
43720b57cec5SDimitry Andric     if (bytes_available > buf_size) {
43730b57cec5SDimitry Andric       memcpy(buf, m_stderr_data.c_str(), buf_size);
43740b57cec5SDimitry Andric       m_stderr_data.erase(0, buf_size);
43750b57cec5SDimitry Andric       bytes_available = buf_size;
43760b57cec5SDimitry Andric     } else {
43770b57cec5SDimitry Andric       memcpy(buf, m_stderr_data.c_str(), bytes_available);
43780b57cec5SDimitry Andric       m_stderr_data.clear();
43790b57cec5SDimitry Andric     }
43800b57cec5SDimitry Andric   }
43810b57cec5SDimitry Andric   return bytes_available;
43820b57cec5SDimitry Andric }
43830b57cec5SDimitry Andric 
STDIOReadThreadBytesReceived(void * baton,const void * src,size_t src_len)43840b57cec5SDimitry Andric void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
43850b57cec5SDimitry Andric                                            size_t src_len) {
43860b57cec5SDimitry Andric   Process *process = (Process *)baton;
43870b57cec5SDimitry Andric   process->AppendSTDOUT(static_cast<const char *>(src), src_len);
43880b57cec5SDimitry Andric }
43890b57cec5SDimitry Andric 
43900b57cec5SDimitry Andric class IOHandlerProcessSTDIO : public IOHandler {
43910b57cec5SDimitry Andric public:
IOHandlerProcessSTDIO(Process * process,int write_fd)43920b57cec5SDimitry Andric   IOHandlerProcessSTDIO(Process *process, int write_fd)
43930b57cec5SDimitry Andric       : IOHandler(process->GetTarget().GetDebugger(),
43940b57cec5SDimitry Andric                   IOHandler::Type::ProcessIO),
43959dba64beSDimitry Andric         m_process(process),
4396349cc55cSDimitry Andric         m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
4397349cc55cSDimitry Andric         m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {
43980b57cec5SDimitry Andric     m_pipe.CreateNew(false);
43990b57cec5SDimitry Andric   }
44000b57cec5SDimitry Andric 
44010b57cec5SDimitry Andric   ~IOHandlerProcessSTDIO() override = default;
44020b57cec5SDimitry Andric 
SetIsRunning(bool running)440381ad6265SDimitry Andric   void SetIsRunning(bool running) {
440481ad6265SDimitry Andric     std::lock_guard<std::mutex> guard(m_mutex);
440581ad6265SDimitry Andric     SetIsDone(!running);
440681ad6265SDimitry Andric     m_is_running = running;
440781ad6265SDimitry Andric   }
440881ad6265SDimitry Andric 
44090b57cec5SDimitry Andric   // Each IOHandler gets to run until it is done. It should read data from the
44100b57cec5SDimitry Andric   // "in" and place output into "out" and "err and return when done.
Run()44110b57cec5SDimitry Andric   void Run() override {
44120b57cec5SDimitry Andric     if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
44130b57cec5SDimitry Andric         !m_pipe.CanRead() || !m_pipe.CanWrite()) {
44140b57cec5SDimitry Andric       SetIsDone(true);
44150b57cec5SDimitry Andric       return;
44160b57cec5SDimitry Andric     }
44170b57cec5SDimitry Andric 
44180b57cec5SDimitry Andric     SetIsDone(false);
44190b57cec5SDimitry Andric     const int read_fd = m_read_file.GetDescriptor();
44200b57cec5SDimitry Andric     Terminal terminal(read_fd);
4421349cc55cSDimitry Andric     TerminalState terminal_state(terminal, false);
4422349cc55cSDimitry Andric     // FIXME: error handling?
4423349cc55cSDimitry Andric     llvm::consumeError(terminal.SetCanonical(false));
4424349cc55cSDimitry Andric     llvm::consumeError(terminal.SetEcho(false));
44250b57cec5SDimitry Andric // FD_ZERO, FD_SET are not supported on windows
44260b57cec5SDimitry Andric #ifndef _WIN32
44270b57cec5SDimitry Andric     const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
442881ad6265SDimitry Andric     SetIsRunning(true);
442981ad6265SDimitry Andric     while (true) {
443081ad6265SDimitry Andric       {
443181ad6265SDimitry Andric         std::lock_guard<std::mutex> guard(m_mutex);
443281ad6265SDimitry Andric         if (GetIsDone())
443381ad6265SDimitry Andric           break;
443481ad6265SDimitry Andric       }
443581ad6265SDimitry Andric 
44360b57cec5SDimitry Andric       SelectHelper select_helper;
44370b57cec5SDimitry Andric       select_helper.FDSetRead(read_fd);
44380b57cec5SDimitry Andric       select_helper.FDSetRead(pipe_read_fd);
44390b57cec5SDimitry Andric       Status error = select_helper.Select();
44400b57cec5SDimitry Andric 
444181ad6265SDimitry Andric       if (error.Fail())
444281ad6265SDimitry Andric         break;
444381ad6265SDimitry Andric 
44440b57cec5SDimitry Andric       char ch = 0;
44450b57cec5SDimitry Andric       size_t n;
44460b57cec5SDimitry Andric       if (select_helper.FDIsSetRead(read_fd)) {
44470b57cec5SDimitry Andric         n = 1;
44480b57cec5SDimitry Andric         if (m_read_file.Read(&ch, n).Success() && n == 1) {
44490b57cec5SDimitry Andric           if (m_write_file.Write(&ch, n).Fail() || n != 1)
445081ad6265SDimitry Andric             break;
44510b57cec5SDimitry Andric         } else
445281ad6265SDimitry Andric           break;
44530b57cec5SDimitry Andric       }
445481ad6265SDimitry Andric 
44550b57cec5SDimitry Andric       if (select_helper.FDIsSetRead(pipe_read_fd)) {
44560b57cec5SDimitry Andric         size_t bytes_read;
44570b57cec5SDimitry Andric         // Consume the interrupt byte
44580b57cec5SDimitry Andric         Status error = m_pipe.Read(&ch, 1, bytes_read);
44590b57cec5SDimitry Andric         if (error.Success()) {
446081ad6265SDimitry Andric           if (ch == 'q')
44610b57cec5SDimitry Andric             break;
446281ad6265SDimitry Andric           if (ch == 'i')
44630b57cec5SDimitry Andric             if (StateIsRunningState(m_process->GetState()))
44640b57cec5SDimitry Andric               m_process->SendAsyncInterrupt();
44650b57cec5SDimitry Andric         }
44660b57cec5SDimitry Andric       }
44670b57cec5SDimitry Andric     }
446881ad6265SDimitry Andric     SetIsRunning(false);
44690b57cec5SDimitry Andric #endif
44700b57cec5SDimitry Andric   }
44710b57cec5SDimitry Andric 
Cancel()44720b57cec5SDimitry Andric   void Cancel() override {
447381ad6265SDimitry Andric     std::lock_guard<std::mutex> guard(m_mutex);
44740b57cec5SDimitry Andric     SetIsDone(true);
44750b57cec5SDimitry Andric     // Only write to our pipe to cancel if we are in
44760b57cec5SDimitry Andric     // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
44770b57cec5SDimitry Andric     // is being run from the command interpreter:
44780b57cec5SDimitry Andric     //
44790b57cec5SDimitry Andric     // (lldb) step_process_thousands_of_times
44800b57cec5SDimitry Andric     //
44810b57cec5SDimitry Andric     // In this case the command interpreter will be in the middle of handling
44820b57cec5SDimitry Andric     // the command and if the process pushes and pops the IOHandler thousands
44830b57cec5SDimitry Andric     // of times, we can end up writing to m_pipe without ever consuming the
44840b57cec5SDimitry Andric     // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
44850b57cec5SDimitry Andric     // deadlocking when the pipe gets fed up and blocks until data is consumed.
44860b57cec5SDimitry Andric     if (m_is_running) {
44870b57cec5SDimitry Andric       char ch = 'q'; // Send 'q' for quit
44880b57cec5SDimitry Andric       size_t bytes_written = 0;
44890b57cec5SDimitry Andric       m_pipe.Write(&ch, 1, bytes_written);
44900b57cec5SDimitry Andric     }
44910b57cec5SDimitry Andric   }
44920b57cec5SDimitry Andric 
Interrupt()44930b57cec5SDimitry Andric   bool Interrupt() override {
44940b57cec5SDimitry Andric     // Do only things that are safe to do in an interrupt context (like in a
44950b57cec5SDimitry Andric     // SIGINT handler), like write 1 byte to a file descriptor. This will
44960b57cec5SDimitry Andric     // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
44970b57cec5SDimitry Andric     // that was written to the pipe and then call
44980b57cec5SDimitry Andric     // m_process->SendAsyncInterrupt() from a much safer location in code.
44990b57cec5SDimitry Andric     if (m_active) {
45000b57cec5SDimitry Andric       char ch = 'i'; // Send 'i' for interrupt
45010b57cec5SDimitry Andric       size_t bytes_written = 0;
45020b57cec5SDimitry Andric       Status result = m_pipe.Write(&ch, 1, bytes_written);
45030b57cec5SDimitry Andric       return result.Success();
45040b57cec5SDimitry Andric     } else {
45050b57cec5SDimitry Andric       // This IOHandler might be pushed on the stack, but not being run
45060b57cec5SDimitry Andric       // currently so do the right thing if we aren't actively watching for
45070b57cec5SDimitry Andric       // STDIN by sending the interrupt to the process. Otherwise the write to
45080b57cec5SDimitry Andric       // the pipe above would do nothing. This can happen when the command
45090b57cec5SDimitry Andric       // interpreter is running and gets a "expression ...". It will be on the
45100b57cec5SDimitry Andric       // IOHandler thread and sending the input is complete to the delegate
45110b57cec5SDimitry Andric       // which will cause the expression to run, which will push the process IO
45120b57cec5SDimitry Andric       // handler, but not run it.
45130b57cec5SDimitry Andric 
45140b57cec5SDimitry Andric       if (StateIsRunningState(m_process->GetState())) {
45150b57cec5SDimitry Andric         m_process->SendAsyncInterrupt();
45160b57cec5SDimitry Andric         return true;
45170b57cec5SDimitry Andric       }
45180b57cec5SDimitry Andric     }
45190b57cec5SDimitry Andric     return false;
45200b57cec5SDimitry Andric   }
45210b57cec5SDimitry Andric 
GotEOF()45220b57cec5SDimitry Andric   void GotEOF() override {}
45230b57cec5SDimitry Andric 
45240b57cec5SDimitry Andric protected:
45250b57cec5SDimitry Andric   Process *m_process;
45269dba64beSDimitry Andric   NativeFile m_read_file;  // Read from this file (usually actual STDIN for LLDB
4527349cc55cSDimitry Andric   NativeFile m_write_file; // Write to this file (usually the primary pty for
45289dba64beSDimitry Andric                            // getting io to debuggee)
45290b57cec5SDimitry Andric   Pipe m_pipe;
453081ad6265SDimitry Andric   std::mutex m_mutex;
453181ad6265SDimitry Andric   bool m_is_running = false;
45320b57cec5SDimitry Andric };
45330b57cec5SDimitry Andric 
SetSTDIOFileDescriptor(int fd)45340b57cec5SDimitry Andric void Process::SetSTDIOFileDescriptor(int fd) {
45350b57cec5SDimitry Andric   // First set up the Read Thread for reading/handling process I/O
45365ffd83dbSDimitry Andric   m_stdio_communication.SetConnection(
45375ffd83dbSDimitry Andric       std::make_unique<ConnectionFileDescriptor>(fd, true));
45380b57cec5SDimitry Andric   if (m_stdio_communication.IsConnected()) {
45390b57cec5SDimitry Andric     m_stdio_communication.SetReadThreadBytesReceivedCallback(
45400b57cec5SDimitry Andric         STDIOReadThreadBytesReceived, this);
45410b57cec5SDimitry Andric     m_stdio_communication.StartReadThread();
45420b57cec5SDimitry Andric 
45430b57cec5SDimitry Andric     // Now read thread is set up, set up input reader.
4544c9157d92SDimitry Andric     {
4545c9157d92SDimitry Andric       std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
45460b57cec5SDimitry Andric       if (!m_process_input_reader)
45470b57cec5SDimitry Andric         m_process_input_reader =
45480b57cec5SDimitry Andric             std::make_shared<IOHandlerProcessSTDIO>(this, fd);
45490b57cec5SDimitry Andric     }
45500b57cec5SDimitry Andric   }
4551c9157d92SDimitry Andric }
45520b57cec5SDimitry Andric 
ProcessIOHandlerIsActive()45530b57cec5SDimitry Andric bool Process::ProcessIOHandlerIsActive() {
4554c9157d92SDimitry Andric   std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
45550b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
45560b57cec5SDimitry Andric   if (io_handler_sp)
45570b57cec5SDimitry Andric     return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
45580b57cec5SDimitry Andric   return false;
45590b57cec5SDimitry Andric }
4560c9157d92SDimitry Andric 
PushProcessIOHandler()45610b57cec5SDimitry Andric bool Process::PushProcessIOHandler() {
4562c9157d92SDimitry Andric   std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
45630b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
45640b57cec5SDimitry Andric   if (io_handler_sp) {
456581ad6265SDimitry Andric     Log *log = GetLog(LLDBLog::Process);
45669dba64beSDimitry Andric     LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
45670b57cec5SDimitry Andric 
45680b57cec5SDimitry Andric     io_handler_sp->SetIsDone(false);
45690b57cec5SDimitry Andric     // If we evaluate an utility function, then we don't cancel the current
45700b57cec5SDimitry Andric     // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
45710b57cec5SDimitry Andric     // existing IOHandler that potentially provides the user interface (e.g.
45720b57cec5SDimitry Andric     // the IOHandler for Editline).
45730b57cec5SDimitry Andric     bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
45745ffd83dbSDimitry Andric     GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
45755ffd83dbSDimitry Andric                                                 cancel_top_handler);
45760b57cec5SDimitry Andric     return true;
45770b57cec5SDimitry Andric   }
45780b57cec5SDimitry Andric   return false;
45790b57cec5SDimitry Andric }
45800b57cec5SDimitry Andric 
PopProcessIOHandler()45810b57cec5SDimitry Andric bool Process::PopProcessIOHandler() {
4582c9157d92SDimitry Andric   std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
45830b57cec5SDimitry Andric   IOHandlerSP io_handler_sp(m_process_input_reader);
45840b57cec5SDimitry Andric   if (io_handler_sp)
45855ffd83dbSDimitry Andric     return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
45860b57cec5SDimitry Andric   return false;
45870b57cec5SDimitry Andric }
45880b57cec5SDimitry Andric 
45890b57cec5SDimitry Andric // The process needs to know about installed plug-ins
SettingsInitialize()45900b57cec5SDimitry Andric void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
45910b57cec5SDimitry Andric 
SettingsTerminate()45920b57cec5SDimitry Andric void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
45930b57cec5SDimitry Andric 
45940b57cec5SDimitry Andric namespace {
4595349cc55cSDimitry Andric // RestorePlanState is used to record the "is private", "is controlling" and
4596349cc55cSDimitry Andric // "okay
45970b57cec5SDimitry Andric // to discard" fields of the plan we are running, and reset it on Clean or on
45980b57cec5SDimitry Andric // destruction. It will only reset the state once, so you can call Clean and
45990b57cec5SDimitry Andric // then monkey with the state and it won't get reset on you again.
46000b57cec5SDimitry Andric 
46010b57cec5SDimitry Andric class RestorePlanState {
46020b57cec5SDimitry Andric public:
RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)46030b57cec5SDimitry Andric   RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
460481ad6265SDimitry Andric       : m_thread_plan_sp(thread_plan_sp) {
46050b57cec5SDimitry Andric     if (m_thread_plan_sp) {
46060b57cec5SDimitry Andric       m_private = m_thread_plan_sp->GetPrivate();
4607349cc55cSDimitry Andric       m_is_controlling = m_thread_plan_sp->IsControllingPlan();
46080b57cec5SDimitry Andric       m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
46090b57cec5SDimitry Andric     }
46100b57cec5SDimitry Andric   }
46110b57cec5SDimitry Andric 
~RestorePlanState()46120b57cec5SDimitry Andric   ~RestorePlanState() { Clean(); }
46130b57cec5SDimitry Andric 
Clean()46140b57cec5SDimitry Andric   void Clean() {
46150b57cec5SDimitry Andric     if (!m_already_reset && m_thread_plan_sp) {
46160b57cec5SDimitry Andric       m_already_reset = true;
46170b57cec5SDimitry Andric       m_thread_plan_sp->SetPrivate(m_private);
4618349cc55cSDimitry Andric       m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
46190b57cec5SDimitry Andric       m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
46200b57cec5SDimitry Andric     }
46210b57cec5SDimitry Andric   }
46220b57cec5SDimitry Andric 
46230b57cec5SDimitry Andric private:
46240b57cec5SDimitry Andric   lldb::ThreadPlanSP m_thread_plan_sp;
462581ad6265SDimitry Andric   bool m_already_reset = false;
4626972a253aSDimitry Andric   bool m_private = false;
4627972a253aSDimitry Andric   bool m_is_controlling = false;
4628972a253aSDimitry Andric   bool m_okay_to_discard = false;
46290b57cec5SDimitry Andric };
46300b57cec5SDimitry Andric } // anonymous namespace
46310b57cec5SDimitry Andric 
46320b57cec5SDimitry Andric static microseconds
GetOneThreadExpressionTimeout(const EvaluateExpressionOptions & options)46330b57cec5SDimitry Andric GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
46340b57cec5SDimitry Andric   const milliseconds default_one_thread_timeout(250);
46350b57cec5SDimitry Andric 
46360b57cec5SDimitry Andric   // If the overall wait is forever, then we don't need to worry about it.
46370b57cec5SDimitry Andric   if (!options.GetTimeout()) {
46380b57cec5SDimitry Andric     return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
46390b57cec5SDimitry Andric                                          : default_one_thread_timeout;
46400b57cec5SDimitry Andric   }
46410b57cec5SDimitry Andric 
46420b57cec5SDimitry Andric   // If the one thread timeout is set, use it.
46430b57cec5SDimitry Andric   if (options.GetOneThreadTimeout())
46440b57cec5SDimitry Andric     return *options.GetOneThreadTimeout();
46450b57cec5SDimitry Andric 
46460b57cec5SDimitry Andric   // Otherwise use half the total timeout, bounded by the
46470b57cec5SDimitry Andric   // default_one_thread_timeout.
46480b57cec5SDimitry Andric   return std::min<microseconds>(default_one_thread_timeout,
46490b57cec5SDimitry Andric                                 *options.GetTimeout() / 2);
46500b57cec5SDimitry Andric }
46510b57cec5SDimitry Andric 
46520b57cec5SDimitry Andric static Timeout<std::micro>
GetExpressionTimeout(const EvaluateExpressionOptions & options,bool before_first_timeout)46530b57cec5SDimitry Andric GetExpressionTimeout(const EvaluateExpressionOptions &options,
46540b57cec5SDimitry Andric                      bool before_first_timeout) {
46550b57cec5SDimitry Andric   // If we are going to run all threads the whole time, or if we are only going
46560b57cec5SDimitry Andric   // to run one thread, we can just return the overall timeout.
46570b57cec5SDimitry Andric   if (!options.GetStopOthers() || !options.GetTryAllThreads())
46580b57cec5SDimitry Andric     return options.GetTimeout();
46590b57cec5SDimitry Andric 
46600b57cec5SDimitry Andric   if (before_first_timeout)
46610b57cec5SDimitry Andric     return GetOneThreadExpressionTimeout(options);
46620b57cec5SDimitry Andric 
46630b57cec5SDimitry Andric   if (!options.GetTimeout())
4664bdd1243dSDimitry Andric     return std::nullopt;
46650b57cec5SDimitry Andric   else
46660b57cec5SDimitry Andric     return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
46670b57cec5SDimitry Andric }
46680b57cec5SDimitry Andric 
4669bdd1243dSDimitry Andric static std::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)46705ffd83dbSDimitry Andric HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
46710b57cec5SDimitry Andric                    RestorePlanState &restorer, const EventSP &event_sp,
46720b57cec5SDimitry Andric                    EventSP &event_to_broadcast_sp,
46735ffd83dbSDimitry Andric                    const EvaluateExpressionOptions &options,
46745ffd83dbSDimitry Andric                    bool handle_interrupts) {
467581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Step | LLDBLog::Process);
46760b57cec5SDimitry Andric 
46775ffd83dbSDimitry Andric   ThreadSP thread_sp = thread_plan_sp->GetTarget()
46785ffd83dbSDimitry Andric                            .GetProcessSP()
46795ffd83dbSDimitry Andric                            ->GetThreadList()
46805ffd83dbSDimitry Andric                            .FindThreadByID(thread_id);
46815ffd83dbSDimitry Andric   if (!thread_sp) {
46825ffd83dbSDimitry Andric     LLDB_LOG(log,
46835ffd83dbSDimitry Andric              "The thread on which we were running the "
46845ffd83dbSDimitry Andric              "expression: tid = {0}, exited while "
46855ffd83dbSDimitry Andric              "the expression was running.",
46865ffd83dbSDimitry Andric              thread_id);
46875ffd83dbSDimitry Andric     return eExpressionThreadVanished;
46885ffd83dbSDimitry Andric   }
46895ffd83dbSDimitry Andric 
46905ffd83dbSDimitry Andric   ThreadPlanSP plan = thread_sp->GetCompletedPlan();
46910b57cec5SDimitry Andric   if (plan == thread_plan_sp && plan->PlanSucceeded()) {
46920b57cec5SDimitry Andric     LLDB_LOG(log, "execution completed successfully");
46930b57cec5SDimitry Andric 
46940b57cec5SDimitry Andric     // Restore the plan state so it will get reported as intended when we are
46950b57cec5SDimitry Andric     // done.
46960b57cec5SDimitry Andric     restorer.Clean();
46970b57cec5SDimitry Andric     return eExpressionCompleted;
46980b57cec5SDimitry Andric   }
46990b57cec5SDimitry Andric 
47005ffd83dbSDimitry Andric   StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
47010b57cec5SDimitry Andric   if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
47020b57cec5SDimitry Andric       stop_info_sp->ShouldNotify(event_sp.get())) {
47030b57cec5SDimitry Andric     LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
47040b57cec5SDimitry Andric     if (!options.DoesIgnoreBreakpoints()) {
47050b57cec5SDimitry Andric       // Restore the plan state and then force Private to false.  We are going
47060b57cec5SDimitry Andric       // to stop because of this plan so we need it to become a public plan or
47070b57cec5SDimitry Andric       // it won't report correctly when we continue to its termination later
47080b57cec5SDimitry Andric       // on.
47090b57cec5SDimitry Andric       restorer.Clean();
47100b57cec5SDimitry Andric       thread_plan_sp->SetPrivate(false);
47110b57cec5SDimitry Andric       event_to_broadcast_sp = event_sp;
47120b57cec5SDimitry Andric     }
47130b57cec5SDimitry Andric     return eExpressionHitBreakpoint;
47140b57cec5SDimitry Andric   }
47150b57cec5SDimitry Andric 
47160b57cec5SDimitry Andric   if (!handle_interrupts &&
47170b57cec5SDimitry Andric       Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4718bdd1243dSDimitry Andric     return std::nullopt;
47190b57cec5SDimitry Andric 
47200b57cec5SDimitry Andric   LLDB_LOG(log, "thread plan did not successfully complete");
47210b57cec5SDimitry Andric   if (!options.DoesUnwindOnError())
47220b57cec5SDimitry Andric     event_to_broadcast_sp = event_sp;
47230b57cec5SDimitry Andric   return eExpressionInterrupted;
47240b57cec5SDimitry Andric }
47250b57cec5SDimitry Andric 
47260b57cec5SDimitry Andric ExpressionResults
RunThreadPlan(ExecutionContext & exe_ctx,lldb::ThreadPlanSP & thread_plan_sp,const EvaluateExpressionOptions & options,DiagnosticManager & diagnostic_manager)47270b57cec5SDimitry Andric Process::RunThreadPlan(ExecutionContext &exe_ctx,
47280b57cec5SDimitry Andric                        lldb::ThreadPlanSP &thread_plan_sp,
47290b57cec5SDimitry Andric                        const EvaluateExpressionOptions &options,
47300b57cec5SDimitry Andric                        DiagnosticManager &diagnostic_manager) {
47310b57cec5SDimitry Andric   ExpressionResults return_value = eExpressionSetupError;
47320b57cec5SDimitry Andric 
47330b57cec5SDimitry Andric   std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
47340b57cec5SDimitry Andric 
47350b57cec5SDimitry Andric   if (!thread_plan_sp) {
47360b57cec5SDimitry Andric     diagnostic_manager.PutString(
47370b57cec5SDimitry Andric         eDiagnosticSeverityError,
47380b57cec5SDimitry Andric         "RunThreadPlan called with empty thread plan.");
47390b57cec5SDimitry Andric     return eExpressionSetupError;
47400b57cec5SDimitry Andric   }
47410b57cec5SDimitry Andric 
47420b57cec5SDimitry Andric   if (!thread_plan_sp->ValidatePlan(nullptr)) {
47430b57cec5SDimitry Andric     diagnostic_manager.PutString(
47440b57cec5SDimitry Andric         eDiagnosticSeverityError,
47450b57cec5SDimitry Andric         "RunThreadPlan called with an invalid thread plan.");
47460b57cec5SDimitry Andric     return eExpressionSetupError;
47470b57cec5SDimitry Andric   }
47480b57cec5SDimitry Andric 
47490b57cec5SDimitry Andric   if (exe_ctx.GetProcessPtr() != this) {
47500b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
47510b57cec5SDimitry Andric                                  "RunThreadPlan called on wrong process.");
47520b57cec5SDimitry Andric     return eExpressionSetupError;
47530b57cec5SDimitry Andric   }
47540b57cec5SDimitry Andric 
47550b57cec5SDimitry Andric   Thread *thread = exe_ctx.GetThreadPtr();
47560b57cec5SDimitry Andric   if (thread == nullptr) {
47570b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
47580b57cec5SDimitry Andric                                  "RunThreadPlan called with invalid thread.");
47590b57cec5SDimitry Andric     return eExpressionSetupError;
47600b57cec5SDimitry Andric   }
47610b57cec5SDimitry Andric 
47625ffd83dbSDimitry Andric   // Record the thread's id so we can tell when a thread we were using
47635ffd83dbSDimitry Andric   // to run the expression exits during the expression evaluation.
47645ffd83dbSDimitry Andric   lldb::tid_t expr_thread_id = thread->GetID();
47655ffd83dbSDimitry Andric 
47660b57cec5SDimitry Andric   // We need to change some of the thread plan attributes for the thread plan
47670b57cec5SDimitry Andric   // runner.  This will restore them when we are done:
47680b57cec5SDimitry Andric 
47690b57cec5SDimitry Andric   RestorePlanState thread_plan_restorer(thread_plan_sp);
47700b57cec5SDimitry Andric 
47710b57cec5SDimitry Andric   // We rely on the thread plan we are running returning "PlanCompleted" if
47720b57cec5SDimitry Andric   // when it successfully completes. For that to be true the plan can't be
47730b57cec5SDimitry Andric   // private - since private plans suppress themselves in the GetCompletedPlan
47740b57cec5SDimitry Andric   // call.
47750b57cec5SDimitry Andric 
47760b57cec5SDimitry Andric   thread_plan_sp->SetPrivate(false);
47770b57cec5SDimitry Andric 
4778349cc55cSDimitry Andric   // The plans run with RunThreadPlan also need to be terminal controlling plans
4779349cc55cSDimitry Andric   // or when they are done we will end up asking the plan above us whether we
47800b57cec5SDimitry Andric   // should stop, which may give the wrong answer.
47810b57cec5SDimitry Andric 
4782349cc55cSDimitry Andric   thread_plan_sp->SetIsControllingPlan(true);
47830b57cec5SDimitry Andric   thread_plan_sp->SetOkayToDiscard(false);
47840b57cec5SDimitry Andric 
47850b57cec5SDimitry Andric   // If we are running some utility expression for LLDB, we now have to mark
47860b57cec5SDimitry Andric   // this in the ProcesModID of this process. This RAII takes care of marking
47870b57cec5SDimitry Andric   // and reverting the mark it once we are done running the expression.
47880b57cec5SDimitry Andric   UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
47890b57cec5SDimitry Andric 
47900b57cec5SDimitry Andric   if (m_private_state.GetValue() != eStateStopped) {
47910b57cec5SDimitry Andric     diagnostic_manager.PutString(
47920b57cec5SDimitry Andric         eDiagnosticSeverityError,
47930b57cec5SDimitry Andric         "RunThreadPlan called while the private state was not stopped.");
47940b57cec5SDimitry Andric     return eExpressionSetupError;
47950b57cec5SDimitry Andric   }
47960b57cec5SDimitry Andric 
47970b57cec5SDimitry Andric   // Save the thread & frame from the exe_ctx for restoration after we run
47980b57cec5SDimitry Andric   const uint32_t thread_idx_id = thread->GetIndexID();
4799fe013be4SDimitry Andric   StackFrameSP selected_frame_sp =
4800fe013be4SDimitry Andric       thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
48010b57cec5SDimitry Andric   if (!selected_frame_sp) {
48020b57cec5SDimitry Andric     thread->SetSelectedFrame(nullptr);
4803fe013be4SDimitry Andric     selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
48040b57cec5SDimitry Andric     if (!selected_frame_sp) {
48050b57cec5SDimitry Andric       diagnostic_manager.Printf(
48060b57cec5SDimitry Andric           eDiagnosticSeverityError,
48070b57cec5SDimitry Andric           "RunThreadPlan called without a selected frame on thread %d",
48080b57cec5SDimitry Andric           thread_idx_id);
48090b57cec5SDimitry Andric       return eExpressionSetupError;
48100b57cec5SDimitry Andric     }
48110b57cec5SDimitry Andric   }
48120b57cec5SDimitry Andric 
48130b57cec5SDimitry Andric   // Make sure the timeout values make sense. The one thread timeout needs to
48140b57cec5SDimitry Andric   // be smaller than the overall timeout.
48150b57cec5SDimitry Andric   if (options.GetOneThreadTimeout() && options.GetTimeout() &&
48160b57cec5SDimitry Andric       *options.GetTimeout() < *options.GetOneThreadTimeout()) {
48170b57cec5SDimitry Andric     diagnostic_manager.PutString(eDiagnosticSeverityError,
48180b57cec5SDimitry Andric                                  "RunThreadPlan called with one thread "
48190b57cec5SDimitry Andric                                  "timeout greater than total timeout");
48200b57cec5SDimitry Andric     return eExpressionSetupError;
48210b57cec5SDimitry Andric   }
48220b57cec5SDimitry Andric 
48230b57cec5SDimitry Andric   StackID ctx_frame_id = selected_frame_sp->GetStackID();
48240b57cec5SDimitry Andric 
48250b57cec5SDimitry Andric   // N.B. Running the target may unset the currently selected thread and frame.
48260b57cec5SDimitry Andric   // We don't want to do that either, so we should arrange to reset them as
48270b57cec5SDimitry Andric   // well.
48280b57cec5SDimitry Andric 
48290b57cec5SDimitry Andric   lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
48300b57cec5SDimitry Andric 
48310b57cec5SDimitry Andric   uint32_t selected_tid;
48320b57cec5SDimitry Andric   StackID selected_stack_id;
48330b57cec5SDimitry Andric   if (selected_thread_sp) {
48340b57cec5SDimitry Andric     selected_tid = selected_thread_sp->GetIndexID();
4835fe013be4SDimitry Andric     selected_stack_id =
4836fe013be4SDimitry Andric         selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
4837fe013be4SDimitry Andric             ->GetStackID();
48380b57cec5SDimitry Andric   } else {
48390b57cec5SDimitry Andric     selected_tid = LLDB_INVALID_THREAD_ID;
48400b57cec5SDimitry Andric   }
48410b57cec5SDimitry Andric 
48420b57cec5SDimitry Andric   HostThread backup_private_state_thread;
48430b57cec5SDimitry Andric   lldb::StateType old_state = eStateInvalid;
48440b57cec5SDimitry Andric   lldb::ThreadPlanSP stopper_base_plan_sp;
48450b57cec5SDimitry Andric 
484681ad6265SDimitry Andric   Log *log(GetLog(LLDBLog::Step | LLDBLog::Process));
48470b57cec5SDimitry Andric   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
48480b57cec5SDimitry Andric     // Yikes, we are running on the private state thread!  So we can't wait for
48490b57cec5SDimitry Andric     // public events on this thread, since we are the thread that is generating
48500b57cec5SDimitry Andric     // public events. The simplest thing to do is to spin up a temporary thread
48510b57cec5SDimitry Andric     // to handle private state thread events while we are fielding public
48520b57cec5SDimitry Andric     // events here.
48539dba64beSDimitry Andric     LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
48540b57cec5SDimitry Andric                    "another state thread to handle the events.");
48550b57cec5SDimitry Andric 
48560b57cec5SDimitry Andric     backup_private_state_thread = m_private_state_thread;
48570b57cec5SDimitry Andric 
48580b57cec5SDimitry Andric     // One other bit of business: we want to run just this thread plan and
48590b57cec5SDimitry Andric     // anything it pushes, and then stop, returning control here. But in the
48600b57cec5SDimitry Andric     // normal course of things, the plan above us on the stack would be given a
48610b57cec5SDimitry Andric     // shot at the stop event before deciding to stop, and we don't want that.
48620b57cec5SDimitry Andric     // So we insert a "stopper" base plan on the stack before the plan we want
48630b57cec5SDimitry Andric     // to run.  Since base plans always stop and return control to the user,
48640b57cec5SDimitry Andric     // that will do just what we want.
48650b57cec5SDimitry Andric     stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
48660b57cec5SDimitry Andric     thread->QueueThreadPlan(stopper_base_plan_sp, false);
48670b57cec5SDimitry Andric     // Have to make sure our public state is stopped, since otherwise the
48680b57cec5SDimitry Andric     // reporting logic below doesn't work correctly.
48690b57cec5SDimitry Andric     old_state = m_public_state.GetValue();
48700b57cec5SDimitry Andric     m_public_state.SetValueNoLock(eStateStopped);
48710b57cec5SDimitry Andric 
48720b57cec5SDimitry Andric     // Now spin up the private state thread:
48730b57cec5SDimitry Andric     StartPrivateStateThread(true);
48740b57cec5SDimitry Andric   }
48750b57cec5SDimitry Andric 
48760b57cec5SDimitry Andric   thread->QueueThreadPlan(
48770b57cec5SDimitry Andric       thread_plan_sp, false); // This used to pass "true" does that make sense?
48780b57cec5SDimitry Andric 
48790b57cec5SDimitry Andric   if (options.GetDebug()) {
48800b57cec5SDimitry Andric     // In this case, we aren't actually going to run, we just want to stop
48810b57cec5SDimitry Andric     // right away. Flush this thread so we will refetch the stacks and show the
48820b57cec5SDimitry Andric     // correct backtrace.
48830b57cec5SDimitry Andric     // FIXME: To make this prettier we should invent some stop reason for this,
48840b57cec5SDimitry Andric     // but that
48850b57cec5SDimitry Andric     // is only cosmetic, and this functionality is only of use to lldb
48860b57cec5SDimitry Andric     // developers who can live with not pretty...
48870b57cec5SDimitry Andric     thread->Flush();
48880b57cec5SDimitry Andric     return eExpressionStoppedForDebug;
48890b57cec5SDimitry Andric   }
48900b57cec5SDimitry Andric 
48910b57cec5SDimitry Andric   ListenerSP listener_sp(
48920b57cec5SDimitry Andric       Listener::MakeListener("lldb.process.listener.run-thread-plan"));
48930b57cec5SDimitry Andric 
48940b57cec5SDimitry Andric   lldb::EventSP event_to_broadcast_sp;
48950b57cec5SDimitry Andric 
48960b57cec5SDimitry Andric   {
48970b57cec5SDimitry Andric     // This process event hijacker Hijacks the Public events and its destructor
48980b57cec5SDimitry Andric     // makes sure that the process events get restored on exit to the function.
48990b57cec5SDimitry Andric     //
49000b57cec5SDimitry Andric     // If the event needs to propagate beyond the hijacker (e.g., the process
49010b57cec5SDimitry Andric     // exits during execution), then the event is put into
49020b57cec5SDimitry Andric     // event_to_broadcast_sp for rebroadcasting.
49030b57cec5SDimitry Andric 
49040b57cec5SDimitry Andric     ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
49050b57cec5SDimitry Andric 
49060b57cec5SDimitry Andric     if (log) {
49070b57cec5SDimitry Andric       StreamString s;
49080b57cec5SDimitry Andric       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
49099dba64beSDimitry Andric       LLDB_LOGF(log,
49109dba64beSDimitry Andric                 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
49110b57cec5SDimitry Andric                 " to run thread plan \"%s\".",
49125ffd83dbSDimitry Andric                 thread_idx_id, expr_thread_id, s.GetData());
49130b57cec5SDimitry Andric     }
49140b57cec5SDimitry Andric 
49150b57cec5SDimitry Andric     bool got_event;
49160b57cec5SDimitry Andric     lldb::EventSP event_sp;
49170b57cec5SDimitry Andric     lldb::StateType stop_state = lldb::eStateInvalid;
49180b57cec5SDimitry Andric 
49190b57cec5SDimitry Andric     bool before_first_timeout = true; // This is set to false the first time
49200b57cec5SDimitry Andric                                       // that we have to halt the target.
49210b57cec5SDimitry Andric     bool do_resume = true;
49220b57cec5SDimitry Andric     bool handle_running_event = true;
49230b57cec5SDimitry Andric 
49240b57cec5SDimitry Andric     // This is just for accounting:
49250b57cec5SDimitry Andric     uint32_t num_resumes = 0;
49260b57cec5SDimitry Andric 
49270b57cec5SDimitry Andric     // If we are going to run all threads the whole time, or if we are only
49280b57cec5SDimitry Andric     // going to run one thread, then we don't need the first timeout.  So we
49290b57cec5SDimitry Andric     // pretend we are after the first timeout already.
49300b57cec5SDimitry Andric     if (!options.GetStopOthers() || !options.GetTryAllThreads())
49310b57cec5SDimitry Andric       before_first_timeout = false;
49320b57cec5SDimitry Andric 
49339dba64beSDimitry Andric     LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
49340b57cec5SDimitry Andric               options.GetStopOthers(), options.GetTryAllThreads(),
49350b57cec5SDimitry Andric               before_first_timeout);
49360b57cec5SDimitry Andric 
49370b57cec5SDimitry Andric     // This isn't going to work if there are unfetched events on the queue. Are
49380b57cec5SDimitry Andric     // there cases where we might want to run the remaining events here, and
49390b57cec5SDimitry Andric     // then try to call the function?  That's probably being too tricky for our
49400b57cec5SDimitry Andric     // own good.
49410b57cec5SDimitry Andric 
49420b57cec5SDimitry Andric     Event *other_events = listener_sp->PeekAtNextEvent();
49430b57cec5SDimitry Andric     if (other_events != nullptr) {
49440b57cec5SDimitry Andric       diagnostic_manager.PutString(
49450b57cec5SDimitry Andric           eDiagnosticSeverityError,
49460b57cec5SDimitry Andric           "RunThreadPlan called with pending events on the queue.");
49470b57cec5SDimitry Andric       return eExpressionSetupError;
49480b57cec5SDimitry Andric     }
49490b57cec5SDimitry Andric 
49500b57cec5SDimitry Andric     // We also need to make sure that the next event is delivered.  We might be
49510b57cec5SDimitry Andric     // calling a function as part of a thread plan, in which case the last
49520b57cec5SDimitry Andric     // delivered event could be the running event, and we don't want event
49530b57cec5SDimitry Andric     // coalescing to cause us to lose OUR running event...
49540b57cec5SDimitry Andric     ForceNextEventDelivery();
49550b57cec5SDimitry Andric 
49560b57cec5SDimitry Andric // This while loop must exit out the bottom, there's cleanup that we need to do
49570b57cec5SDimitry Andric // when we are done. So don't call return anywhere within it.
49580b57cec5SDimitry Andric 
49590b57cec5SDimitry Andric #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
49600b57cec5SDimitry Andric     // It's pretty much impossible to write test cases for things like: One
49610b57cec5SDimitry Andric     // thread timeout expires, I go to halt, but the process already stopped on
49620b57cec5SDimitry Andric     // the function call stop breakpoint.  Turning on this define will make us
49630b57cec5SDimitry Andric     // not fetch the first event till after the halt.  So if you run a quick
49640b57cec5SDimitry Andric     // function, it will have completed, and the completion event will be
49650b57cec5SDimitry Andric     // waiting, when you interrupt for halt. The expression evaluation should
49660b57cec5SDimitry Andric     // still succeed.
49670b57cec5SDimitry Andric     bool miss_first_event = true;
49680b57cec5SDimitry Andric #endif
49690b57cec5SDimitry Andric     while (true) {
49700b57cec5SDimitry Andric       // We usually want to resume the process if we get to the top of the
49710b57cec5SDimitry Andric       // loop. The only exception is if we get two running events with no
49720b57cec5SDimitry Andric       // intervening stop, which can happen, we will just wait for then next
49730b57cec5SDimitry Andric       // stop event.
49749dba64beSDimitry Andric       LLDB_LOGF(log,
49759dba64beSDimitry Andric                 "Top of while loop: do_resume: %i handle_running_event: %i "
49760b57cec5SDimitry Andric                 "before_first_timeout: %i.",
49770b57cec5SDimitry Andric                 do_resume, handle_running_event, before_first_timeout);
49780b57cec5SDimitry Andric 
49790b57cec5SDimitry Andric       if (do_resume || handle_running_event) {
49800b57cec5SDimitry Andric         // Do the initial resume and wait for the running event before going
49810b57cec5SDimitry Andric         // further.
49820b57cec5SDimitry Andric 
49830b57cec5SDimitry Andric         if (do_resume) {
49840b57cec5SDimitry Andric           num_resumes++;
49850b57cec5SDimitry Andric           Status resume_error = PrivateResume();
49860b57cec5SDimitry Andric           if (!resume_error.Success()) {
49870b57cec5SDimitry Andric             diagnostic_manager.Printf(
49880b57cec5SDimitry Andric                 eDiagnosticSeverityError,
49890b57cec5SDimitry Andric                 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
49900b57cec5SDimitry Andric                 resume_error.AsCString());
49910b57cec5SDimitry Andric             return_value = eExpressionSetupError;
49920b57cec5SDimitry Andric             break;
49930b57cec5SDimitry Andric           }
49940b57cec5SDimitry Andric         }
49950b57cec5SDimitry Andric 
49960b57cec5SDimitry Andric         got_event =
49970b57cec5SDimitry Andric             listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
49980b57cec5SDimitry Andric         if (!got_event) {
49999dba64beSDimitry Andric           LLDB_LOGF(log,
50009dba64beSDimitry Andric                     "Process::RunThreadPlan(): didn't get any event after "
50010b57cec5SDimitry Andric                     "resume %" PRIu32 ", exiting.",
50020b57cec5SDimitry Andric                     num_resumes);
50030b57cec5SDimitry Andric 
50040b57cec5SDimitry Andric           diagnostic_manager.Printf(eDiagnosticSeverityError,
50050b57cec5SDimitry Andric                                     "didn't get any event after resume %" PRIu32
50060b57cec5SDimitry Andric                                     ", exiting.",
50070b57cec5SDimitry Andric                                     num_resumes);
50080b57cec5SDimitry Andric           return_value = eExpressionSetupError;
50090b57cec5SDimitry Andric           break;
50100b57cec5SDimitry Andric         }
50110b57cec5SDimitry Andric 
50120b57cec5SDimitry Andric         stop_state =
50130b57cec5SDimitry Andric             Process::ProcessEventData::GetStateFromEvent(event_sp.get());
50140b57cec5SDimitry Andric 
50150b57cec5SDimitry Andric         if (stop_state != eStateRunning) {
50160b57cec5SDimitry Andric           bool restarted = false;
50170b57cec5SDimitry Andric 
50180b57cec5SDimitry Andric           if (stop_state == eStateStopped) {
50190b57cec5SDimitry Andric             restarted = Process::ProcessEventData::GetRestartedFromEvent(
50200b57cec5SDimitry Andric                 event_sp.get());
50219dba64beSDimitry Andric             LLDB_LOGF(
50229dba64beSDimitry Andric                 log,
50230b57cec5SDimitry Andric                 "Process::RunThreadPlan(): didn't get running event after "
50240b57cec5SDimitry Andric                 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
50250b57cec5SDimitry Andric                 "handle_running_event: %i).",
50260b57cec5SDimitry Andric                 num_resumes, StateAsCString(stop_state), restarted, do_resume,
50270b57cec5SDimitry Andric                 handle_running_event);
50280b57cec5SDimitry Andric           }
50290b57cec5SDimitry Andric 
50300b57cec5SDimitry Andric           if (restarted) {
50310b57cec5SDimitry Andric             // This is probably an overabundance of caution, I don't think I
50320b57cec5SDimitry Andric             // should ever get a stopped & restarted event here.  But if I do,
50330b57cec5SDimitry Andric             // the best thing is to Halt and then get out of here.
50340b57cec5SDimitry Andric             const bool clear_thread_plans = false;
50350b57cec5SDimitry Andric             const bool use_run_lock = false;
50360b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
50370b57cec5SDimitry Andric           }
50380b57cec5SDimitry Andric 
50390b57cec5SDimitry Andric           diagnostic_manager.Printf(
50400b57cec5SDimitry Andric               eDiagnosticSeverityError,
50410b57cec5SDimitry Andric               "didn't get running event after initial resume, got %s instead.",
50420b57cec5SDimitry Andric               StateAsCString(stop_state));
50430b57cec5SDimitry Andric           return_value = eExpressionSetupError;
50440b57cec5SDimitry Andric           break;
50450b57cec5SDimitry Andric         }
50460b57cec5SDimitry Andric 
50470b57cec5SDimitry Andric         if (log)
50480b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
50490b57cec5SDimitry Andric         // We need to call the function synchronously, so spin waiting for it
50500b57cec5SDimitry Andric         // to return. If we get interrupted while executing, we're going to
50510b57cec5SDimitry Andric         // lose our context, and won't be able to gather the result at this
50520b57cec5SDimitry Andric         // point. We set the timeout AFTER the resume, since the resume takes
50530b57cec5SDimitry Andric         // some time and we don't want to charge that to the timeout.
50540b57cec5SDimitry Andric       } else {
50550b57cec5SDimitry Andric         if (log)
50560b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): waiting for next event.");
50570b57cec5SDimitry Andric       }
50580b57cec5SDimitry Andric 
50590b57cec5SDimitry Andric       do_resume = true;
50600b57cec5SDimitry Andric       handle_running_event = true;
50610b57cec5SDimitry Andric 
50620b57cec5SDimitry Andric       // Now wait for the process to stop again:
50630b57cec5SDimitry Andric       event_sp.reset();
50640b57cec5SDimitry Andric 
50650b57cec5SDimitry Andric       Timeout<std::micro> timeout =
50660b57cec5SDimitry Andric           GetExpressionTimeout(options, before_first_timeout);
50670b57cec5SDimitry Andric       if (log) {
50680b57cec5SDimitry Andric         if (timeout) {
50690b57cec5SDimitry Andric           auto now = system_clock::now();
50709dba64beSDimitry Andric           LLDB_LOGF(log,
50719dba64beSDimitry Andric                     "Process::RunThreadPlan(): about to wait - now is %s - "
50720b57cec5SDimitry Andric                     "endpoint is %s",
50730b57cec5SDimitry Andric                     llvm::to_string(now).c_str(),
50740b57cec5SDimitry Andric                     llvm::to_string(now + *timeout).c_str());
50750b57cec5SDimitry Andric         } else {
50769dba64beSDimitry Andric           LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
50770b57cec5SDimitry Andric         }
50780b57cec5SDimitry Andric       }
50790b57cec5SDimitry Andric 
50800b57cec5SDimitry Andric #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
50810b57cec5SDimitry Andric       // See comment above...
50820b57cec5SDimitry Andric       if (miss_first_event) {
50839dba64beSDimitry Andric         std::this_thread::sleep_for(std::chrono::milliseconds(1));
50840b57cec5SDimitry Andric         miss_first_event = false;
50850b57cec5SDimitry Andric         got_event = false;
50860b57cec5SDimitry Andric       } else
50870b57cec5SDimitry Andric #endif
50880b57cec5SDimitry Andric         got_event = listener_sp->GetEvent(event_sp, timeout);
50890b57cec5SDimitry Andric 
50900b57cec5SDimitry Andric       if (got_event) {
50910b57cec5SDimitry Andric         if (event_sp) {
50920b57cec5SDimitry Andric           bool keep_going = false;
50930b57cec5SDimitry Andric           if (event_sp->GetType() == eBroadcastBitInterrupt) {
50940b57cec5SDimitry Andric             const bool clear_thread_plans = false;
50950b57cec5SDimitry Andric             const bool use_run_lock = false;
50960b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
50970b57cec5SDimitry Andric             return_value = eExpressionInterrupted;
50980b57cec5SDimitry Andric             diagnostic_manager.PutString(eDiagnosticSeverityRemark,
50990b57cec5SDimitry Andric                                          "execution halted by user interrupt.");
51009dba64beSDimitry Andric             LLDB_LOGF(log, "Process::RunThreadPlan(): Got  interrupted by "
51010b57cec5SDimitry Andric                            "eBroadcastBitInterrupted, exiting.");
51020b57cec5SDimitry Andric             break;
51030b57cec5SDimitry Andric           } else {
51040b57cec5SDimitry Andric             stop_state =
51050b57cec5SDimitry Andric                 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
51069dba64beSDimitry Andric             LLDB_LOGF(log,
51070b57cec5SDimitry Andric                       "Process::RunThreadPlan(): in while loop, got event: %s.",
51080b57cec5SDimitry Andric                       StateAsCString(stop_state));
51090b57cec5SDimitry Andric 
51100b57cec5SDimitry Andric             switch (stop_state) {
51110b57cec5SDimitry Andric             case lldb::eStateStopped: {
51125ffd83dbSDimitry Andric               if (Process::ProcessEventData::GetRestartedFromEvent(
51130b57cec5SDimitry Andric                       event_sp.get())) {
51140b57cec5SDimitry Andric                 // If we were restarted, we just need to go back up to fetch
51150b57cec5SDimitry Andric                 // another event.
51169dba64beSDimitry Andric                 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
51170b57cec5SDimitry Andric                                "restart, so we'll continue waiting.");
51180b57cec5SDimitry Andric                 keep_going = true;
51190b57cec5SDimitry Andric                 do_resume = false;
51200b57cec5SDimitry Andric                 handle_running_event = true;
51210b57cec5SDimitry Andric               } else {
51220b57cec5SDimitry Andric                 const bool handle_interrupts = true;
51230b57cec5SDimitry Andric                 return_value = *HandleStoppedEvent(
51245ffd83dbSDimitry Andric                     expr_thread_id, thread_plan_sp, thread_plan_restorer,
51255ffd83dbSDimitry Andric                     event_sp, event_to_broadcast_sp, options,
51265ffd83dbSDimitry Andric                     handle_interrupts);
51275ffd83dbSDimitry Andric                 if (return_value == eExpressionThreadVanished)
51285ffd83dbSDimitry Andric                   keep_going = false;
51290b57cec5SDimitry Andric               }
51300b57cec5SDimitry Andric             } break;
51310b57cec5SDimitry Andric 
51320b57cec5SDimitry Andric             case lldb::eStateRunning:
51330b57cec5SDimitry Andric               // This shouldn't really happen, but sometimes we do get two
51340b57cec5SDimitry Andric               // running events without an intervening stop, and in that case
51350b57cec5SDimitry Andric               // we should just go back to waiting for the stop.
51360b57cec5SDimitry Andric               do_resume = false;
51370b57cec5SDimitry Andric               keep_going = true;
51380b57cec5SDimitry Andric               handle_running_event = false;
51390b57cec5SDimitry Andric               break;
51400b57cec5SDimitry Andric 
51410b57cec5SDimitry Andric             default:
51429dba64beSDimitry Andric               LLDB_LOGF(log,
51439dba64beSDimitry Andric                         "Process::RunThreadPlan(): execution stopped with "
51440b57cec5SDimitry Andric                         "unexpected state: %s.",
51450b57cec5SDimitry Andric                         StateAsCString(stop_state));
51460b57cec5SDimitry Andric 
51470b57cec5SDimitry Andric               if (stop_state == eStateExited)
51480b57cec5SDimitry Andric                 event_to_broadcast_sp = event_sp;
51490b57cec5SDimitry Andric 
51500b57cec5SDimitry Andric               diagnostic_manager.PutString(
51510b57cec5SDimitry Andric                   eDiagnosticSeverityError,
51520b57cec5SDimitry Andric                   "execution stopped with unexpected state.");
51530b57cec5SDimitry Andric               return_value = eExpressionInterrupted;
51540b57cec5SDimitry Andric               break;
51550b57cec5SDimitry Andric             }
51560b57cec5SDimitry Andric           }
51570b57cec5SDimitry Andric 
51580b57cec5SDimitry Andric           if (keep_going)
51590b57cec5SDimitry Andric             continue;
51600b57cec5SDimitry Andric           else
51610b57cec5SDimitry Andric             break;
51620b57cec5SDimitry Andric         } else {
51630b57cec5SDimitry Andric           if (log)
51640b57cec5SDimitry Andric             log->PutCString("Process::RunThreadPlan(): got_event was true, but "
51650b57cec5SDimitry Andric                             "the event pointer was null.  How odd...");
51660b57cec5SDimitry Andric           return_value = eExpressionInterrupted;
51670b57cec5SDimitry Andric           break;
51680b57cec5SDimitry Andric         }
51690b57cec5SDimitry Andric       } else {
51700b57cec5SDimitry Andric         // If we didn't get an event that means we've timed out... We will
51710b57cec5SDimitry Andric         // interrupt the process here.  Depending on what we were asked to do
51720b57cec5SDimitry Andric         // we will either exit, or try with all threads running for the same
51730b57cec5SDimitry Andric         // timeout.
51740b57cec5SDimitry Andric 
51750b57cec5SDimitry Andric         if (log) {
51760b57cec5SDimitry Andric           if (options.GetTryAllThreads()) {
51770b57cec5SDimitry Andric             if (before_first_timeout) {
51780b57cec5SDimitry Andric               LLDB_LOG(log,
51790b57cec5SDimitry Andric                        "Running function with one thread timeout timed out.");
51800b57cec5SDimitry Andric             } else
51810b57cec5SDimitry Andric               LLDB_LOG(log, "Restarting function with all threads enabled and "
51820b57cec5SDimitry Andric                             "timeout: {0} timed out, abandoning execution.",
51830b57cec5SDimitry Andric                        timeout);
51840b57cec5SDimitry Andric           } else
51850b57cec5SDimitry Andric             LLDB_LOG(log, "Running function with timeout: {0} timed out, "
51860b57cec5SDimitry Andric                           "abandoning execution.",
51870b57cec5SDimitry Andric                      timeout);
51880b57cec5SDimitry Andric         }
51890b57cec5SDimitry Andric 
51900b57cec5SDimitry Andric         // It is possible that between the time we issued the Halt, and we get
51910b57cec5SDimitry Andric         // around to calling Halt the target could have stopped.  That's fine,
51920b57cec5SDimitry Andric         // Halt will figure that out and send the appropriate Stopped event.
51930b57cec5SDimitry Andric         // BUT it is also possible that we stopped & restarted (e.g. hit a
51940b57cec5SDimitry Andric         // signal with "stop" set to false.)  In
51950b57cec5SDimitry Andric         // that case, we'll get the stopped & restarted event, and we should go
51960b57cec5SDimitry Andric         // back to waiting for the Halt's stopped event.  That's what this
51970b57cec5SDimitry Andric         // while loop does.
51980b57cec5SDimitry Andric 
51990b57cec5SDimitry Andric         bool back_to_top = true;
52000b57cec5SDimitry Andric         uint32_t try_halt_again = 0;
52010b57cec5SDimitry Andric         bool do_halt = true;
52020b57cec5SDimitry Andric         const uint32_t num_retries = 5;
52030b57cec5SDimitry Andric         while (try_halt_again < num_retries) {
52040b57cec5SDimitry Andric           Status halt_error;
52050b57cec5SDimitry Andric           if (do_halt) {
52069dba64beSDimitry Andric             LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
52070b57cec5SDimitry Andric             const bool clear_thread_plans = false;
52080b57cec5SDimitry Andric             const bool use_run_lock = false;
52090b57cec5SDimitry Andric             Halt(clear_thread_plans, use_run_lock);
52100b57cec5SDimitry Andric           }
52110b57cec5SDimitry Andric           if (halt_error.Success()) {
52120b57cec5SDimitry Andric             if (log)
52130b57cec5SDimitry Andric               log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
52140b57cec5SDimitry Andric 
52150b57cec5SDimitry Andric             got_event =
52160b57cec5SDimitry Andric                 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
52170b57cec5SDimitry Andric 
52180b57cec5SDimitry Andric             if (got_event) {
52190b57cec5SDimitry Andric               stop_state =
52200b57cec5SDimitry Andric                   Process::ProcessEventData::GetStateFromEvent(event_sp.get());
52210b57cec5SDimitry Andric               if (log) {
52229dba64beSDimitry Andric                 LLDB_LOGF(log,
52239dba64beSDimitry Andric                           "Process::RunThreadPlan(): Stopped with event: %s",
52240b57cec5SDimitry Andric                           StateAsCString(stop_state));
52250b57cec5SDimitry Andric                 if (stop_state == lldb::eStateStopped &&
52260b57cec5SDimitry Andric                     Process::ProcessEventData::GetInterruptedFromEvent(
52270b57cec5SDimitry Andric                         event_sp.get()))
52280b57cec5SDimitry Andric                   log->PutCString("    Event was the Halt interruption event.");
52290b57cec5SDimitry Andric               }
52300b57cec5SDimitry Andric 
52310b57cec5SDimitry Andric               if (stop_state == lldb::eStateStopped) {
52320b57cec5SDimitry Andric                 if (Process::ProcessEventData::GetRestartedFromEvent(
52330b57cec5SDimitry Andric                         event_sp.get())) {
52340b57cec5SDimitry Andric                   if (log)
52350b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): Went to halt "
52360b57cec5SDimitry Andric                                     "but got a restarted event, there must be "
52370b57cec5SDimitry Andric                                     "an un-restarted stopped event so try "
52380b57cec5SDimitry Andric                                     "again...  "
52390b57cec5SDimitry Andric                                     "Exiting wait loop.");
52400b57cec5SDimitry Andric                   try_halt_again++;
52410b57cec5SDimitry Andric                   do_halt = false;
52420b57cec5SDimitry Andric                   continue;
52430b57cec5SDimitry Andric                 }
52440b57cec5SDimitry Andric 
52450b57cec5SDimitry Andric                 // Between the time we initiated the Halt and the time we
52460b57cec5SDimitry Andric                 // delivered it, the process could have already finished its
52470b57cec5SDimitry Andric                 // job.  Check that here:
52480b57cec5SDimitry Andric                 const bool handle_interrupts = false;
52490b57cec5SDimitry Andric                 if (auto result = HandleStoppedEvent(
52505ffd83dbSDimitry Andric                         expr_thread_id, thread_plan_sp, thread_plan_restorer,
52515ffd83dbSDimitry Andric                         event_sp, event_to_broadcast_sp, options,
52525ffd83dbSDimitry Andric                         handle_interrupts)) {
52530b57cec5SDimitry Andric                   return_value = *result;
52540b57cec5SDimitry Andric                   back_to_top = false;
52550b57cec5SDimitry Andric                   break;
52560b57cec5SDimitry Andric                 }
52570b57cec5SDimitry Andric 
52580b57cec5SDimitry Andric                 if (!options.GetTryAllThreads()) {
52590b57cec5SDimitry Andric                   if (log)
52600b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): try_all_threads "
52610b57cec5SDimitry Andric                                     "was false, we stopped so now we're "
52620b57cec5SDimitry Andric                                     "quitting.");
52630b57cec5SDimitry Andric                   return_value = eExpressionInterrupted;
52640b57cec5SDimitry Andric                   back_to_top = false;
52650b57cec5SDimitry Andric                   break;
52660b57cec5SDimitry Andric                 }
52670b57cec5SDimitry Andric 
52680b57cec5SDimitry Andric                 if (before_first_timeout) {
52690b57cec5SDimitry Andric                   // Set all the other threads to run, and return to the top of
52700b57cec5SDimitry Andric                   // the loop, which will continue;
52710b57cec5SDimitry Andric                   before_first_timeout = false;
52720b57cec5SDimitry Andric                   thread_plan_sp->SetStopOthers(false);
52730b57cec5SDimitry Andric                   if (log)
52740b57cec5SDimitry Andric                     log->PutCString(
52750b57cec5SDimitry Andric                         "Process::RunThreadPlan(): about to resume.");
52760b57cec5SDimitry Andric 
52770b57cec5SDimitry Andric                   back_to_top = true;
52780b57cec5SDimitry Andric                   break;
52790b57cec5SDimitry Andric                 } else {
52800b57cec5SDimitry Andric                   // Running all threads failed, so return Interrupted.
52810b57cec5SDimitry Andric                   if (log)
52820b57cec5SDimitry Andric                     log->PutCString("Process::RunThreadPlan(): running all "
52830b57cec5SDimitry Andric                                     "threads timed out.");
52840b57cec5SDimitry Andric                   return_value = eExpressionInterrupted;
52850b57cec5SDimitry Andric                   back_to_top = false;
52860b57cec5SDimitry Andric                   break;
52870b57cec5SDimitry Andric                 }
52880b57cec5SDimitry Andric               }
52890b57cec5SDimitry Andric             } else {
52900b57cec5SDimitry Andric               if (log)
52910b57cec5SDimitry Andric                 log->PutCString("Process::RunThreadPlan(): halt said it "
52920b57cec5SDimitry Andric                                 "succeeded, but I got no event.  "
52930b57cec5SDimitry Andric                                 "I'm getting out of here passing Interrupted.");
52940b57cec5SDimitry Andric               return_value = eExpressionInterrupted;
52950b57cec5SDimitry Andric               back_to_top = false;
52960b57cec5SDimitry Andric               break;
52970b57cec5SDimitry Andric             }
52980b57cec5SDimitry Andric           } else {
52990b57cec5SDimitry Andric             try_halt_again++;
53000b57cec5SDimitry Andric             continue;
53010b57cec5SDimitry Andric           }
53020b57cec5SDimitry Andric         }
53030b57cec5SDimitry Andric 
53040b57cec5SDimitry Andric         if (!back_to_top || try_halt_again > num_retries)
53050b57cec5SDimitry Andric           break;
53060b57cec5SDimitry Andric         else
53070b57cec5SDimitry Andric           continue;
53080b57cec5SDimitry Andric       }
53090b57cec5SDimitry Andric     } // END WAIT LOOP
53100b57cec5SDimitry Andric 
53110b57cec5SDimitry Andric     // If we had to start up a temporary private state thread to run this
53120b57cec5SDimitry Andric     // thread plan, shut it down now.
53130b57cec5SDimitry Andric     if (backup_private_state_thread.IsJoinable()) {
53140b57cec5SDimitry Andric       StopPrivateStateThread();
53150b57cec5SDimitry Andric       Status error;
53160b57cec5SDimitry Andric       m_private_state_thread = backup_private_state_thread;
53170b57cec5SDimitry Andric       if (stopper_base_plan_sp) {
53180b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
53190b57cec5SDimitry Andric       }
53200b57cec5SDimitry Andric       if (old_state != eStateInvalid)
53210b57cec5SDimitry Andric         m_public_state.SetValueNoLock(old_state);
53220b57cec5SDimitry Andric     }
53230b57cec5SDimitry Andric 
53245ffd83dbSDimitry Andric     // If our thread went away on us, we need to get out of here without
53255ffd83dbSDimitry Andric     // doing any more work.  We don't have to clean up the thread plan, that
53265ffd83dbSDimitry Andric     // will have happened when the Thread was destroyed.
53275ffd83dbSDimitry Andric     if (return_value == eExpressionThreadVanished) {
53285ffd83dbSDimitry Andric       return return_value;
53295ffd83dbSDimitry Andric     }
53305ffd83dbSDimitry Andric 
53310b57cec5SDimitry Andric     if (return_value != eExpressionCompleted && log) {
53320b57cec5SDimitry Andric       // Print a backtrace into the log so we can figure out where we are:
53330b57cec5SDimitry Andric       StreamString s;
53340b57cec5SDimitry Andric       s.PutCString("Thread state after unsuccessful completion: \n");
53350b57cec5SDimitry Andric       thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
53360b57cec5SDimitry Andric       log->PutString(s.GetString());
53370b57cec5SDimitry Andric     }
53380b57cec5SDimitry Andric     // Restore the thread state if we are going to discard the plan execution.
53390b57cec5SDimitry Andric     // There are three cases where this could happen: 1) The execution
53400b57cec5SDimitry Andric     // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
53410b57cec5SDimitry Andric     // was true 3) We got some other error, and discard_on_error was true
53420b57cec5SDimitry Andric     bool should_unwind = (return_value == eExpressionInterrupted &&
53430b57cec5SDimitry Andric                           options.DoesUnwindOnError()) ||
53440b57cec5SDimitry Andric                          (return_value == eExpressionHitBreakpoint &&
53450b57cec5SDimitry Andric                           options.DoesIgnoreBreakpoints());
53460b57cec5SDimitry Andric 
53470b57cec5SDimitry Andric     if (return_value == eExpressionCompleted || should_unwind) {
53480b57cec5SDimitry Andric       thread_plan_sp->RestoreThreadState();
53490b57cec5SDimitry Andric     }
53500b57cec5SDimitry Andric 
53510b57cec5SDimitry Andric     // Now do some processing on the results of the run:
53520b57cec5SDimitry Andric     if (return_value == eExpressionInterrupted ||
53530b57cec5SDimitry Andric         return_value == eExpressionHitBreakpoint) {
53540b57cec5SDimitry Andric       if (log) {
53550b57cec5SDimitry Andric         StreamString s;
53560b57cec5SDimitry Andric         if (event_sp)
53570b57cec5SDimitry Andric           event_sp->Dump(&s);
53580b57cec5SDimitry Andric         else {
53590b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): Stop event that "
53600b57cec5SDimitry Andric                           "interrupted us is NULL.");
53610b57cec5SDimitry Andric         }
53620b57cec5SDimitry Andric 
53630b57cec5SDimitry Andric         StreamString ts;
53640b57cec5SDimitry Andric 
53650b57cec5SDimitry Andric         const char *event_explanation = nullptr;
53660b57cec5SDimitry Andric 
53670b57cec5SDimitry Andric         do {
53680b57cec5SDimitry Andric           if (!event_sp) {
53690b57cec5SDimitry Andric             event_explanation = "<no event>";
53700b57cec5SDimitry Andric             break;
53710b57cec5SDimitry Andric           } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
53720b57cec5SDimitry Andric             event_explanation = "<user interrupt>";
53730b57cec5SDimitry Andric             break;
53740b57cec5SDimitry Andric           } else {
53750b57cec5SDimitry Andric             const Process::ProcessEventData *event_data =
53760b57cec5SDimitry Andric                 Process::ProcessEventData::GetEventDataFromEvent(
53770b57cec5SDimitry Andric                     event_sp.get());
53780b57cec5SDimitry Andric 
53790b57cec5SDimitry Andric             if (!event_data) {
53800b57cec5SDimitry Andric               event_explanation = "<no event data>";
53810b57cec5SDimitry Andric               break;
53820b57cec5SDimitry Andric             }
53830b57cec5SDimitry Andric 
53840b57cec5SDimitry Andric             Process *process = event_data->GetProcessSP().get();
53850b57cec5SDimitry Andric 
53860b57cec5SDimitry Andric             if (!process) {
53870b57cec5SDimitry Andric               event_explanation = "<no process>";
53880b57cec5SDimitry Andric               break;
53890b57cec5SDimitry Andric             }
53900b57cec5SDimitry Andric 
53910b57cec5SDimitry Andric             ThreadList &thread_list = process->GetThreadList();
53920b57cec5SDimitry Andric 
53930b57cec5SDimitry Andric             uint32_t num_threads = thread_list.GetSize();
53940b57cec5SDimitry Andric             uint32_t thread_index;
53950b57cec5SDimitry Andric 
53960b57cec5SDimitry Andric             ts.Printf("<%u threads> ", num_threads);
53970b57cec5SDimitry Andric 
53980b57cec5SDimitry Andric             for (thread_index = 0; thread_index < num_threads; ++thread_index) {
53990b57cec5SDimitry Andric               Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
54000b57cec5SDimitry Andric 
54010b57cec5SDimitry Andric               if (!thread) {
54020b57cec5SDimitry Andric                 ts.Printf("<?> ");
54030b57cec5SDimitry Andric                 continue;
54040b57cec5SDimitry Andric               }
54050b57cec5SDimitry Andric 
54060b57cec5SDimitry Andric               ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
54070b57cec5SDimitry Andric               RegisterContext *register_context =
54080b57cec5SDimitry Andric                   thread->GetRegisterContext().get();
54090b57cec5SDimitry Andric 
54100b57cec5SDimitry Andric               if (register_context)
54110b57cec5SDimitry Andric                 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
54120b57cec5SDimitry Andric               else
54130b57cec5SDimitry Andric                 ts.Printf("[ip unknown] ");
54140b57cec5SDimitry Andric 
54150b57cec5SDimitry Andric               // Show the private stop info here, the public stop info will be
54160b57cec5SDimitry Andric               // from the last natural stop.
54170b57cec5SDimitry Andric               lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
54180b57cec5SDimitry Andric               if (stop_info_sp) {
54190b57cec5SDimitry Andric                 const char *stop_desc = stop_info_sp->GetDescription();
54200b57cec5SDimitry Andric                 if (stop_desc)
54210b57cec5SDimitry Andric                   ts.PutCString(stop_desc);
54220b57cec5SDimitry Andric               }
54230b57cec5SDimitry Andric               ts.Printf(">");
54240b57cec5SDimitry Andric             }
54250b57cec5SDimitry Andric 
54260b57cec5SDimitry Andric             event_explanation = ts.GetData();
54270b57cec5SDimitry Andric           }
54280b57cec5SDimitry Andric         } while (false);
54290b57cec5SDimitry Andric 
54300b57cec5SDimitry Andric         if (event_explanation)
54319dba64beSDimitry Andric           LLDB_LOGF(log,
54329dba64beSDimitry Andric                     "Process::RunThreadPlan(): execution interrupted: %s %s",
54330b57cec5SDimitry Andric                     s.GetData(), event_explanation);
54340b57cec5SDimitry Andric         else
54359dba64beSDimitry Andric           LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
54360b57cec5SDimitry Andric                     s.GetData());
54370b57cec5SDimitry Andric       }
54380b57cec5SDimitry Andric 
54390b57cec5SDimitry Andric       if (should_unwind) {
54409dba64beSDimitry Andric         LLDB_LOGF(log,
54419dba64beSDimitry Andric                   "Process::RunThreadPlan: ExecutionInterrupted - "
54420b57cec5SDimitry Andric                   "discarding thread plans up to %p.",
54430b57cec5SDimitry Andric                   static_cast<void *>(thread_plan_sp.get()));
54440b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
54450b57cec5SDimitry Andric       } else {
54469dba64beSDimitry Andric         LLDB_LOGF(log,
54479dba64beSDimitry Andric                   "Process::RunThreadPlan: ExecutionInterrupted - for "
54480b57cec5SDimitry Andric                   "plan: %p not discarding.",
54490b57cec5SDimitry Andric                   static_cast<void *>(thread_plan_sp.get()));
54500b57cec5SDimitry Andric       }
54510b57cec5SDimitry Andric     } else if (return_value == eExpressionSetupError) {
54520b57cec5SDimitry Andric       if (log)
54530b57cec5SDimitry Andric         log->PutCString("Process::RunThreadPlan(): execution set up error.");
54540b57cec5SDimitry Andric 
54550b57cec5SDimitry Andric       if (options.DoesUnwindOnError()) {
54560b57cec5SDimitry Andric         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
54570b57cec5SDimitry Andric       }
54580b57cec5SDimitry Andric     } else {
54590b57cec5SDimitry Andric       if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
54600b57cec5SDimitry Andric         if (log)
54610b57cec5SDimitry Andric           log->PutCString("Process::RunThreadPlan(): thread plan is done");
54620b57cec5SDimitry Andric         return_value = eExpressionCompleted;
54630b57cec5SDimitry Andric       } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
54640b57cec5SDimitry Andric         if (log)
54650b57cec5SDimitry Andric           log->PutCString(
54660b57cec5SDimitry Andric               "Process::RunThreadPlan(): thread plan was discarded");
54670b57cec5SDimitry Andric         return_value = eExpressionDiscarded;
54680b57cec5SDimitry Andric       } else {
54690b57cec5SDimitry Andric         if (log)
54700b57cec5SDimitry Andric           log->PutCString(
54710b57cec5SDimitry Andric               "Process::RunThreadPlan(): thread plan stopped in mid course");
54720b57cec5SDimitry Andric         if (options.DoesUnwindOnError() && thread_plan_sp) {
54730b57cec5SDimitry Andric           if (log)
54740b57cec5SDimitry Andric             log->PutCString("Process::RunThreadPlan(): discarding thread plan "
54750b57cec5SDimitry Andric                             "'cause unwind_on_error is set.");
54760b57cec5SDimitry Andric           thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
54770b57cec5SDimitry Andric         }
54780b57cec5SDimitry Andric       }
54790b57cec5SDimitry Andric     }
54800b57cec5SDimitry Andric 
54810b57cec5SDimitry Andric     // Thread we ran the function in may have gone away because we ran the
54820b57cec5SDimitry Andric     // target Check that it's still there, and if it is put it back in the
54830b57cec5SDimitry Andric     // context. Also restore the frame in the context if it is still present.
54840b57cec5SDimitry Andric     thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
54850b57cec5SDimitry Andric     if (thread) {
54860b57cec5SDimitry Andric       exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
54870b57cec5SDimitry Andric     }
54880b57cec5SDimitry Andric 
54890b57cec5SDimitry Andric     // Also restore the current process'es selected frame & thread, since this
54900b57cec5SDimitry Andric     // function calling may be done behind the user's back.
54910b57cec5SDimitry Andric 
54920b57cec5SDimitry Andric     if (selected_tid != LLDB_INVALID_THREAD_ID) {
54930b57cec5SDimitry Andric       if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
54940b57cec5SDimitry Andric           selected_stack_id.IsValid()) {
54950b57cec5SDimitry Andric         // We were able to restore the selected thread, now restore the frame:
54960b57cec5SDimitry Andric         std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
54970b57cec5SDimitry Andric         StackFrameSP old_frame_sp =
54980b57cec5SDimitry Andric             GetThreadList().GetSelectedThread()->GetFrameWithStackID(
54990b57cec5SDimitry Andric                 selected_stack_id);
55000b57cec5SDimitry Andric         if (old_frame_sp)
55010b57cec5SDimitry Andric           GetThreadList().GetSelectedThread()->SetSelectedFrame(
55020b57cec5SDimitry Andric               old_frame_sp.get());
55030b57cec5SDimitry Andric       }
55040b57cec5SDimitry Andric     }
55050b57cec5SDimitry Andric   }
55060b57cec5SDimitry Andric 
55070b57cec5SDimitry Andric   // If the process exited during the run of the thread plan, notify everyone.
55080b57cec5SDimitry Andric 
55090b57cec5SDimitry Andric   if (event_to_broadcast_sp) {
55100b57cec5SDimitry Andric     if (log)
55110b57cec5SDimitry Andric       log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
55120b57cec5SDimitry Andric     BroadcastEvent(event_to_broadcast_sp);
55130b57cec5SDimitry Andric   }
55140b57cec5SDimitry Andric 
55150b57cec5SDimitry Andric   return return_value;
55160b57cec5SDimitry Andric }
55170b57cec5SDimitry Andric 
ExecutionResultAsCString(ExpressionResults result)55180b57cec5SDimitry Andric const char *Process::ExecutionResultAsCString(ExpressionResults result) {
55195ffd83dbSDimitry Andric   const char *result_name = "<unknown>";
55200b57cec5SDimitry Andric 
55210b57cec5SDimitry Andric   switch (result) {
55220b57cec5SDimitry Andric   case eExpressionCompleted:
55230b57cec5SDimitry Andric     result_name = "eExpressionCompleted";
55240b57cec5SDimitry Andric     break;
55250b57cec5SDimitry Andric   case eExpressionDiscarded:
55260b57cec5SDimitry Andric     result_name = "eExpressionDiscarded";
55270b57cec5SDimitry Andric     break;
55280b57cec5SDimitry Andric   case eExpressionInterrupted:
55290b57cec5SDimitry Andric     result_name = "eExpressionInterrupted";
55300b57cec5SDimitry Andric     break;
55310b57cec5SDimitry Andric   case eExpressionHitBreakpoint:
55320b57cec5SDimitry Andric     result_name = "eExpressionHitBreakpoint";
55330b57cec5SDimitry Andric     break;
55340b57cec5SDimitry Andric   case eExpressionSetupError:
55350b57cec5SDimitry Andric     result_name = "eExpressionSetupError";
55360b57cec5SDimitry Andric     break;
55370b57cec5SDimitry Andric   case eExpressionParseError:
55380b57cec5SDimitry Andric     result_name = "eExpressionParseError";
55390b57cec5SDimitry Andric     break;
55400b57cec5SDimitry Andric   case eExpressionResultUnavailable:
55410b57cec5SDimitry Andric     result_name = "eExpressionResultUnavailable";
55420b57cec5SDimitry Andric     break;
55430b57cec5SDimitry Andric   case eExpressionTimedOut:
55440b57cec5SDimitry Andric     result_name = "eExpressionTimedOut";
55450b57cec5SDimitry Andric     break;
55460b57cec5SDimitry Andric   case eExpressionStoppedForDebug:
55470b57cec5SDimitry Andric     result_name = "eExpressionStoppedForDebug";
55480b57cec5SDimitry Andric     break;
55495ffd83dbSDimitry Andric   case eExpressionThreadVanished:
55505ffd83dbSDimitry Andric     result_name = "eExpressionThreadVanished";
55510b57cec5SDimitry Andric   }
55520b57cec5SDimitry Andric   return result_name;
55530b57cec5SDimitry Andric }
55540b57cec5SDimitry Andric 
GetStatus(Stream & strm)55550b57cec5SDimitry Andric void Process::GetStatus(Stream &strm) {
55560b57cec5SDimitry Andric   const StateType state = GetState();
55570b57cec5SDimitry Andric   if (StateIsStoppedState(state, false)) {
55580b57cec5SDimitry Andric     if (state == eStateExited) {
55590b57cec5SDimitry Andric       int exit_status = GetExitStatus();
55600b57cec5SDimitry Andric       const char *exit_description = GetExitDescription();
55610b57cec5SDimitry Andric       strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
55620b57cec5SDimitry Andric                   GetID(), exit_status, exit_status,
55630b57cec5SDimitry Andric                   exit_description ? exit_description : "");
55640b57cec5SDimitry Andric     } else {
55650b57cec5SDimitry Andric       if (state == eStateConnected)
55660b57cec5SDimitry Andric         strm.Printf("Connected to remote target.\n");
55670b57cec5SDimitry Andric       else
55680b57cec5SDimitry Andric         strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
55690b57cec5SDimitry Andric     }
55700b57cec5SDimitry Andric   } else {
55710b57cec5SDimitry Andric     strm.Printf("Process %" PRIu64 " is running.\n", GetID());
55720b57cec5SDimitry Andric   }
55730b57cec5SDimitry Andric }
55740b57cec5SDimitry 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)55750b57cec5SDimitry Andric size_t Process::GetThreadStatus(Stream &strm,
55760b57cec5SDimitry Andric                                 bool only_threads_with_stop_reason,
55770b57cec5SDimitry Andric                                 uint32_t start_frame, uint32_t num_frames,
55780b57cec5SDimitry Andric                                 uint32_t num_frames_with_source,
55790b57cec5SDimitry Andric                                 bool stop_format) {
55800b57cec5SDimitry Andric   size_t num_thread_infos_dumped = 0;
55810b57cec5SDimitry Andric 
55820b57cec5SDimitry Andric   // You can't hold the thread list lock while calling Thread::GetStatus.  That
55830b57cec5SDimitry Andric   // very well might run code (e.g. if we need it to get return values or
55840b57cec5SDimitry Andric   // arguments.)  For that to work the process has to be able to acquire it.
55850b57cec5SDimitry Andric   // So instead copy the thread ID's, and look them up one by one:
55860b57cec5SDimitry Andric 
55870b57cec5SDimitry Andric   uint32_t num_threads;
55880b57cec5SDimitry Andric   std::vector<lldb::tid_t> thread_id_array;
55890b57cec5SDimitry Andric   // Scope for thread list locker;
55900b57cec5SDimitry Andric   {
55910b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
55920b57cec5SDimitry Andric     ThreadList &curr_thread_list = GetThreadList();
55930b57cec5SDimitry Andric     num_threads = curr_thread_list.GetSize();
55940b57cec5SDimitry Andric     uint32_t idx;
55950b57cec5SDimitry Andric     thread_id_array.resize(num_threads);
55960b57cec5SDimitry Andric     for (idx = 0; idx < num_threads; ++idx)
55970b57cec5SDimitry Andric       thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
55980b57cec5SDimitry Andric   }
55990b57cec5SDimitry Andric 
56000b57cec5SDimitry Andric   for (uint32_t i = 0; i < num_threads; i++) {
56010b57cec5SDimitry Andric     ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
56020b57cec5SDimitry Andric     if (thread_sp) {
56030b57cec5SDimitry Andric       if (only_threads_with_stop_reason) {
56040b57cec5SDimitry Andric         StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
56050b57cec5SDimitry Andric         if (!stop_info_sp || !stop_info_sp->IsValid())
56060b57cec5SDimitry Andric           continue;
56070b57cec5SDimitry Andric       }
56080b57cec5SDimitry Andric       thread_sp->GetStatus(strm, start_frame, num_frames,
56090b57cec5SDimitry Andric                            num_frames_with_source,
56100b57cec5SDimitry Andric                            stop_format);
56110b57cec5SDimitry Andric       ++num_thread_infos_dumped;
56120b57cec5SDimitry Andric     } else {
561381ad6265SDimitry Andric       Log *log = GetLog(LLDBLog::Process);
56149dba64beSDimitry Andric       LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
56150b57cec5SDimitry Andric                      " vanished while running Thread::GetStatus.");
56160b57cec5SDimitry Andric     }
56170b57cec5SDimitry Andric   }
56180b57cec5SDimitry Andric   return num_thread_infos_dumped;
56190b57cec5SDimitry Andric }
56200b57cec5SDimitry Andric 
AddInvalidMemoryRegion(const LoadRange & region)56210b57cec5SDimitry Andric void Process::AddInvalidMemoryRegion(const LoadRange &region) {
56220b57cec5SDimitry Andric   m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
56230b57cec5SDimitry Andric }
56240b57cec5SDimitry Andric 
RemoveInvalidMemoryRange(const LoadRange & region)56250b57cec5SDimitry Andric bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
56260b57cec5SDimitry Andric   return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
56270b57cec5SDimitry Andric                                            region.GetByteSize());
56280b57cec5SDimitry Andric }
56290b57cec5SDimitry Andric 
AddPreResumeAction(PreResumeActionCallback callback,void * baton)56300b57cec5SDimitry Andric void Process::AddPreResumeAction(PreResumeActionCallback callback,
56310b57cec5SDimitry Andric                                  void *baton) {
56320b57cec5SDimitry Andric   m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
56330b57cec5SDimitry Andric }
56340b57cec5SDimitry Andric 
RunPreResumeActions()56350b57cec5SDimitry Andric bool Process::RunPreResumeActions() {
56360b57cec5SDimitry Andric   bool result = true;
56370b57cec5SDimitry Andric   while (!m_pre_resume_actions.empty()) {
56380b57cec5SDimitry Andric     struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
56390b57cec5SDimitry Andric     m_pre_resume_actions.pop_back();
56400b57cec5SDimitry Andric     bool this_result = action.callback(action.baton);
56410b57cec5SDimitry Andric     if (result)
56420b57cec5SDimitry Andric       result = this_result;
56430b57cec5SDimitry Andric   }
56440b57cec5SDimitry Andric   return result;
56450b57cec5SDimitry Andric }
56460b57cec5SDimitry Andric 
ClearPreResumeActions()56470b57cec5SDimitry Andric void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
56480b57cec5SDimitry Andric 
ClearPreResumeAction(PreResumeActionCallback callback,void * baton)56490b57cec5SDimitry Andric void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
56500b57cec5SDimitry Andric {
56510b57cec5SDimitry Andric     PreResumeCallbackAndBaton element(callback, baton);
56520b57cec5SDimitry Andric     auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
56530b57cec5SDimitry Andric     if (found_iter != m_pre_resume_actions.end())
56540b57cec5SDimitry Andric     {
56550b57cec5SDimitry Andric         m_pre_resume_actions.erase(found_iter);
56560b57cec5SDimitry Andric     }
56570b57cec5SDimitry Andric }
56580b57cec5SDimitry Andric 
GetRunLock()56590b57cec5SDimitry Andric ProcessRunLock &Process::GetRunLock() {
56600b57cec5SDimitry Andric   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
56610b57cec5SDimitry Andric     return m_private_run_lock;
56620b57cec5SDimitry Andric   else
56630b57cec5SDimitry Andric     return m_public_run_lock;
56640b57cec5SDimitry Andric }
56650b57cec5SDimitry Andric 
CurrentThreadIsPrivateStateThread()56669dba64beSDimitry Andric bool Process::CurrentThreadIsPrivateStateThread()
56679dba64beSDimitry Andric {
56689dba64beSDimitry Andric   return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
56699dba64beSDimitry Andric }
56709dba64beSDimitry Andric 
56719dba64beSDimitry Andric 
Flush()56720b57cec5SDimitry Andric void Process::Flush() {
56730b57cec5SDimitry Andric   m_thread_list.Flush();
56740b57cec5SDimitry Andric   m_extended_thread_list.Flush();
56750b57cec5SDimitry Andric   m_extended_thread_stop_id = 0;
56760b57cec5SDimitry Andric   m_queue_list.Clear();
56770b57cec5SDimitry Andric   m_queue_list_stop_id = 0;
56780b57cec5SDimitry Andric }
56790b57cec5SDimitry Andric 
GetCodeAddressMask()5680fe6060f1SDimitry Andric lldb::addr_t Process::GetCodeAddressMask() {
5681fe013be4SDimitry Andric   if (uint32_t num_bits_setting = GetVirtualAddressableBits())
5682fe013be4SDimitry Andric     return ~((1ULL << num_bits_setting) - 1);
5683fe013be4SDimitry Andric 
5684fe6060f1SDimitry Andric   return m_code_address_mask;
5685fe6060f1SDimitry Andric }
5686fe6060f1SDimitry Andric 
GetDataAddressMask()5687fe6060f1SDimitry Andric lldb::addr_t Process::GetDataAddressMask() {
5688fe013be4SDimitry Andric   if (uint32_t num_bits_setting = GetVirtualAddressableBits())
5689fe013be4SDimitry Andric     return ~((1ULL << num_bits_setting) - 1);
5690fe013be4SDimitry Andric 
5691fe6060f1SDimitry Andric   return m_data_address_mask;
5692fe6060f1SDimitry Andric }
5693fe6060f1SDimitry Andric 
GetHighmemCodeAddressMask()5694fe013be4SDimitry Andric lldb::addr_t Process::GetHighmemCodeAddressMask() {
5695fe013be4SDimitry Andric   if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())
5696fe013be4SDimitry Andric     return ~((1ULL << num_bits_setting) - 1);
5697*a58f00eaSDimitry Andric   if (m_highmem_code_address_mask)
5698*a58f00eaSDimitry Andric     return m_highmem_code_address_mask;
5699fe013be4SDimitry Andric   return GetCodeAddressMask();
5700fe013be4SDimitry Andric }
5701fe013be4SDimitry Andric 
GetHighmemDataAddressMask()5702fe013be4SDimitry Andric lldb::addr_t Process::GetHighmemDataAddressMask() {
5703fe013be4SDimitry Andric   if (uint32_t num_bits_setting = GetHighmemVirtualAddressableBits())
5704fe013be4SDimitry Andric     return ~((1ULL << num_bits_setting) - 1);
5705*a58f00eaSDimitry Andric   if (m_highmem_data_address_mask)
5706*a58f00eaSDimitry Andric     return m_highmem_data_address_mask;
5707fe013be4SDimitry Andric   return GetDataAddressMask();
5708fe013be4SDimitry Andric }
5709fe013be4SDimitry Andric 
SetCodeAddressMask(lldb::addr_t code_address_mask)5710fe013be4SDimitry Andric void Process::SetCodeAddressMask(lldb::addr_t code_address_mask) {
5711fe013be4SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Process),
5712fe013be4SDimitry Andric            "Setting Process code address mask to {0:x}", code_address_mask);
5713fe013be4SDimitry Andric   m_code_address_mask = code_address_mask;
5714fe013be4SDimitry Andric }
5715fe013be4SDimitry Andric 
SetDataAddressMask(lldb::addr_t data_address_mask)5716fe013be4SDimitry Andric void Process::SetDataAddressMask(lldb::addr_t data_address_mask) {
5717fe013be4SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Process),
5718fe013be4SDimitry Andric            "Setting Process data address mask to {0:x}", data_address_mask);
5719fe013be4SDimitry Andric   m_data_address_mask = data_address_mask;
5720fe013be4SDimitry Andric }
5721fe013be4SDimitry Andric 
SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)5722fe013be4SDimitry Andric void Process::SetHighmemCodeAddressMask(lldb::addr_t code_address_mask) {
5723fe013be4SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Process),
5724fe013be4SDimitry Andric            "Setting Process highmem code address mask to {0:x}",
5725fe013be4SDimitry Andric            code_address_mask);
5726fe013be4SDimitry Andric   m_highmem_code_address_mask = code_address_mask;
5727fe013be4SDimitry Andric }
5728fe013be4SDimitry Andric 
SetHighmemDataAddressMask(lldb::addr_t data_address_mask)5729fe013be4SDimitry Andric void Process::SetHighmemDataAddressMask(lldb::addr_t data_address_mask) {
5730fe013be4SDimitry Andric   LLDB_LOG(GetLog(LLDBLog::Process),
5731fe013be4SDimitry Andric            "Setting Process highmem data address mask to {0:x}",
5732fe013be4SDimitry Andric            data_address_mask);
5733fe013be4SDimitry Andric   m_highmem_data_address_mask = data_address_mask;
5734fe013be4SDimitry Andric }
5735fe013be4SDimitry Andric 
FixCodeAddress(addr_t addr)5736fe013be4SDimitry Andric addr_t Process::FixCodeAddress(addr_t addr) {
5737fe013be4SDimitry Andric   if (ABISP abi_sp = GetABI())
5738fe013be4SDimitry Andric     addr = abi_sp->FixCodeAddress(addr);
5739fe013be4SDimitry Andric   return addr;
5740fe013be4SDimitry Andric }
5741fe013be4SDimitry Andric 
FixDataAddress(addr_t addr)5742fe013be4SDimitry Andric addr_t Process::FixDataAddress(addr_t addr) {
5743fe013be4SDimitry Andric   if (ABISP abi_sp = GetABI())
5744fe013be4SDimitry Andric     addr = abi_sp->FixDataAddress(addr);
5745fe013be4SDimitry Andric   return addr;
5746fe013be4SDimitry Andric }
5747fe013be4SDimitry Andric 
FixAnyAddress(addr_t addr)5748fe013be4SDimitry Andric addr_t Process::FixAnyAddress(addr_t addr) {
5749fe013be4SDimitry Andric   if (ABISP abi_sp = GetABI())
5750fe013be4SDimitry Andric     addr = abi_sp->FixAnyAddress(addr);
5751fe013be4SDimitry Andric   return addr;
5752fe013be4SDimitry Andric }
5753fe013be4SDimitry Andric 
DidExec()57540b57cec5SDimitry Andric void Process::DidExec() {
575581ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
57569dba64beSDimitry Andric   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
57570b57cec5SDimitry Andric 
57580b57cec5SDimitry Andric   Target &target = GetTarget();
57590b57cec5SDimitry Andric   target.CleanupProcess();
57600b57cec5SDimitry Andric   target.ClearModules(false);
57610b57cec5SDimitry Andric   m_dynamic_checkers_up.reset();
57620b57cec5SDimitry Andric   m_abi_sp.reset();
57630b57cec5SDimitry Andric   m_system_runtime_up.reset();
57640b57cec5SDimitry Andric   m_os_up.reset();
57650b57cec5SDimitry Andric   m_dyld_up.reset();
57660b57cec5SDimitry Andric   m_jit_loaders_up.reset();
57670b57cec5SDimitry Andric   m_image_tokens.clear();
5768bdd1243dSDimitry Andric   // After an exec, the inferior is a new process and these memory regions are
5769bdd1243dSDimitry Andric   // no longer allocated.
5770bdd1243dSDimitry Andric   m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);
57710b57cec5SDimitry Andric   {
57720b57cec5SDimitry Andric     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
57730b57cec5SDimitry Andric     m_language_runtimes.clear();
57740b57cec5SDimitry Andric   }
57750b57cec5SDimitry Andric   m_instrumentation_runtimes.clear();
57760b57cec5SDimitry Andric   m_thread_list.DiscardThreadPlans();
57770b57cec5SDimitry Andric   m_memory_cache.Clear(true);
57780b57cec5SDimitry Andric   DoDidExec();
57790b57cec5SDimitry Andric   CompleteAttach();
57800b57cec5SDimitry Andric   // Flush the process (threads and all stack frames) after running
57810b57cec5SDimitry Andric   // CompleteAttach() in case the dynamic loader loaded things in new
57820b57cec5SDimitry Andric   // locations.
57830b57cec5SDimitry Andric   Flush();
57840b57cec5SDimitry Andric 
57850b57cec5SDimitry Andric   // After we figure out what was loaded/unloaded in CompleteAttach, we need to
57860b57cec5SDimitry Andric   // let the target know so it can do any cleanup it needs to.
57870b57cec5SDimitry Andric   target.DidExec();
57880b57cec5SDimitry Andric }
57890b57cec5SDimitry Andric 
ResolveIndirectFunction(const Address * address,Status & error)57900b57cec5SDimitry Andric addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
57910b57cec5SDimitry Andric   if (address == nullptr) {
57920b57cec5SDimitry Andric     error.SetErrorString("Invalid address argument");
57930b57cec5SDimitry Andric     return LLDB_INVALID_ADDRESS;
57940b57cec5SDimitry Andric   }
57950b57cec5SDimitry Andric 
57960b57cec5SDimitry Andric   addr_t function_addr = LLDB_INVALID_ADDRESS;
57970b57cec5SDimitry Andric 
57980b57cec5SDimitry Andric   addr_t addr = address->GetLoadAddress(&GetTarget());
57990b57cec5SDimitry Andric   std::map<addr_t, addr_t>::const_iterator iter =
58000b57cec5SDimitry Andric       m_resolved_indirect_addresses.find(addr);
58010b57cec5SDimitry Andric   if (iter != m_resolved_indirect_addresses.end()) {
58020b57cec5SDimitry Andric     function_addr = (*iter).second;
58030b57cec5SDimitry Andric   } else {
58049dba64beSDimitry Andric     if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
58050b57cec5SDimitry Andric       Symbol *symbol = address->CalculateSymbolContextSymbol();
58060b57cec5SDimitry Andric       error.SetErrorStringWithFormat(
58070b57cec5SDimitry Andric           "Unable to call resolver for indirect function %s",
58080b57cec5SDimitry Andric           symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
58090b57cec5SDimitry Andric       function_addr = LLDB_INVALID_ADDRESS;
58100b57cec5SDimitry Andric     } else {
5811fe6060f1SDimitry Andric       if (ABISP abi_sp = GetABI())
5812fe6060f1SDimitry Andric         function_addr = abi_sp->FixCodeAddress(function_addr);
58130b57cec5SDimitry Andric       m_resolved_indirect_addresses.insert(
58140b57cec5SDimitry Andric           std::pair<addr_t, addr_t>(addr, function_addr));
58150b57cec5SDimitry Andric     }
58160b57cec5SDimitry Andric   }
58170b57cec5SDimitry Andric   return function_addr;
58180b57cec5SDimitry Andric }
58190b57cec5SDimitry Andric 
ModulesDidLoad(ModuleList & module_list)58200b57cec5SDimitry Andric void Process::ModulesDidLoad(ModuleList &module_list) {
5821e8d8bef9SDimitry Andric   // Inform the system runtime of the modified modules.
58220b57cec5SDimitry Andric   SystemRuntime *sys_runtime = GetSystemRuntime();
5823e8d8bef9SDimitry Andric   if (sys_runtime)
58240b57cec5SDimitry Andric     sys_runtime->ModulesDidLoad(module_list);
58250b57cec5SDimitry Andric 
58260b57cec5SDimitry Andric   GetJITLoaders().ModulesDidLoad(module_list);
58270b57cec5SDimitry Andric 
5828e8d8bef9SDimitry Andric   // Give the instrumentation runtimes a chance to be created before informing
5829e8d8bef9SDimitry Andric   // them of the modified modules.
58300b57cec5SDimitry Andric   InstrumentationRuntime::ModulesDidLoad(module_list, this,
58310b57cec5SDimitry Andric                                          m_instrumentation_runtimes);
5832e8d8bef9SDimitry Andric   for (auto &runtime : m_instrumentation_runtimes)
5833e8d8bef9SDimitry Andric     runtime.second->ModulesDidLoad(module_list);
58340b57cec5SDimitry Andric 
5835e8d8bef9SDimitry Andric   // Give the language runtimes a chance to be created before informing them of
5836e8d8bef9SDimitry Andric   // the modified modules.
5837e8d8bef9SDimitry Andric   for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
5838e8d8bef9SDimitry Andric     if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
58390b57cec5SDimitry Andric       runtime->ModulesDidLoad(module_list);
58400b57cec5SDimitry Andric   }
58410b57cec5SDimitry Andric 
58420b57cec5SDimitry Andric   // If we don't have an operating system plug-in, try to load one since
58430b57cec5SDimitry Andric   // loading shared libraries might cause a new one to try and load
58440b57cec5SDimitry Andric   if (!m_os_up)
58450b57cec5SDimitry Andric     LoadOperatingSystemPlugin(false);
58460b57cec5SDimitry Andric 
5847e8d8bef9SDimitry Andric   // Inform the structured-data plugins of the modified modules.
5848fe013be4SDimitry Andric   for (auto &pair : m_structured_data_plugin_map) {
58490b57cec5SDimitry Andric     if (pair.second)
58500b57cec5SDimitry Andric       pair.second->ModulesDidLoad(*this, module_list);
58510b57cec5SDimitry Andric   }
58520b57cec5SDimitry Andric }
58530b57cec5SDimitry Andric 
PrintWarningOptimization(const SymbolContext & sc)58540b57cec5SDimitry Andric void Process::PrintWarningOptimization(const SymbolContext &sc) {
58555ffd83dbSDimitry Andric   if (!GetWarningsOptimization())
58565ffd83dbSDimitry Andric     return;
585781ad6265SDimitry Andric   if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())
58585ffd83dbSDimitry Andric     return;
585981ad6265SDimitry Andric   sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
58600b57cec5SDimitry Andric }
58610b57cec5SDimitry Andric 
PrintWarningUnsupportedLanguage(const SymbolContext & sc)58625ffd83dbSDimitry Andric void Process::PrintWarningUnsupportedLanguage(const SymbolContext &sc) {
58635ffd83dbSDimitry Andric   if (!GetWarningsUnsupportedLanguage())
58645ffd83dbSDimitry Andric     return;
58655ffd83dbSDimitry Andric   if (!sc.module_sp)
58665ffd83dbSDimitry Andric     return;
58675ffd83dbSDimitry Andric   LanguageType language = sc.GetLanguage();
58685ffd83dbSDimitry Andric   if (language == eLanguageTypeUnknown)
58695ffd83dbSDimitry Andric     return;
5870fe6060f1SDimitry Andric   LanguageSet plugins =
5871fe6060f1SDimitry Andric       PluginManager::GetAllTypeSystemSupportedLanguagesForTypes();
587281ad6265SDimitry Andric   if (plugins[language])
587381ad6265SDimitry Andric     return;
587481ad6265SDimitry Andric   sc.module_sp->ReportWarningUnsupportedLanguage(
587581ad6265SDimitry Andric       language, GetTarget().GetDebugger().GetID());
58765ffd83dbSDimitry Andric }
58775ffd83dbSDimitry Andric 
GetProcessInfo(ProcessInstanceInfo & info)58780b57cec5SDimitry Andric bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
58790b57cec5SDimitry Andric   info.Clear();
58800b57cec5SDimitry Andric 
58810b57cec5SDimitry Andric   PlatformSP platform_sp = GetTarget().GetPlatform();
58820b57cec5SDimitry Andric   if (!platform_sp)
58830b57cec5SDimitry Andric     return false;
58840b57cec5SDimitry Andric 
58850b57cec5SDimitry Andric   return platform_sp->GetProcessInfo(GetID(), info);
58860b57cec5SDimitry Andric }
58870b57cec5SDimitry Andric 
GetHistoryThreads(lldb::addr_t addr)58880b57cec5SDimitry Andric ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
58890b57cec5SDimitry Andric   ThreadCollectionSP threads;
58900b57cec5SDimitry Andric 
58910b57cec5SDimitry Andric   const MemoryHistorySP &memory_history =
58920b57cec5SDimitry Andric       MemoryHistory::FindPlugin(shared_from_this());
58930b57cec5SDimitry Andric 
58940b57cec5SDimitry Andric   if (!memory_history) {
58950b57cec5SDimitry Andric     return threads;
58960b57cec5SDimitry Andric   }
58970b57cec5SDimitry Andric 
58980b57cec5SDimitry Andric   threads = std::make_shared<ThreadCollection>(
58990b57cec5SDimitry Andric       memory_history->GetHistoryThreads(addr));
59000b57cec5SDimitry Andric 
59010b57cec5SDimitry Andric   return threads;
59020b57cec5SDimitry Andric }
59030b57cec5SDimitry Andric 
59040b57cec5SDimitry Andric InstrumentationRuntimeSP
GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)59050b57cec5SDimitry Andric Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
59060b57cec5SDimitry Andric   InstrumentationRuntimeCollection::iterator pos;
59070b57cec5SDimitry Andric   pos = m_instrumentation_runtimes.find(type);
59080b57cec5SDimitry Andric   if (pos == m_instrumentation_runtimes.end()) {
59090b57cec5SDimitry Andric     return InstrumentationRuntimeSP();
59100b57cec5SDimitry Andric   } else
59110b57cec5SDimitry Andric     return (*pos).second;
59120b57cec5SDimitry Andric }
59130b57cec5SDimitry Andric 
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)59140b57cec5SDimitry Andric bool Process::GetModuleSpec(const FileSpec &module_file_spec,
59150b57cec5SDimitry Andric                             const ArchSpec &arch, ModuleSpec &module_spec) {
59160b57cec5SDimitry Andric   module_spec.Clear();
59170b57cec5SDimitry Andric   return false;
59180b57cec5SDimitry Andric }
59190b57cec5SDimitry Andric 
AddImageToken(lldb::addr_t image_ptr)59200b57cec5SDimitry Andric size_t Process::AddImageToken(lldb::addr_t image_ptr) {
59210b57cec5SDimitry Andric   m_image_tokens.push_back(image_ptr);
59220b57cec5SDimitry Andric   return m_image_tokens.size() - 1;
59230b57cec5SDimitry Andric }
59240b57cec5SDimitry Andric 
GetImagePtrFromToken(size_t token) const59250b57cec5SDimitry Andric lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
59260b57cec5SDimitry Andric   if (token < m_image_tokens.size())
59270b57cec5SDimitry Andric     return m_image_tokens[token];
5928c9157d92SDimitry Andric   return LLDB_INVALID_IMAGE_TOKEN;
59290b57cec5SDimitry Andric }
59300b57cec5SDimitry Andric 
ResetImageToken(size_t token)59310b57cec5SDimitry Andric void Process::ResetImageToken(size_t token) {
59320b57cec5SDimitry Andric   if (token < m_image_tokens.size())
5933c9157d92SDimitry Andric     m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
59340b57cec5SDimitry Andric }
59350b57cec5SDimitry Andric 
59360b57cec5SDimitry Andric Address
AdvanceAddressToNextBranchInstruction(Address default_stop_addr,AddressRange range_bounds)59370b57cec5SDimitry Andric Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
59380b57cec5SDimitry Andric                                                AddressRange range_bounds) {
59390b57cec5SDimitry Andric   Target &target = GetTarget();
59400b57cec5SDimitry Andric   DisassemblerSP disassembler_sp;
59410b57cec5SDimitry Andric   InstructionList *insn_list = nullptr;
59420b57cec5SDimitry Andric 
59430b57cec5SDimitry Andric   Address retval = default_stop_addr;
59440b57cec5SDimitry Andric 
59450b57cec5SDimitry Andric   if (!target.GetUseFastStepping())
59460b57cec5SDimitry Andric     return retval;
59470b57cec5SDimitry Andric   if (!default_stop_addr.IsValid())
59480b57cec5SDimitry Andric     return retval;
59490b57cec5SDimitry Andric 
59500b57cec5SDimitry Andric   const char *plugin_name = nullptr;
59510b57cec5SDimitry Andric   const char *flavor = nullptr;
59520b57cec5SDimitry Andric   disassembler_sp = Disassembler::DisassembleRange(
5953fe6060f1SDimitry Andric       target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds);
59540b57cec5SDimitry Andric   if (disassembler_sp)
59550b57cec5SDimitry Andric     insn_list = &disassembler_sp->GetInstructionList();
59560b57cec5SDimitry Andric 
59570b57cec5SDimitry Andric   if (insn_list == nullptr) {
59580b57cec5SDimitry Andric     return retval;
59590b57cec5SDimitry Andric   }
59600b57cec5SDimitry Andric 
59610b57cec5SDimitry Andric   size_t insn_offset =
59620b57cec5SDimitry Andric       insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
59630b57cec5SDimitry Andric   if (insn_offset == UINT32_MAX) {
59640b57cec5SDimitry Andric     return retval;
59650b57cec5SDimitry Andric   }
59660b57cec5SDimitry Andric 
5967e8d8bef9SDimitry Andric   uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
5968e8d8bef9SDimitry Andric       insn_offset, false /* ignore_calls*/, nullptr);
59690b57cec5SDimitry Andric   if (branch_index == UINT32_MAX) {
59700b57cec5SDimitry Andric     return retval;
59710b57cec5SDimitry Andric   }
59720b57cec5SDimitry Andric 
59730b57cec5SDimitry Andric   if (branch_index > insn_offset) {
59740b57cec5SDimitry Andric     Address next_branch_insn_address =
59750b57cec5SDimitry Andric         insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
59760b57cec5SDimitry Andric     if (next_branch_insn_address.IsValid() &&
59770b57cec5SDimitry Andric         range_bounds.ContainsFileAddress(next_branch_insn_address)) {
59780b57cec5SDimitry Andric       retval = next_branch_insn_address;
59790b57cec5SDimitry Andric     }
59800b57cec5SDimitry Andric   }
59810b57cec5SDimitry Andric 
59820b57cec5SDimitry Andric   return retval;
59830b57cec5SDimitry Andric }
59840b57cec5SDimitry Andric 
GetMemoryRegionInfo(lldb::addr_t load_addr,MemoryRegionInfo & range_info)5985d56accc7SDimitry Andric Status Process::GetMemoryRegionInfo(lldb::addr_t load_addr,
5986d56accc7SDimitry Andric                                     MemoryRegionInfo &range_info) {
5987d56accc7SDimitry Andric   if (const lldb::ABISP &abi = GetABI())
598881ad6265SDimitry Andric     load_addr = abi->FixAnyAddress(load_addr);
5989d56accc7SDimitry Andric   return DoGetMemoryRegionInfo(load_addr, range_info);
5990d56accc7SDimitry Andric }
59910b57cec5SDimitry Andric 
GetMemoryRegions(lldb_private::MemoryRegionInfos & region_list)5992d56accc7SDimitry Andric Status Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
59930b57cec5SDimitry Andric   Status error;
59940b57cec5SDimitry Andric 
59950b57cec5SDimitry Andric   lldb::addr_t range_end = 0;
5996d56accc7SDimitry Andric   const lldb::ABISP &abi = GetABI();
59970b57cec5SDimitry Andric 
59980b57cec5SDimitry Andric   region_list.clear();
59990b57cec5SDimitry Andric   do {
60000b57cec5SDimitry Andric     lldb_private::MemoryRegionInfo region_info;
60010b57cec5SDimitry Andric     error = GetMemoryRegionInfo(range_end, region_info);
60020b57cec5SDimitry Andric     // GetMemoryRegionInfo should only return an error if it is unimplemented.
60030b57cec5SDimitry Andric     if (error.Fail()) {
60040b57cec5SDimitry Andric       region_list.clear();
60050b57cec5SDimitry Andric       break;
60060b57cec5SDimitry Andric     }
60070b57cec5SDimitry Andric 
6008d56accc7SDimitry Andric     // We only check the end address, not start and end, because we assume that
6009d56accc7SDimitry Andric     // the start will not have non-address bits until the first unmappable
6010d56accc7SDimitry Andric     // region. We will have exited the loop by that point because the previous
6011d56accc7SDimitry Andric     // region, the last mappable region, will have non-address bits in its end
6012d56accc7SDimitry Andric     // address.
60130b57cec5SDimitry Andric     range_end = region_info.GetRange().GetRangeEnd();
60140b57cec5SDimitry Andric     if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
60150b57cec5SDimitry Andric       region_list.push_back(std::move(region_info));
60160b57cec5SDimitry Andric     }
6017d56accc7SDimitry Andric   } while (
6018d56accc7SDimitry Andric       // For a process with no non-address bits, all address bits
6019d56accc7SDimitry Andric       // set means the end of memory.
6020d56accc7SDimitry Andric       range_end != LLDB_INVALID_ADDRESS &&
6021d56accc7SDimitry Andric       // If we have non-address bits and some are set then the end
6022d56accc7SDimitry Andric       // is at or beyond the end of mappable memory.
602381ad6265SDimitry Andric       !(abi && (abi->FixAnyAddress(range_end) != range_end)));
60240b57cec5SDimitry Andric 
60250b57cec5SDimitry Andric   return error;
60260b57cec5SDimitry Andric }
60270b57cec5SDimitry Andric 
60280b57cec5SDimitry Andric Status
ConfigureStructuredData(llvm::StringRef type_name,const StructuredData::ObjectSP & config_sp)6029fe013be4SDimitry Andric Process::ConfigureStructuredData(llvm::StringRef type_name,
60300b57cec5SDimitry Andric                                  const StructuredData::ObjectSP &config_sp) {
60310b57cec5SDimitry Andric   // If you get this, the Process-derived class needs to implement a method to
60320b57cec5SDimitry Andric   // enable an already-reported asynchronous structured data feature. See
60330b57cec5SDimitry Andric   // ProcessGDBRemote for an example implementation over gdb-remote.
60340b57cec5SDimitry Andric   return Status("unimplemented");
60350b57cec5SDimitry Andric }
60360b57cec5SDimitry Andric 
MapSupportedStructuredDataPlugins(const StructuredData::Array & supported_type_names)60370b57cec5SDimitry Andric void Process::MapSupportedStructuredDataPlugins(
60380b57cec5SDimitry Andric     const StructuredData::Array &supported_type_names) {
603981ad6265SDimitry Andric   Log *log = GetLog(LLDBLog::Process);
60400b57cec5SDimitry Andric 
60410b57cec5SDimitry Andric   // Bail out early if there are no type names to map.
60420b57cec5SDimitry Andric   if (supported_type_names.GetSize() == 0) {
6043fe013be4SDimitry Andric     LLDB_LOG(log, "no structured data types supported");
60440b57cec5SDimitry Andric     return;
60450b57cec5SDimitry Andric   }
60460b57cec5SDimitry Andric 
6047fe013be4SDimitry Andric   // These StringRefs are backed by the input parameter.
6048fe013be4SDimitry Andric   std::set<llvm::StringRef> type_names;
60490b57cec5SDimitry Andric 
6050fe013be4SDimitry Andric   LLDB_LOG(log,
6051fe013be4SDimitry Andric            "the process supports the following async structured data types:");
60520b57cec5SDimitry Andric 
60530b57cec5SDimitry Andric   supported_type_names.ForEach(
6054fe013be4SDimitry Andric       [&type_names, &log](StructuredData::Object *object) {
6055fe013be4SDimitry Andric         // There shouldn't be null objects in the array.
6056fe013be4SDimitry Andric         if (!object)
60570b57cec5SDimitry Andric           return false;
60580b57cec5SDimitry Andric 
6059fe013be4SDimitry Andric         // All type names should be strings.
6060fe013be4SDimitry Andric         const llvm::StringRef type_name = object->GetStringValue();
6061fe013be4SDimitry Andric         if (type_name.empty())
60620b57cec5SDimitry Andric           return false;
60630b57cec5SDimitry Andric 
6064fe013be4SDimitry Andric         type_names.insert(type_name);
6065fe013be4SDimitry Andric         LLDB_LOG(log, "- {0}", type_name);
60660b57cec5SDimitry Andric         return true;
60670b57cec5SDimitry Andric       });
60680b57cec5SDimitry Andric 
60690b57cec5SDimitry Andric   // For each StructuredDataPlugin, if the plugin handles any of the types in
60700b57cec5SDimitry Andric   // the supported_type_names, map that type name to that plugin. Stop when
60710b57cec5SDimitry Andric   // we've consumed all the type names.
60720b57cec5SDimitry Andric   // FIXME: should we return an error if there are type names nobody
60730b57cec5SDimitry Andric   // supports?
6074fe013be4SDimitry Andric   for (uint32_t plugin_index = 0; !type_names.empty(); plugin_index++) {
60750b57cec5SDimitry Andric     auto create_instance =
60760b57cec5SDimitry Andric         PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
60770b57cec5SDimitry Andric             plugin_index);
60780b57cec5SDimitry Andric     if (!create_instance)
60790b57cec5SDimitry Andric       break;
60800b57cec5SDimitry Andric 
60810b57cec5SDimitry Andric     // Create the plugin.
60820b57cec5SDimitry Andric     StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
60830b57cec5SDimitry Andric     if (!plugin_sp) {
60840b57cec5SDimitry Andric       // This plugin doesn't think it can work with the process. Move on to the
60850b57cec5SDimitry Andric       // next.
60860b57cec5SDimitry Andric       continue;
60870b57cec5SDimitry Andric     }
60880b57cec5SDimitry Andric 
60890b57cec5SDimitry Andric     // For any of the remaining type names, map any that this plugin supports.
6090fe013be4SDimitry Andric     std::vector<llvm::StringRef> names_to_remove;
6091fe013be4SDimitry Andric     for (llvm::StringRef type_name : type_names) {
60920b57cec5SDimitry Andric       if (plugin_sp->SupportsStructuredDataType(type_name)) {
60930b57cec5SDimitry Andric         m_structured_data_plugin_map.insert(
60940b57cec5SDimitry Andric             std::make_pair(type_name, plugin_sp));
60950b57cec5SDimitry Andric         names_to_remove.push_back(type_name);
6096349cc55cSDimitry Andric         LLDB_LOG(log, "using plugin {0} for type name {1}",
6097349cc55cSDimitry Andric                  plugin_sp->GetPluginName(), type_name);
60980b57cec5SDimitry Andric       }
60990b57cec5SDimitry Andric     }
61000b57cec5SDimitry Andric 
61010b57cec5SDimitry Andric     // Remove the type names that were consumed by this plugin.
6102fe013be4SDimitry Andric     for (llvm::StringRef type_name : names_to_remove)
6103fe013be4SDimitry Andric       type_names.erase(type_name);
61040b57cec5SDimitry Andric   }
61050b57cec5SDimitry Andric }
61060b57cec5SDimitry Andric 
RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)61070b57cec5SDimitry Andric bool Process::RouteAsyncStructuredData(
61080b57cec5SDimitry Andric     const StructuredData::ObjectSP object_sp) {
61090b57cec5SDimitry Andric   // Nothing to do if there's no data.
61100b57cec5SDimitry Andric   if (!object_sp)
61110b57cec5SDimitry Andric     return false;
61120b57cec5SDimitry Andric 
61130b57cec5SDimitry Andric   // The contract is this must be a dictionary, so we can look up the routing
61140b57cec5SDimitry Andric   // key via the top-level 'type' string value within the dictionary.
61150b57cec5SDimitry Andric   StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
61160b57cec5SDimitry Andric   if (!dictionary)
61170b57cec5SDimitry Andric     return false;
61180b57cec5SDimitry Andric 
61190b57cec5SDimitry Andric   // Grab the async structured type name (i.e. the feature/plugin name).
6120fe013be4SDimitry Andric   llvm::StringRef type_name;
61210b57cec5SDimitry Andric   if (!dictionary->GetValueForKeyAsString("type", type_name))
61220b57cec5SDimitry Andric     return false;
61230b57cec5SDimitry Andric 
61240b57cec5SDimitry Andric   // Check if there's a plugin registered for this type name.
61250b57cec5SDimitry Andric   auto find_it = m_structured_data_plugin_map.find(type_name);
61260b57cec5SDimitry Andric   if (find_it == m_structured_data_plugin_map.end()) {
61270b57cec5SDimitry Andric     // We don't have a mapping for this structured data type.
61280b57cec5SDimitry Andric     return false;
61290b57cec5SDimitry Andric   }
61300b57cec5SDimitry Andric 
61310b57cec5SDimitry Andric   // Route the structured data to the plugin.
61320b57cec5SDimitry Andric   find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
61330b57cec5SDimitry Andric   return true;
61340b57cec5SDimitry Andric }
61350b57cec5SDimitry Andric 
UpdateAutomaticSignalFiltering()61360b57cec5SDimitry Andric Status Process::UpdateAutomaticSignalFiltering() {
61370b57cec5SDimitry Andric   // Default implementation does nothign.
61380b57cec5SDimitry Andric   // No automatic signal filtering to speak of.
61390b57cec5SDimitry Andric   return Status();
61400b57cec5SDimitry Andric }
61410b57cec5SDimitry Andric 
GetLoadImageUtilityFunction(Platform * platform,llvm::function_ref<std::unique_ptr<UtilityFunction> ()> factory)61420b57cec5SDimitry Andric UtilityFunction *Process::GetLoadImageUtilityFunction(
61430b57cec5SDimitry Andric     Platform *platform,
61440b57cec5SDimitry Andric     llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
61450b57cec5SDimitry Andric   if (platform != GetTarget().GetPlatform().get())
61460b57cec5SDimitry Andric     return nullptr;
61479dba64beSDimitry Andric   llvm::call_once(m_dlopen_utility_func_flag_once,
61480b57cec5SDimitry Andric                   [&] { m_dlopen_utility_func_up = factory(); });
61490b57cec5SDimitry Andric   return m_dlopen_utility_func_up.get();
61500b57cec5SDimitry Andric }
61519dba64beSDimitry Andric 
TraceSupported()6152fe6060f1SDimitry Andric llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6153e8d8bef9SDimitry Andric   if (!IsLiveDebugSession())
6154e8d8bef9SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
6155e8d8bef9SDimitry Andric                                    "Can't trace a non-live process.");
6156e8d8bef9SDimitry Andric   return llvm::make_error<UnimplementedError>();
6157e8d8bef9SDimitry Andric }
6158e8d8bef9SDimitry Andric 
CallVoidArgVoidPtrReturn(const Address * address,addr_t & returned_func,bool trap_exceptions)61599dba64beSDimitry Andric bool Process::CallVoidArgVoidPtrReturn(const Address *address,
61609dba64beSDimitry Andric                                        addr_t &returned_func,
61619dba64beSDimitry Andric                                        bool trap_exceptions) {
61629dba64beSDimitry Andric   Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
61639dba64beSDimitry Andric   if (thread == nullptr || address == nullptr)
61649dba64beSDimitry Andric     return false;
61659dba64beSDimitry Andric 
61669dba64beSDimitry Andric   EvaluateExpressionOptions options;
61679dba64beSDimitry Andric   options.SetStopOthers(true);
61689dba64beSDimitry Andric   options.SetUnwindOnError(true);
61699dba64beSDimitry Andric   options.SetIgnoreBreakpoints(true);
61709dba64beSDimitry Andric   options.SetTryAllThreads(true);
61719dba64beSDimitry Andric   options.SetDebug(false);
61729dba64beSDimitry Andric   options.SetTimeout(GetUtilityExpressionTimeout());
61739dba64beSDimitry Andric   options.SetTrapExceptions(trap_exceptions);
61749dba64beSDimitry Andric 
61759dba64beSDimitry Andric   auto type_system_or_err =
61769dba64beSDimitry Andric       GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
61779dba64beSDimitry Andric   if (!type_system_or_err) {
61789dba64beSDimitry Andric     llvm::consumeError(type_system_or_err.takeError());
61799dba64beSDimitry Andric     return false;
61809dba64beSDimitry Andric   }
6181bdd1243dSDimitry Andric   auto ts = *type_system_or_err;
6182bdd1243dSDimitry Andric   if (!ts)
6183bdd1243dSDimitry Andric     return false;
61849dba64beSDimitry Andric   CompilerType void_ptr_type =
6185bdd1243dSDimitry Andric       ts->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
61869dba64beSDimitry Andric   lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
61879dba64beSDimitry Andric       *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
61889dba64beSDimitry Andric   if (call_plan_sp) {
61899dba64beSDimitry Andric     DiagnosticManager diagnostics;
61909dba64beSDimitry Andric 
61919dba64beSDimitry Andric     StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
61929dba64beSDimitry Andric     if (frame) {
61939dba64beSDimitry Andric       ExecutionContext exe_ctx;
61949dba64beSDimitry Andric       frame->CalculateExecutionContext(exe_ctx);
61959dba64beSDimitry Andric       ExpressionResults result =
61969dba64beSDimitry Andric           RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
61979dba64beSDimitry Andric       if (result == eExpressionCompleted) {
61989dba64beSDimitry Andric         returned_func =
61999dba64beSDimitry Andric             call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
62009dba64beSDimitry Andric                 LLDB_INVALID_ADDRESS);
62019dba64beSDimitry Andric 
62029dba64beSDimitry Andric         if (GetAddressByteSize() == 4) {
62039dba64beSDimitry Andric           if (returned_func == UINT32_MAX)
62049dba64beSDimitry Andric             return false;
62059dba64beSDimitry Andric         } else if (GetAddressByteSize() == 8) {
62069dba64beSDimitry Andric           if (returned_func == UINT64_MAX)
62079dba64beSDimitry Andric             return false;
62089dba64beSDimitry Andric         }
62099dba64beSDimitry Andric         return true;
62109dba64beSDimitry Andric       }
62119dba64beSDimitry Andric     }
62129dba64beSDimitry Andric   }
62139dba64beSDimitry Andric 
62149dba64beSDimitry Andric   return false;
62159dba64beSDimitry Andric }
6216fe6060f1SDimitry Andric 
GetMemoryTagManager()6217fe6060f1SDimitry Andric llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6218fe6060f1SDimitry Andric   Architecture *arch = GetTarget().GetArchitecturePlugin();
6219fe6060f1SDimitry Andric   const MemoryTagManager *tag_manager =
6220fe6060f1SDimitry Andric       arch ? arch->GetMemoryTagManager() : nullptr;
6221fe6060f1SDimitry Andric   if (!arch || !tag_manager) {
6222fe6060f1SDimitry Andric     return llvm::createStringError(
6223fe6060f1SDimitry Andric         llvm::inconvertibleErrorCode(),
6224349cc55cSDimitry Andric         "This architecture does not support memory tagging");
6225fe6060f1SDimitry Andric   }
6226fe6060f1SDimitry Andric 
6227fe6060f1SDimitry Andric   if (!SupportsMemoryTagging()) {
6228fe6060f1SDimitry Andric     return llvm::createStringError(llvm::inconvertibleErrorCode(),
6229fe6060f1SDimitry Andric                                    "Process does not support memory tagging");
6230fe6060f1SDimitry Andric   }
6231fe6060f1SDimitry Andric 
6232fe6060f1SDimitry Andric   return tag_manager;
6233fe6060f1SDimitry Andric }
6234fe6060f1SDimitry Andric 
6235fe6060f1SDimitry Andric llvm::Expected<std::vector<lldb::addr_t>>
ReadMemoryTags(lldb::addr_t addr,size_t len)6236fe6060f1SDimitry Andric Process::ReadMemoryTags(lldb::addr_t addr, size_t len) {
6237fe6060f1SDimitry Andric   llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6238fe6060f1SDimitry Andric       GetMemoryTagManager();
6239fe6060f1SDimitry Andric   if (!tag_manager_or_err)
6240fe6060f1SDimitry Andric     return tag_manager_or_err.takeError();
6241fe6060f1SDimitry Andric 
6242fe6060f1SDimitry Andric   const MemoryTagManager *tag_manager = *tag_manager_or_err;
6243fe6060f1SDimitry Andric   llvm::Expected<std::vector<uint8_t>> tag_data =
6244fe6060f1SDimitry Andric       DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6245fe6060f1SDimitry Andric   if (!tag_data)
6246fe6060f1SDimitry Andric     return tag_data.takeError();
6247fe6060f1SDimitry Andric 
6248fe6060f1SDimitry Andric   return tag_manager->UnpackTagsData(*tag_data,
6249fe6060f1SDimitry Andric                                      len / tag_manager->GetGranuleSize());
6250fe6060f1SDimitry Andric }
6251fe6060f1SDimitry Andric 
WriteMemoryTags(lldb::addr_t addr,size_t len,const std::vector<lldb::addr_t> & tags)6252fe6060f1SDimitry Andric Status Process::WriteMemoryTags(lldb::addr_t addr, size_t len,
6253fe6060f1SDimitry Andric                                 const std::vector<lldb::addr_t> &tags) {
6254fe6060f1SDimitry Andric   llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6255fe6060f1SDimitry Andric       GetMemoryTagManager();
6256fe6060f1SDimitry Andric   if (!tag_manager_or_err)
6257fe6060f1SDimitry Andric     return Status(tag_manager_or_err.takeError());
6258fe6060f1SDimitry Andric 
6259fe6060f1SDimitry Andric   const MemoryTagManager *tag_manager = *tag_manager_or_err;
6260fe6060f1SDimitry Andric   llvm::Expected<std::vector<uint8_t>> packed_tags =
6261fe6060f1SDimitry Andric       tag_manager->PackTags(tags);
6262fe6060f1SDimitry Andric   if (!packed_tags) {
6263fe6060f1SDimitry Andric     return Status(packed_tags.takeError());
6264fe6060f1SDimitry Andric   }
6265fe6060f1SDimitry Andric 
6266fe6060f1SDimitry Andric   return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6267fe6060f1SDimitry Andric                            *packed_tags);
6268fe6060f1SDimitry Andric }
6269c9157d92SDimitry Andric 
6270c9157d92SDimitry Andric // Create a CoreFileMemoryRange from a MemoryRegionInfo
6271c9157d92SDimitry Andric static Process::CoreFileMemoryRange
CreateCoreFileMemoryRange(const MemoryRegionInfo & region)6272c9157d92SDimitry Andric CreateCoreFileMemoryRange(const MemoryRegionInfo &region) {
6273c9157d92SDimitry Andric   const addr_t addr = region.GetRange().GetRangeBase();
6274c9157d92SDimitry Andric   llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());
6275c9157d92SDimitry Andric   return {range, region.GetLLDBPermissions()};
6276c9157d92SDimitry Andric }
6277c9157d92SDimitry Andric 
6278c9157d92SDimitry Andric // Add dirty pages to the core file ranges and return true if dirty pages
6279c9157d92SDimitry Andric // were added. Return false if the dirty page information is not valid or in
6280c9157d92SDimitry Andric // the region.
AddDirtyPages(const MemoryRegionInfo & region,Process::CoreFileMemoryRanges & ranges)6281c9157d92SDimitry Andric static bool AddDirtyPages(const MemoryRegionInfo &region,
6282c9157d92SDimitry Andric                           Process::CoreFileMemoryRanges &ranges) {
6283c9157d92SDimitry Andric   const auto &dirty_page_list = region.GetDirtyPageList();
6284c9157d92SDimitry Andric   if (!dirty_page_list)
6285c9157d92SDimitry Andric     return false;
6286c9157d92SDimitry Andric   const uint32_t lldb_permissions = region.GetLLDBPermissions();
6287c9157d92SDimitry Andric   const addr_t page_size = region.GetPageSize();
6288c9157d92SDimitry Andric   if (page_size == 0)
6289c9157d92SDimitry Andric     return false;
6290c9157d92SDimitry Andric   llvm::AddressRange range(0, 0);
6291c9157d92SDimitry Andric   for (addr_t page_addr : *dirty_page_list) {
6292c9157d92SDimitry Andric     if (range.empty()) {
6293c9157d92SDimitry Andric       // No range yet, initialize the range with the current dirty page.
6294c9157d92SDimitry Andric       range = llvm::AddressRange(page_addr, page_addr + page_size);
6295c9157d92SDimitry Andric     } else {
6296c9157d92SDimitry Andric       if (range.end() == page_addr) {
6297c9157d92SDimitry Andric         // Combine consective ranges.
6298c9157d92SDimitry Andric         range = llvm::AddressRange(range.start(), page_addr + page_size);
6299c9157d92SDimitry Andric       } else {
6300c9157d92SDimitry Andric         // Add previous contiguous range and init the new range with the
6301c9157d92SDimitry Andric         // current dirty page.
6302c9157d92SDimitry Andric         ranges.push_back({range, lldb_permissions});
6303c9157d92SDimitry Andric         range = llvm::AddressRange(page_addr, page_addr + page_size);
6304c9157d92SDimitry Andric       }
6305c9157d92SDimitry Andric     }
6306c9157d92SDimitry Andric   }
6307c9157d92SDimitry Andric   // The last range
6308c9157d92SDimitry Andric   if (!range.empty())
6309c9157d92SDimitry Andric     ranges.push_back({range, lldb_permissions});
6310c9157d92SDimitry Andric   return true;
6311c9157d92SDimitry Andric }
6312c9157d92SDimitry Andric 
6313c9157d92SDimitry Andric // Given a region, add the region to \a ranges.
6314c9157d92SDimitry Andric //
6315c9157d92SDimitry Andric // Only add the region if it isn't empty and if it has some permissions.
6316c9157d92SDimitry Andric // If \a try_dirty_pages is true, then try to add only the dirty pages for a
6317c9157d92SDimitry Andric // given region. If the region has dirty page information, only dirty pages
6318c9157d92SDimitry Andric // will be added to \a ranges, else the entire range will be added to \a
6319c9157d92SDimitry Andric // ranges.
AddRegion(const MemoryRegionInfo & region,bool try_dirty_pages,Process::CoreFileMemoryRanges & ranges)6320c9157d92SDimitry Andric static void AddRegion(const MemoryRegionInfo &region, bool try_dirty_pages,
6321c9157d92SDimitry Andric                       Process::CoreFileMemoryRanges &ranges) {
6322c9157d92SDimitry Andric   // Don't add empty ranges or ranges with no permissions.
6323c9157d92SDimitry Andric   if (region.GetRange().GetByteSize() == 0 || region.GetLLDBPermissions() == 0)
6324c9157d92SDimitry Andric     return;
6325c9157d92SDimitry Andric   if (try_dirty_pages && AddDirtyPages(region, ranges))
6326c9157d92SDimitry Andric     return;
6327c9157d92SDimitry Andric   ranges.push_back(CreateCoreFileMemoryRange(region));
6328c9157d92SDimitry Andric }
6329c9157d92SDimitry Andric 
6330c9157d92SDimitry Andric // Save all memory regions that are not empty or have at least some permissions
6331c9157d92SDimitry Andric // for a full core file style.
GetCoreFileSaveRangesFull(Process & process,const MemoryRegionInfos & regions,Process::CoreFileMemoryRanges & ranges)6332c9157d92SDimitry Andric static void GetCoreFileSaveRangesFull(Process &process,
6333c9157d92SDimitry Andric                                       const MemoryRegionInfos &regions,
6334c9157d92SDimitry Andric                                       Process::CoreFileMemoryRanges &ranges) {
6335c9157d92SDimitry Andric 
6336c9157d92SDimitry Andric   // Don't add only dirty pages, add full regions.
6337c9157d92SDimitry Andric const bool try_dirty_pages = false;
6338c9157d92SDimitry Andric   for (const auto &region : regions)
6339c9157d92SDimitry Andric     AddRegion(region, try_dirty_pages, ranges);
6340c9157d92SDimitry Andric }
6341c9157d92SDimitry Andric 
6342c9157d92SDimitry Andric // Save only the dirty pages to the core file. Make sure the process has at
6343c9157d92SDimitry Andric // least some dirty pages, as some OS versions don't support reporting what
6344c9157d92SDimitry Andric // pages are dirty within an memory region. If no memory regions have dirty
6345c9157d92SDimitry Andric // page information fall back to saving out all ranges with write permissions.
6346c9157d92SDimitry Andric static void
GetCoreFileSaveRangesDirtyOnly(Process & process,const MemoryRegionInfos & regions,Process::CoreFileMemoryRanges & ranges)6347c9157d92SDimitry Andric GetCoreFileSaveRangesDirtyOnly(Process &process,
6348c9157d92SDimitry Andric                                const MemoryRegionInfos &regions,
6349c9157d92SDimitry Andric                                Process::CoreFileMemoryRanges &ranges) {
6350c9157d92SDimitry Andric   // Iterate over the regions and find all dirty pages.
6351c9157d92SDimitry Andric   bool have_dirty_page_info = false;
6352c9157d92SDimitry Andric   for (const auto &region : regions) {
6353c9157d92SDimitry Andric     if (AddDirtyPages(region, ranges))
6354c9157d92SDimitry Andric       have_dirty_page_info = true;
6355c9157d92SDimitry Andric   }
6356c9157d92SDimitry Andric 
6357c9157d92SDimitry Andric   if (!have_dirty_page_info) {
6358c9157d92SDimitry Andric     // We didn't find support for reporting dirty pages from the process
6359c9157d92SDimitry Andric     // plug-in so fall back to any region with write access permissions.
6360c9157d92SDimitry Andric     const bool try_dirty_pages = false;
6361c9157d92SDimitry Andric     for (const auto &region : regions)
6362c9157d92SDimitry Andric       if (region.GetWritable() == MemoryRegionInfo::eYes)
6363c9157d92SDimitry Andric         AddRegion(region, try_dirty_pages, ranges);
6364c9157d92SDimitry Andric   }
6365c9157d92SDimitry Andric }
6366c9157d92SDimitry Andric 
6367c9157d92SDimitry Andric // Save all thread stacks to the core file. Some OS versions support reporting
6368c9157d92SDimitry Andric // when a memory region is stack related. We check on this information, but we
6369c9157d92SDimitry Andric // also use the stack pointers of each thread and add those in case the OS
6370c9157d92SDimitry Andric // doesn't support reporting stack memory. This function also attempts to only
6371c9157d92SDimitry Andric // emit dirty pages from the stack if the memory regions support reporting
6372c9157d92SDimitry Andric // dirty regions as this will make the core file smaller. If the process
6373c9157d92SDimitry Andric // doesn't support dirty regions, then it will fall back to adding the full
6374c9157d92SDimitry Andric // stack region.
6375c9157d92SDimitry Andric static void
GetCoreFileSaveRangesStackOnly(Process & process,const MemoryRegionInfos & regions,Process::CoreFileMemoryRanges & ranges)6376c9157d92SDimitry Andric GetCoreFileSaveRangesStackOnly(Process &process,
6377c9157d92SDimitry Andric                                const MemoryRegionInfos &regions,
6378c9157d92SDimitry Andric                                Process::CoreFileMemoryRanges &ranges) {
6379c9157d92SDimitry Andric   // Some platforms support annotating the region information that tell us that
6380c9157d92SDimitry Andric   // it comes from a thread stack. So look for those regions first.
6381c9157d92SDimitry Andric 
6382c9157d92SDimitry Andric   // Keep track of which stack regions we have added
6383c9157d92SDimitry Andric   std::set<addr_t> stack_bases;
6384c9157d92SDimitry Andric 
6385c9157d92SDimitry Andric   const bool try_dirty_pages = true;
6386c9157d92SDimitry Andric   for (const auto &region : regions) {
6387c9157d92SDimitry Andric     if (region.IsStackMemory() == MemoryRegionInfo::eYes) {
6388c9157d92SDimitry Andric       stack_bases.insert(region.GetRange().GetRangeBase());
6389c9157d92SDimitry Andric       AddRegion(region, try_dirty_pages, ranges);
6390c9157d92SDimitry Andric     }
6391c9157d92SDimitry Andric   }
6392c9157d92SDimitry Andric 
6393c9157d92SDimitry Andric   // Also check with our threads and get the regions for their stack pointers
6394c9157d92SDimitry Andric   // and add those regions if not already added above.
6395c9157d92SDimitry Andric   for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {
6396c9157d92SDimitry Andric     if (!thread_sp)
6397c9157d92SDimitry Andric       continue;
6398c9157d92SDimitry Andric     StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
6399c9157d92SDimitry Andric     if (!frame_sp)
6400c9157d92SDimitry Andric       continue;
6401c9157d92SDimitry Andric     RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();
6402c9157d92SDimitry Andric     if (!reg_ctx_sp)
6403c9157d92SDimitry Andric       continue;
6404c9157d92SDimitry Andric     const addr_t sp = reg_ctx_sp->GetSP();
6405c9157d92SDimitry Andric     lldb_private::MemoryRegionInfo sp_region;
6406c9157d92SDimitry Andric     if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {
6407c9157d92SDimitry Andric       // Only add this region if not already added above. If our stack pointer
6408c9157d92SDimitry Andric       // is pointing off in the weeds, we will want this range.
6409c9157d92SDimitry Andric       if (stack_bases.count(sp_region.GetRange().GetRangeBase()) == 0)
6410c9157d92SDimitry Andric         AddRegion(sp_region, try_dirty_pages, ranges);
6411c9157d92SDimitry Andric     }
6412c9157d92SDimitry Andric   }
6413c9157d92SDimitry Andric }
6414c9157d92SDimitry Andric 
CalculateCoreFileSaveRanges(lldb::SaveCoreStyle core_style,CoreFileMemoryRanges & ranges)6415c9157d92SDimitry Andric Status Process::CalculateCoreFileSaveRanges(lldb::SaveCoreStyle core_style,
6416c9157d92SDimitry Andric                                             CoreFileMemoryRanges &ranges) {
6417c9157d92SDimitry Andric   lldb_private::MemoryRegionInfos regions;
6418c9157d92SDimitry Andric   Status err = GetMemoryRegions(regions);
6419c9157d92SDimitry Andric   if (err.Fail())
6420c9157d92SDimitry Andric     return err;
6421c9157d92SDimitry Andric   if (regions.empty())
6422c9157d92SDimitry Andric     return Status("failed to get any valid memory regions from the process");
6423c9157d92SDimitry Andric 
6424c9157d92SDimitry Andric   switch (core_style) {
6425c9157d92SDimitry Andric   case eSaveCoreUnspecified:
6426c9157d92SDimitry Andric     err = Status("callers must set the core_style to something other than "
6427c9157d92SDimitry Andric                  "eSaveCoreUnspecified");
6428c9157d92SDimitry Andric     break;
6429c9157d92SDimitry Andric 
6430c9157d92SDimitry Andric   case eSaveCoreFull:
6431c9157d92SDimitry Andric     GetCoreFileSaveRangesFull(*this, regions, ranges);
6432c9157d92SDimitry Andric     break;
6433c9157d92SDimitry Andric 
6434c9157d92SDimitry Andric   case eSaveCoreDirtyOnly:
6435c9157d92SDimitry Andric     GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges);
6436c9157d92SDimitry Andric     break;
6437c9157d92SDimitry Andric 
6438c9157d92SDimitry Andric   case eSaveCoreStackOnly:
6439c9157d92SDimitry Andric     GetCoreFileSaveRangesStackOnly(*this, regions, ranges);
6440c9157d92SDimitry Andric     break;
6441c9157d92SDimitry Andric   }
6442c9157d92SDimitry Andric 
6443c9157d92SDimitry Andric   if (err.Fail())
6444c9157d92SDimitry Andric     return err;
6445c9157d92SDimitry Andric 
6446c9157d92SDimitry Andric   if (ranges.empty())
6447c9157d92SDimitry Andric     return Status("no valid address ranges found for core style");
6448c9157d92SDimitry Andric 
6449c9157d92SDimitry Andric   return Status(); // Success!
6450c9157d92SDimitry Andric }
6451