1 //===-- Process.cpp -------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <atomic>
10 #include <memory>
11 #include <mutex>
12 
13 #include "llvm/Support/ScopedPrinter.h"
14 #include "llvm/Support/Threading.h"
15 
16 #include "lldb/Breakpoint/BreakpointLocation.h"
17 #include "lldb/Breakpoint/StoppointCallbackContext.h"
18 #include "lldb/Core/Debugger.h"
19 #include "lldb/Core/Module.h"
20 #include "lldb/Core/ModuleSpec.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Core/StreamFile.h"
23 #include "lldb/Expression/DiagnosticManager.h"
24 #include "lldb/Expression/DynamicCheckerFunctions.h"
25 #include "lldb/Expression/UserExpression.h"
26 #include "lldb/Expression/UtilityFunction.h"
27 #include "lldb/Host/ConnectionFileDescriptor.h"
28 #include "lldb/Host/FileSystem.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Host/HostInfo.h"
31 #include "lldb/Host/OptionParser.h"
32 #include "lldb/Host/Pipe.h"
33 #include "lldb/Host/Terminal.h"
34 #include "lldb/Host/ThreadLauncher.h"
35 #include "lldb/Interpreter/CommandInterpreter.h"
36 #include "lldb/Interpreter/OptionArgParser.h"
37 #include "lldb/Interpreter/OptionValueProperties.h"
38 #include "lldb/Symbol/Function.h"
39 #include "lldb/Symbol/Symbol.h"
40 #include "lldb/Target/ABI.h"
41 #include "lldb/Target/AssertFrameRecognizer.h"
42 #include "lldb/Target/DynamicLoader.h"
43 #include "lldb/Target/InstrumentationRuntime.h"
44 #include "lldb/Target/JITLoader.h"
45 #include "lldb/Target/JITLoaderList.h"
46 #include "lldb/Target/Language.h"
47 #include "lldb/Target/LanguageRuntime.h"
48 #include "lldb/Target/MemoryHistory.h"
49 #include "lldb/Target/MemoryRegionInfo.h"
50 #include "lldb/Target/OperatingSystem.h"
51 #include "lldb/Target/Platform.h"
52 #include "lldb/Target/Process.h"
53 #include "lldb/Target/RegisterContext.h"
54 #include "lldb/Target/StopInfo.h"
55 #include "lldb/Target/StructuredDataPlugin.h"
56 #include "lldb/Target/SystemRuntime.h"
57 #include "lldb/Target/Target.h"
58 #include "lldb/Target/TargetList.h"
59 #include "lldb/Target/Thread.h"
60 #include "lldb/Target/ThreadPlan.h"
61 #include "lldb/Target/ThreadPlanBase.h"
62 #include "lldb/Target/ThreadPlanCallFunction.h"
63 #include "lldb/Target/ThreadPlanStack.h"
64 #include "lldb/Target/UnixSignals.h"
65 #include "lldb/Utility/Event.h"
66 #include "lldb/Utility/Log.h"
67 #include "lldb/Utility/NameMatches.h"
68 #include "lldb/Utility/ProcessInfo.h"
69 #include "lldb/Utility/SelectHelper.h"
70 #include "lldb/Utility/State.h"
71 
72 using namespace lldb;
73 using namespace lldb_private;
74 using namespace std::chrono;
75 
76 // Comment out line below to disable memory caching, overriding the process
77 // setting target.process.disable-memory-cache
78 #define ENABLE_MEMORY_CACHING
79 
80 #ifdef ENABLE_MEMORY_CACHING
81 #define DISABLE_MEM_CACHE_DEFAULT false
82 #else
83 #define DISABLE_MEM_CACHE_DEFAULT true
84 #endif
85 
86 class ProcessOptionValueProperties : public OptionValueProperties {
87 public:
88   ProcessOptionValueProperties(ConstString name)
89       : OptionValueProperties(name) {}
90 
91   // This constructor is used when creating ProcessOptionValueProperties when
92   // it is part of a new lldb_private::Process instance. It will copy all
93   // current global property values as needed
94   ProcessOptionValueProperties(ProcessProperties *global_properties)
95       : OptionValueProperties(*global_properties->GetValueProperties()) {}
96 
97   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
98                                      bool will_modify,
99                                      uint32_t idx) const override {
100     // When getting the value for a key from the process options, we will
101     // always try and grab the setting from the current process if there is
102     // one. Else we just use the one from this instance.
103     if (exe_ctx) {
104       Process *process = exe_ctx->GetProcessPtr();
105       if (process) {
106         ProcessOptionValueProperties *instance_properties =
107             static_cast<ProcessOptionValueProperties *>(
108                 process->GetValueProperties().get());
109         if (this != instance_properties)
110           return instance_properties->ProtectedGetPropertyAtIndex(idx);
111       }
112     }
113     return ProtectedGetPropertyAtIndex(idx);
114   }
115 };
116 
117 #define LLDB_PROPERTIES_process
118 #include "TargetProperties.inc"
119 
120 enum {
121 #define LLDB_PROPERTIES_process
122 #include "TargetPropertiesEnum.inc"
123 };
124 
125 ProcessProperties::ProcessProperties(lldb_private::Process *process)
126     : Properties(),
127       m_process(process) // Can be nullptr for global ProcessProperties
128 {
129   if (process == nullptr) {
130     // Global process properties, set them up one time
131     m_collection_sp =
132         std::make_shared<ProcessOptionValueProperties>(ConstString("process"));
133     m_collection_sp->Initialize(g_process_properties);
134     m_collection_sp->AppendProperty(
135         ConstString("thread"), ConstString("Settings specific to threads."),
136         true, Thread::GetGlobalProperties()->GetValueProperties());
137   } else {
138     m_collection_sp = std::make_shared<ProcessOptionValueProperties>(
139         Process::GetGlobalProperties().get());
140     m_collection_sp->SetValueChangedCallback(
141         ePropertyPythonOSPluginPath,
142         [this] { m_process->LoadOperatingSystemPlugin(true); });
143   }
144 }
145 
146 ProcessProperties::~ProcessProperties() = default;
147 
148 bool ProcessProperties::GetDisableMemoryCache() const {
149   const uint32_t idx = ePropertyDisableMemCache;
150   return m_collection_sp->GetPropertyAtIndexAsBoolean(
151       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
152 }
153 
154 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
155   const uint32_t idx = ePropertyMemCacheLineSize;
156   return m_collection_sp->GetPropertyAtIndexAsUInt64(
157       nullptr, idx, g_process_properties[idx].default_uint_value);
158 }
159 
160 Args ProcessProperties::GetExtraStartupCommands() const {
161   Args args;
162   const uint32_t idx = ePropertyExtraStartCommand;
163   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
164   return args;
165 }
166 
167 void ProcessProperties::SetExtraStartupCommands(const Args &args) {
168   const uint32_t idx = ePropertyExtraStartCommand;
169   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
170 }
171 
172 FileSpec ProcessProperties::GetPythonOSPluginPath() const {
173   const uint32_t idx = ePropertyPythonOSPluginPath;
174   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
175 }
176 
177 void ProcessProperties::SetPythonOSPluginPath(const FileSpec &file) {
178   const uint32_t idx = ePropertyPythonOSPluginPath;
179   m_collection_sp->SetPropertyAtIndexAsFileSpec(nullptr, idx, file);
180 }
181 
182 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
183   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
184   return m_collection_sp->GetPropertyAtIndexAsBoolean(
185       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
186 }
187 
188 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore) {
189   const uint32_t idx = ePropertyIgnoreBreakpointsInExpressions;
190   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
191 }
192 
193 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
194   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
195   return m_collection_sp->GetPropertyAtIndexAsBoolean(
196       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
197 }
198 
199 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore) {
200   const uint32_t idx = ePropertyUnwindOnErrorInExpressions;
201   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, ignore);
202 }
203 
204 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
205   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
206   return m_collection_sp->GetPropertyAtIndexAsBoolean(
207       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
208 }
209 
210 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop) {
211   const uint32_t idx = ePropertyStopOnSharedLibraryEvents;
212   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
213 }
214 
215 bool ProcessProperties::GetDetachKeepsStopped() const {
216   const uint32_t idx = ePropertyDetachKeepsStopped;
217   return m_collection_sp->GetPropertyAtIndexAsBoolean(
218       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
219 }
220 
221 void ProcessProperties::SetDetachKeepsStopped(bool stop) {
222   const uint32_t idx = ePropertyDetachKeepsStopped;
223   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, stop);
224 }
225 
226 bool ProcessProperties::GetWarningsOptimization() const {
227   const uint32_t idx = ePropertyWarningOptimization;
228   return m_collection_sp->GetPropertyAtIndexAsBoolean(
229       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
230 }
231 
232 bool ProcessProperties::GetStopOnExec() const {
233   const uint32_t idx = ePropertyStopOnExec;
234   return m_collection_sp->GetPropertyAtIndexAsBoolean(
235       nullptr, idx, g_process_properties[idx].default_uint_value != 0);
236 }
237 
238 std::chrono::seconds ProcessProperties::GetUtilityExpressionTimeout() const {
239   const uint32_t idx = ePropertyUtilityExpressionTimeout;
240   uint64_t value = m_collection_sp->GetPropertyAtIndexAsUInt64(
241       nullptr, idx, g_process_properties[idx].default_uint_value);
242   return std::chrono::seconds(value);
243 }
244 
245 Status ProcessLaunchCommandOptions::SetOptionValue(
246     uint32_t option_idx, llvm::StringRef option_arg,
247     ExecutionContext *execution_context) {
248   Status error;
249   const int short_option = m_getopt_table[option_idx].val;
250 
251   switch (short_option) {
252   case 's': // Stop at program entry point
253     launch_info.GetFlags().Set(eLaunchFlagStopAtEntry);
254     break;
255 
256   case 'i': // STDIN for read only
257   {
258     FileAction action;
259     if (action.Open(STDIN_FILENO, FileSpec(option_arg), true, false))
260       launch_info.AppendFileAction(action);
261     break;
262   }
263 
264   case 'o': // Open STDOUT for write only
265   {
266     FileAction action;
267     if (action.Open(STDOUT_FILENO, FileSpec(option_arg), false, true))
268       launch_info.AppendFileAction(action);
269     break;
270   }
271 
272   case 'e': // STDERR for write only
273   {
274     FileAction action;
275     if (action.Open(STDERR_FILENO, FileSpec(option_arg), false, true))
276       launch_info.AppendFileAction(action);
277     break;
278   }
279 
280   case 'p': // Process plug-in name
281     launch_info.SetProcessPluginName(option_arg);
282     break;
283 
284   case 'n': // Disable STDIO
285   {
286     FileAction action;
287     const FileSpec dev_null(FileSystem::DEV_NULL);
288     if (action.Open(STDIN_FILENO, dev_null, true, false))
289       launch_info.AppendFileAction(action);
290     if (action.Open(STDOUT_FILENO, dev_null, false, true))
291       launch_info.AppendFileAction(action);
292     if (action.Open(STDERR_FILENO, dev_null, false, true))
293       launch_info.AppendFileAction(action);
294     break;
295   }
296 
297   case 'w':
298     launch_info.SetWorkingDirectory(FileSpec(option_arg));
299     break;
300 
301   case 't': // Open process in new terminal window
302     launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
303     break;
304 
305   case 'a': {
306     TargetSP target_sp =
307         execution_context ? execution_context->GetTargetSP() : TargetSP();
308     PlatformSP platform_sp =
309         target_sp ? target_sp->GetPlatform() : PlatformSP();
310     launch_info.GetArchitecture() =
311         Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
312   } break;
313 
314   case 'A': // Disable ASLR.
315   {
316     bool success;
317     const bool disable_aslr_arg =
318         OptionArgParser::ToBoolean(option_arg, true, &success);
319     if (success)
320       disable_aslr = disable_aslr_arg ? eLazyBoolYes : eLazyBoolNo;
321     else
322       error.SetErrorStringWithFormat(
323           "Invalid boolean value for disable-aslr option: '%s'",
324           option_arg.empty() ? "<null>" : option_arg.str().c_str());
325     break;
326   }
327 
328   case 'X': // shell expand args.
329   {
330     bool success;
331     const bool expand_args =
332         OptionArgParser::ToBoolean(option_arg, true, &success);
333     if (success)
334       launch_info.SetShellExpandArguments(expand_args);
335     else
336       error.SetErrorStringWithFormat(
337           "Invalid boolean value for shell-expand-args option: '%s'",
338           option_arg.empty() ? "<null>" : option_arg.str().c_str());
339     break;
340   }
341 
342   case 'c':
343     if (!option_arg.empty())
344       launch_info.SetShell(FileSpec(option_arg));
345     else
346       launch_info.SetShell(HostInfo::GetDefaultShell());
347     break;
348 
349   case 'v':
350     launch_info.GetEnvironment().insert(option_arg);
351     break;
352 
353   default:
354     error.SetErrorStringWithFormat("unrecognized short option character '%c'",
355                                    short_option);
356     break;
357   }
358   return error;
359 }
360 
361 static constexpr OptionDefinition g_process_launch_options[] = {
362     {LLDB_OPT_SET_ALL, false, "stop-at-entry", 's', OptionParser::eNoArgument,
363      nullptr, {}, 0, eArgTypeNone,
364      "Stop at the entry point of the program when launching a process."},
365     {LLDB_OPT_SET_ALL, false, "disable-aslr", 'A',
366      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
367      "Set whether to disable address space layout randomization when launching "
368      "a process."},
369     {LLDB_OPT_SET_ALL, false, "plugin", 'p', OptionParser::eRequiredArgument,
370      nullptr, {}, 0, eArgTypePlugin,
371      "Name of the process plugin you want to use."},
372     {LLDB_OPT_SET_ALL, false, "working-dir", 'w',
373      OptionParser::eRequiredArgument, nullptr, {}, 0,
374      eArgTypeDirectoryName,
375      "Set the current working directory to <path> when running the inferior."},
376     {LLDB_OPT_SET_ALL, false, "arch", 'a', OptionParser::eRequiredArgument,
377      nullptr, {}, 0, eArgTypeArchitecture,
378      "Set the architecture for the process to launch when ambiguous."},
379     {LLDB_OPT_SET_ALL, false, "environment", 'v',
380      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeNone,
381      "Specify an environment variable name/value string (--environment "
382      "NAME=VALUE). Can be specified multiple times for subsequent environment "
383      "entries."},
384     {LLDB_OPT_SET_1 | LLDB_OPT_SET_2 | LLDB_OPT_SET_3, false, "shell", 'c',
385      OptionParser::eOptionalArgument, nullptr, {}, 0, eArgTypeFilename,
386      "Run the process in a shell (not supported on all platforms)."},
387 
388     {LLDB_OPT_SET_1, false, "stdin", 'i', OptionParser::eRequiredArgument,
389      nullptr, {}, 0, eArgTypeFilename,
390      "Redirect stdin for the process to <filename>."},
391     {LLDB_OPT_SET_1, false, "stdout", 'o', OptionParser::eRequiredArgument,
392      nullptr, {}, 0, eArgTypeFilename,
393      "Redirect stdout for the process to <filename>."},
394     {LLDB_OPT_SET_1, false, "stderr", 'e', OptionParser::eRequiredArgument,
395      nullptr, {}, 0, eArgTypeFilename,
396      "Redirect stderr for the process to <filename>."},
397 
398     {LLDB_OPT_SET_2, false, "tty", 't', OptionParser::eNoArgument, nullptr,
399      {}, 0, eArgTypeNone,
400      "Start the process in a terminal (not supported on all platforms)."},
401 
402     {LLDB_OPT_SET_3, false, "no-stdio", 'n', OptionParser::eNoArgument, nullptr,
403      {}, 0, eArgTypeNone,
404      "Do not set up for terminal I/O to go to running process."},
405     {LLDB_OPT_SET_4, false, "shell-expand-args", 'X',
406      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
407      "Set whether to shell expand arguments to the process when launching."},
408 };
409 
410 llvm::ArrayRef<OptionDefinition> ProcessLaunchCommandOptions::GetDefinitions() {
411   return llvm::makeArrayRef(g_process_launch_options);
412 }
413 
414 ProcessSP Process::FindPlugin(lldb::TargetSP target_sp,
415                               llvm::StringRef plugin_name,
416                               ListenerSP listener_sp,
417                               const FileSpec *crash_file_path) {
418   static uint32_t g_process_unique_id = 0;
419 
420   ProcessSP process_sp;
421   ProcessCreateInstance create_callback = nullptr;
422   if (!plugin_name.empty()) {
423     ConstString const_plugin_name(plugin_name);
424     create_callback =
425         PluginManager::GetProcessCreateCallbackForPluginName(const_plugin_name);
426     if (create_callback) {
427       process_sp = create_callback(target_sp, listener_sp, crash_file_path);
428       if (process_sp) {
429         if (process_sp->CanDebug(target_sp, true)) {
430           process_sp->m_process_unique_id = ++g_process_unique_id;
431         } else
432           process_sp.reset();
433       }
434     }
435   } else {
436     for (uint32_t idx = 0;
437          (create_callback =
438               PluginManager::GetProcessCreateCallbackAtIndex(idx)) != nullptr;
439          ++idx) {
440       process_sp = create_callback(target_sp, listener_sp, crash_file_path);
441       if (process_sp) {
442         if (process_sp->CanDebug(target_sp, false)) {
443           process_sp->m_process_unique_id = ++g_process_unique_id;
444           break;
445         } else
446           process_sp.reset();
447       }
448     }
449   }
450   return process_sp;
451 }
452 
453 ConstString &Process::GetStaticBroadcasterClass() {
454   static ConstString class_name("lldb.process");
455   return class_name;
456 }
457 
458 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp)
459     : Process(target_sp, listener_sp,
460               UnixSignals::Create(HostInfo::GetArchitecture())) {
461   // This constructor just delegates to the full Process constructor,
462   // defaulting to using the Host's UnixSignals.
463 }
464 
465 Process::Process(lldb::TargetSP target_sp, ListenerSP listener_sp,
466                  const UnixSignalsSP &unix_signals_sp)
467     : ProcessProperties(this), UserID(LLDB_INVALID_PROCESS_ID),
468       Broadcaster((target_sp->GetDebugger().GetBroadcasterManager()),
469                   Process::GetStaticBroadcasterClass().AsCString()),
470       m_target_wp(target_sp), m_public_state(eStateUnloaded),
471       m_private_state(eStateUnloaded),
472       m_private_state_broadcaster(nullptr,
473                                   "lldb.process.internal_state_broadcaster"),
474       m_private_state_control_broadcaster(
475           nullptr, "lldb.process.internal_state_control_broadcaster"),
476       m_private_state_listener_sp(
477           Listener::MakeListener("lldb.process.internal_state_listener")),
478       m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
479       m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
480       m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
481       m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
482       m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
483       m_notifications(), m_image_tokens(), m_listener_sp(listener_sp),
484       m_breakpoint_site_list(), m_dynamic_checkers_up(),
485       m_unix_signals_sp(unix_signals_sp), m_abi_sp(), m_process_input_reader(),
486       m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
487       m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
488       m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
489       m_memory_cache(*this), m_allocated_memory_cache(*this),
490       m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
491       m_private_run_lock(), m_finalizing(false), m_finalize_called(false),
492       m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
493       m_last_broadcast_state(eStateInvalid), m_destroy_in_process(false),
494       m_can_interpret_function_calls(false), m_warnings_issued(),
495       m_run_thread_plan_lock(), m_can_jit(eCanJITDontKnow) {
496   CheckInWithManager();
497 
498   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
499   LLDB_LOGF(log, "%p Process::Process()", static_cast<void *>(this));
500 
501   if (!m_unix_signals_sp)
502     m_unix_signals_sp = std::make_shared<UnixSignals>();
503 
504   SetEventName(eBroadcastBitStateChanged, "state-changed");
505   SetEventName(eBroadcastBitInterrupt, "interrupt");
506   SetEventName(eBroadcastBitSTDOUT, "stdout-available");
507   SetEventName(eBroadcastBitSTDERR, "stderr-available");
508   SetEventName(eBroadcastBitProfileData, "profile-data-available");
509   SetEventName(eBroadcastBitStructuredData, "structured-data-available");
510 
511   m_private_state_control_broadcaster.SetEventName(
512       eBroadcastInternalStateControlStop, "control-stop");
513   m_private_state_control_broadcaster.SetEventName(
514       eBroadcastInternalStateControlPause, "control-pause");
515   m_private_state_control_broadcaster.SetEventName(
516       eBroadcastInternalStateControlResume, "control-resume");
517 
518   m_listener_sp->StartListeningForEvents(
519       this, eBroadcastBitStateChanged | eBroadcastBitInterrupt |
520                 eBroadcastBitSTDOUT | eBroadcastBitSTDERR |
521                 eBroadcastBitProfileData | eBroadcastBitStructuredData);
522 
523   m_private_state_listener_sp->StartListeningForEvents(
524       &m_private_state_broadcaster,
525       eBroadcastBitStateChanged | eBroadcastBitInterrupt);
526 
527   m_private_state_listener_sp->StartListeningForEvents(
528       &m_private_state_control_broadcaster,
529       eBroadcastInternalStateControlStop | eBroadcastInternalStateControlPause |
530           eBroadcastInternalStateControlResume);
531   // We need something valid here, even if just the default UnixSignalsSP.
532   assert(m_unix_signals_sp && "null m_unix_signals_sp after initialization");
533 
534   // Allow the platform to override the default cache line size
535   OptionValueSP value_sp =
536       m_collection_sp
537           ->GetPropertyAtIndex(nullptr, true, ePropertyMemCacheLineSize)
538           ->GetValue();
539   uint32_t platform_cache_line_size =
540       target_sp->GetPlatform()->GetDefaultMemoryCacheLineSize();
541   if (!value_sp->OptionWasSet() && platform_cache_line_size != 0)
542     value_sp->SetUInt64Value(platform_cache_line_size);
543 
544   RegisterAssertFrameRecognizer(this);
545 }
546 
547 Process::~Process() {
548   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
549   LLDB_LOGF(log, "%p Process::~Process()", static_cast<void *>(this));
550   StopPrivateStateThread();
551 
552   // ThreadList::Clear() will try to acquire this process's mutex, so
553   // explicitly clear the thread list here to ensure that the mutex is not
554   // destroyed before the thread list.
555   m_thread_list.Clear();
556 }
557 
558 const ProcessPropertiesSP &Process::GetGlobalProperties() {
559   // NOTE: intentional leak so we don't crash if global destructor chain gets
560   // called as other threads still use the result of this function
561   static ProcessPropertiesSP *g_settings_sp_ptr =
562       new ProcessPropertiesSP(new ProcessProperties(nullptr));
563   return *g_settings_sp_ptr;
564 }
565 
566 void Process::Finalize() {
567   m_finalizing = true;
568 
569   // Destroy this process if needed
570   switch (GetPrivateState()) {
571   case eStateConnected:
572   case eStateAttaching:
573   case eStateLaunching:
574   case eStateStopped:
575   case eStateRunning:
576   case eStateStepping:
577   case eStateCrashed:
578   case eStateSuspended:
579     Destroy(false);
580     break;
581 
582   case eStateInvalid:
583   case eStateUnloaded:
584   case eStateDetached:
585   case eStateExited:
586     break;
587   }
588 
589   // Clear our broadcaster before we proceed with destroying
590   Broadcaster::Clear();
591 
592   // Do any cleanup needed prior to being destructed... Subclasses that
593   // override this method should call this superclass method as well.
594 
595   // We need to destroy the loader before the derived Process class gets
596   // destroyed since it is very likely that undoing the loader will require
597   // access to the real process.
598   m_dynamic_checkers_up.reset();
599   m_abi_sp.reset();
600   m_os_up.reset();
601   m_system_runtime_up.reset();
602   m_dyld_up.reset();
603   m_jit_loaders_up.reset();
604   m_thread_plans.Clear();
605   m_thread_list_real.Destroy();
606   m_thread_list.Destroy();
607   m_extended_thread_list.Destroy();
608   m_queue_list.Clear();
609   m_queue_list_stop_id = 0;
610   std::vector<Notifications> empty_notifications;
611   m_notifications.swap(empty_notifications);
612   m_image_tokens.clear();
613   m_memory_cache.Clear();
614   m_allocated_memory_cache.Clear();
615   {
616     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
617     m_language_runtimes.clear();
618   }
619   m_instrumentation_runtimes.clear();
620   m_next_event_action_up.reset();
621   // Clear the last natural stop ID since it has a strong reference to this
622   // process
623   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
624   //#ifdef LLDB_CONFIGURATION_DEBUG
625   //    StreamFile s(stdout, false);
626   //    EventSP event_sp;
627   //    while (m_private_state_listener_sp->GetNextEvent(event_sp))
628   //    {
629   //        event_sp->Dump (&s);
630   //        s.EOL();
631   //    }
632   //#endif
633   // We have to be very careful here as the m_private_state_listener might
634   // contain events that have ProcessSP values in them which can keep this
635   // process around forever. These events need to be cleared out.
636   m_private_state_listener_sp->Clear();
637   m_public_run_lock.TrySetRunning(); // This will do nothing if already locked
638   m_public_run_lock.SetStopped();
639   m_private_run_lock.TrySetRunning(); // This will do nothing if already locked
640   m_private_run_lock.SetStopped();
641   m_structured_data_plugin_map.clear();
642   m_finalize_called = true;
643 }
644 
645 void Process::RegisterNotificationCallbacks(const Notifications &callbacks) {
646   m_notifications.push_back(callbacks);
647   if (callbacks.initialize != nullptr)
648     callbacks.initialize(callbacks.baton, this);
649 }
650 
651 bool Process::UnregisterNotificationCallbacks(const Notifications &callbacks) {
652   std::vector<Notifications>::iterator pos, end = m_notifications.end();
653   for (pos = m_notifications.begin(); pos != end; ++pos) {
654     if (pos->baton == callbacks.baton &&
655         pos->initialize == callbacks.initialize &&
656         pos->process_state_changed == callbacks.process_state_changed) {
657       m_notifications.erase(pos);
658       return true;
659     }
660   }
661   return false;
662 }
663 
664 void Process::SynchronouslyNotifyStateChanged(StateType state) {
665   std::vector<Notifications>::iterator notification_pos,
666       notification_end = m_notifications.end();
667   for (notification_pos = m_notifications.begin();
668        notification_pos != notification_end; ++notification_pos) {
669     if (notification_pos->process_state_changed)
670       notification_pos->process_state_changed(notification_pos->baton, this,
671                                               state);
672   }
673 }
674 
675 // FIXME: We need to do some work on events before the general Listener sees
676 // them.
677 // For instance if we are continuing from a breakpoint, we need to ensure that
678 // we do the little "insert real insn, step & stop" trick.  But we can't do
679 // that when the event is delivered by the broadcaster - since that is done on
680 // the thread that is waiting for new events, so if we needed more than one
681 // event for our handling, we would stall.  So instead we do it when we fetch
682 // the event off of the queue.
683 //
684 
685 StateType Process::GetNextEvent(EventSP &event_sp) {
686   StateType state = eStateInvalid;
687 
688   if (m_listener_sp->GetEventForBroadcaster(this, event_sp,
689                                             std::chrono::seconds(0)) &&
690       event_sp)
691     state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
692 
693   return state;
694 }
695 
696 void Process::SyncIOHandler(uint32_t iohandler_id,
697                             const Timeout<std::micro> &timeout) {
698   // don't sync (potentially context switch) in case where there is no process
699   // IO
700   if (!m_process_input_reader)
701     return;
702 
703   auto Result = m_iohandler_sync.WaitForValueNotEqualTo(iohandler_id, timeout);
704 
705   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
706   if (Result) {
707     LLDB_LOG(
708         log,
709         "waited from m_iohandler_sync to change from {0}. New value is {1}.",
710         iohandler_id, *Result);
711   } else {
712     LLDB_LOG(log, "timed out waiting for m_iohandler_sync to change from {0}.",
713              iohandler_id);
714   }
715 }
716 
717 StateType Process::WaitForProcessToStop(const Timeout<std::micro> &timeout,
718                                         EventSP *event_sp_ptr, bool wait_always,
719                                         ListenerSP hijack_listener_sp,
720                                         Stream *stream, bool use_run_lock) {
721   // We can't just wait for a "stopped" event, because the stopped event may
722   // have restarted the target. We have to actually check each event, and in
723   // the case of a stopped event check the restarted flag on the event.
724   if (event_sp_ptr)
725     event_sp_ptr->reset();
726   StateType state = GetState();
727   // If we are exited or detached, we won't ever get back to any other valid
728   // state...
729   if (state == eStateDetached || state == eStateExited)
730     return state;
731 
732   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
733   LLDB_LOG(log, "timeout = {0}", timeout);
734 
735   if (!wait_always && StateIsStoppedState(state, true) &&
736       StateIsStoppedState(GetPrivateState(), true)) {
737     LLDB_LOGF(log,
738               "Process::%s returning without waiting for events; process "
739               "private and public states are already 'stopped'.",
740               __FUNCTION__);
741     // We need to toggle the run lock as this won't get done in
742     // SetPublicState() if the process is hijacked.
743     if (hijack_listener_sp && use_run_lock)
744       m_public_run_lock.SetStopped();
745     return state;
746   }
747 
748   while (state != eStateInvalid) {
749     EventSP event_sp;
750     state = GetStateChangedEvents(event_sp, timeout, hijack_listener_sp);
751     if (event_sp_ptr && event_sp)
752       *event_sp_ptr = event_sp;
753 
754     bool pop_process_io_handler = (hijack_listener_sp.get() != nullptr);
755     Process::HandleProcessStateChangedEvent(event_sp, stream,
756                                             pop_process_io_handler);
757 
758     switch (state) {
759     case eStateCrashed:
760     case eStateDetached:
761     case eStateExited:
762     case eStateUnloaded:
763       // We need to toggle the run lock as this won't get done in
764       // SetPublicState() if the process is hijacked.
765       if (hijack_listener_sp && use_run_lock)
766         m_public_run_lock.SetStopped();
767       return state;
768     case eStateStopped:
769       if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get()))
770         continue;
771       else {
772         // We need to toggle the run lock as this won't get done in
773         // SetPublicState() if the process is hijacked.
774         if (hijack_listener_sp && use_run_lock)
775           m_public_run_lock.SetStopped();
776         return state;
777       }
778     default:
779       continue;
780     }
781   }
782   return state;
783 }
784 
785 bool Process::HandleProcessStateChangedEvent(const EventSP &event_sp,
786                                              Stream *stream,
787                                              bool &pop_process_io_handler) {
788   const bool handle_pop = pop_process_io_handler;
789 
790   pop_process_io_handler = false;
791   ProcessSP process_sp =
792       Process::ProcessEventData::GetProcessFromEvent(event_sp.get());
793 
794   if (!process_sp)
795     return false;
796 
797   StateType event_state =
798       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
799   if (event_state == eStateInvalid)
800     return false;
801 
802   switch (event_state) {
803   case eStateInvalid:
804   case eStateUnloaded:
805   case eStateAttaching:
806   case eStateLaunching:
807   case eStateStepping:
808   case eStateDetached:
809     if (stream)
810       stream->Printf("Process %" PRIu64 " %s\n", process_sp->GetID(),
811                      StateAsCString(event_state));
812     if (event_state == eStateDetached)
813       pop_process_io_handler = true;
814     break;
815 
816   case eStateConnected:
817   case eStateRunning:
818     // Don't be chatty when we run...
819     break;
820 
821   case eStateExited:
822     if (stream)
823       process_sp->GetStatus(*stream);
824     pop_process_io_handler = true;
825     break;
826 
827   case eStateStopped:
828   case eStateCrashed:
829   case eStateSuspended:
830     // Make sure the program hasn't been auto-restarted:
831     if (Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
832       if (stream) {
833         size_t num_reasons =
834             Process::ProcessEventData::GetNumRestartedReasons(event_sp.get());
835         if (num_reasons > 0) {
836           // FIXME: Do we want to report this, or would that just be annoyingly
837           // chatty?
838           if (num_reasons == 1) {
839             const char *reason =
840                 Process::ProcessEventData::GetRestartedReasonAtIndex(
841                     event_sp.get(), 0);
842             stream->Printf("Process %" PRIu64 " stopped and restarted: %s\n",
843                            process_sp->GetID(),
844                            reason ? reason : "<UNKNOWN REASON>");
845           } else {
846             stream->Printf("Process %" PRIu64
847                            " stopped and restarted, reasons:\n",
848                            process_sp->GetID());
849 
850             for (size_t i = 0; i < num_reasons; i++) {
851               const char *reason =
852                   Process::ProcessEventData::GetRestartedReasonAtIndex(
853                       event_sp.get(), i);
854               stream->Printf("\t%s\n", reason ? reason : "<UNKNOWN REASON>");
855             }
856           }
857         }
858       }
859     } else {
860       StopInfoSP curr_thread_stop_info_sp;
861       // Lock the thread list so it doesn't change on us, this is the scope for
862       // the locker:
863       {
864         ThreadList &thread_list = process_sp->GetThreadList();
865         std::lock_guard<std::recursive_mutex> guard(thread_list.GetMutex());
866 
867         ThreadSP curr_thread(thread_list.GetSelectedThread());
868         ThreadSP thread;
869         StopReason curr_thread_stop_reason = eStopReasonInvalid;
870         if (curr_thread) {
871           curr_thread_stop_reason = curr_thread->GetStopReason();
872           curr_thread_stop_info_sp = curr_thread->GetStopInfo();
873         }
874         if (!curr_thread || !curr_thread->IsValid() ||
875             curr_thread_stop_reason == eStopReasonInvalid ||
876             curr_thread_stop_reason == eStopReasonNone) {
877           // Prefer a thread that has just completed its plan over another
878           // thread as current thread.
879           ThreadSP plan_thread;
880           ThreadSP other_thread;
881 
882           const size_t num_threads = thread_list.GetSize();
883           size_t i;
884           for (i = 0; i < num_threads; ++i) {
885             thread = thread_list.GetThreadAtIndex(i);
886             StopReason thread_stop_reason = thread->GetStopReason();
887             switch (thread_stop_reason) {
888             case eStopReasonInvalid:
889             case eStopReasonNone:
890               break;
891 
892             case eStopReasonSignal: {
893               // Don't select a signal thread if we weren't going to stop at
894               // that signal.  We have to have had another reason for stopping
895               // here, and the user doesn't want to see this thread.
896               uint64_t signo = thread->GetStopInfo()->GetValue();
897               if (process_sp->GetUnixSignals()->GetShouldStop(signo)) {
898                 if (!other_thread)
899                   other_thread = thread;
900               }
901               break;
902             }
903             case eStopReasonTrace:
904             case eStopReasonBreakpoint:
905             case eStopReasonWatchpoint:
906             case eStopReasonException:
907             case eStopReasonExec:
908             case eStopReasonThreadExiting:
909             case eStopReasonInstrumentation:
910               if (!other_thread)
911                 other_thread = thread;
912               break;
913             case eStopReasonPlanComplete:
914               if (!plan_thread)
915                 plan_thread = thread;
916               break;
917             }
918           }
919           if (plan_thread)
920             thread_list.SetSelectedThreadByID(plan_thread->GetID());
921           else if (other_thread)
922             thread_list.SetSelectedThreadByID(other_thread->GetID());
923           else {
924             if (curr_thread && curr_thread->IsValid())
925               thread = curr_thread;
926             else
927               thread = thread_list.GetThreadAtIndex(0);
928 
929             if (thread)
930               thread_list.SetSelectedThreadByID(thread->GetID());
931           }
932         }
933       }
934       // Drop the ThreadList mutex by here, since GetThreadStatus below might
935       // have to run code, e.g. for Data formatters, and if we hold the
936       // ThreadList mutex, then the process is going to have a hard time
937       // restarting the process.
938       if (stream) {
939         Debugger &debugger = process_sp->GetTarget().GetDebugger();
940         if (debugger.GetTargetList().GetSelectedTarget().get() ==
941             &process_sp->GetTarget()) {
942           ThreadSP thread_sp = process_sp->GetThreadList().GetSelectedThread();
943 
944           if (!thread_sp || !thread_sp->IsValid())
945             return false;
946 
947           const bool only_threads_with_stop_reason = true;
948           const uint32_t start_frame = thread_sp->GetSelectedFrameIndex();
949           const uint32_t num_frames = 1;
950           const uint32_t num_frames_with_source = 1;
951           const bool stop_format = true;
952 
953           process_sp->GetStatus(*stream);
954           process_sp->GetThreadStatus(*stream, only_threads_with_stop_reason,
955                                       start_frame, num_frames,
956                                       num_frames_with_source,
957                                       stop_format);
958           if (curr_thread_stop_info_sp) {
959             lldb::addr_t crashing_address;
960             ValueObjectSP valobj_sp = StopInfo::GetCrashingDereference(
961                 curr_thread_stop_info_sp, &crashing_address);
962             if (valobj_sp) {
963               const ValueObject::GetExpressionPathFormat format =
964                   ValueObject::GetExpressionPathFormat::
965                       eGetExpressionPathFormatHonorPointers;
966               stream->PutCString("Likely cause: ");
967               valobj_sp->GetExpressionPath(*stream, format);
968               stream->Printf(" accessed 0x%" PRIx64 "\n", crashing_address);
969             }
970           }
971         } else {
972           uint32_t target_idx = debugger.GetTargetList().GetIndexOfTarget(
973               process_sp->GetTarget().shared_from_this());
974           if (target_idx != UINT32_MAX)
975             stream->Printf("Target %d: (", target_idx);
976           else
977             stream->Printf("Target <unknown index>: (");
978           process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
979           stream->Printf(") stopped.\n");
980         }
981       }
982 
983       // Pop the process IO handler
984       pop_process_io_handler = true;
985     }
986     break;
987   }
988 
989   if (handle_pop && pop_process_io_handler)
990     process_sp->PopProcessIOHandler();
991 
992   return true;
993 }
994 
995 bool Process::HijackProcessEvents(ListenerSP listener_sp) {
996   if (listener_sp) {
997     return HijackBroadcaster(listener_sp, eBroadcastBitStateChanged |
998                                               eBroadcastBitInterrupt);
999   } else
1000     return false;
1001 }
1002 
1003 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
1004 
1005 StateType Process::GetStateChangedEvents(EventSP &event_sp,
1006                                          const Timeout<std::micro> &timeout,
1007                                          ListenerSP hijack_listener_sp) {
1008   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1009   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1010 
1011   ListenerSP listener_sp = hijack_listener_sp;
1012   if (!listener_sp)
1013     listener_sp = m_listener_sp;
1014 
1015   StateType state = eStateInvalid;
1016   if (listener_sp->GetEventForBroadcasterWithType(
1017           this, eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1018           timeout)) {
1019     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1020       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1021     else
1022       LLDB_LOG(log, "got no event or was interrupted.");
1023   }
1024 
1025   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout, state);
1026   return state;
1027 }
1028 
1029 Event *Process::PeekAtStateChangedEvents() {
1030   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1031 
1032   LLDB_LOGF(log, "Process::%s...", __FUNCTION__);
1033 
1034   Event *event_ptr;
1035   event_ptr = m_listener_sp->PeekAtNextEventForBroadcasterWithType(
1036       this, eBroadcastBitStateChanged);
1037   if (log) {
1038     if (event_ptr) {
1039       LLDB_LOGF(log, "Process::%s (event_ptr) => %s", __FUNCTION__,
1040                 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr)));
1041     } else {
1042       LLDB_LOGF(log, "Process::%s no events found", __FUNCTION__);
1043     }
1044   }
1045   return event_ptr;
1046 }
1047 
1048 StateType
1049 Process::GetStateChangedEventsPrivate(EventSP &event_sp,
1050                                       const Timeout<std::micro> &timeout) {
1051   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1052   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1053 
1054   StateType state = eStateInvalid;
1055   if (m_private_state_listener_sp->GetEventForBroadcasterWithType(
1056           &m_private_state_broadcaster,
1057           eBroadcastBitStateChanged | eBroadcastBitInterrupt, event_sp,
1058           timeout))
1059     if (event_sp && event_sp->GetType() == eBroadcastBitStateChanged)
1060       state = Process::ProcessEventData::GetStateFromEvent(event_sp.get());
1061 
1062   LLDB_LOG(log, "timeout = {0}, event_sp) => {1}", timeout,
1063            state == eStateInvalid ? "TIMEOUT" : StateAsCString(state));
1064   return state;
1065 }
1066 
1067 bool Process::GetEventsPrivate(EventSP &event_sp,
1068                                const Timeout<std::micro> &timeout,
1069                                bool control_only) {
1070   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1071   LLDB_LOG(log, "timeout = {0}, event_sp)...", timeout);
1072 
1073   if (control_only)
1074     return m_private_state_listener_sp->GetEventForBroadcaster(
1075         &m_private_state_control_broadcaster, event_sp, timeout);
1076   else
1077     return m_private_state_listener_sp->GetEvent(event_sp, timeout);
1078 }
1079 
1080 bool Process::IsRunning() const {
1081   return StateIsRunningState(m_public_state.GetValue());
1082 }
1083 
1084 int Process::GetExitStatus() {
1085   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1086 
1087   if (m_public_state.GetValue() == eStateExited)
1088     return m_exit_status;
1089   return -1;
1090 }
1091 
1092 const char *Process::GetExitDescription() {
1093   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1094 
1095   if (m_public_state.GetValue() == eStateExited && !m_exit_string.empty())
1096     return m_exit_string.c_str();
1097   return nullptr;
1098 }
1099 
1100 bool Process::SetExitStatus(int status, const char *cstr) {
1101   // Use a mutex to protect setting the exit status.
1102   std::lock_guard<std::mutex> guard(m_exit_status_mutex);
1103 
1104   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1105                                                   LIBLLDB_LOG_PROCESS));
1106   LLDB_LOGF(
1107       log, "Process::SetExitStatus (status=%i (0x%8.8x), description=%s%s%s)",
1108       status, status, cstr ? "\"" : "", cstr ? cstr : "NULL", cstr ? "\"" : "");
1109 
1110   // We were already in the exited state
1111   if (m_private_state.GetValue() == eStateExited) {
1112     LLDB_LOGF(log, "Process::SetExitStatus () ignoring exit status because "
1113                    "state was already set to eStateExited");
1114     return false;
1115   }
1116 
1117   m_exit_status = status;
1118   if (cstr)
1119     m_exit_string = cstr;
1120   else
1121     m_exit_string.clear();
1122 
1123   // Clear the last natural stop ID since it has a strong reference to this
1124   // process
1125   m_mod_id.SetStopEventForLastNaturalStopID(EventSP());
1126 
1127   SetPrivateState(eStateExited);
1128 
1129   // Allow subclasses to do some cleanup
1130   DidExit();
1131 
1132   return true;
1133 }
1134 
1135 bool Process::IsAlive() {
1136   switch (m_private_state.GetValue()) {
1137   case eStateConnected:
1138   case eStateAttaching:
1139   case eStateLaunching:
1140   case eStateStopped:
1141   case eStateRunning:
1142   case eStateStepping:
1143   case eStateCrashed:
1144   case eStateSuspended:
1145     return true;
1146   default:
1147     return false;
1148   }
1149 }
1150 
1151 // This static callback can be used to watch for local child processes on the
1152 // current host. The child process exits, the process will be found in the
1153 // global target list (we want to be completely sure that the
1154 // lldb_private::Process doesn't go away before we can deliver the signal.
1155 bool Process::SetProcessExitStatus(
1156     lldb::pid_t pid, bool exited,
1157     int signo,      // Zero for no signal
1158     int exit_status // Exit value of process if signal is zero
1159     ) {
1160   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
1161   LLDB_LOGF(log,
1162             "Process::SetProcessExitStatus (pid=%" PRIu64
1163             ", exited=%i, signal=%i, exit_status=%i)\n",
1164             pid, exited, signo, exit_status);
1165 
1166   if (exited) {
1167     TargetSP target_sp(Debugger::FindTargetWithProcessID(pid));
1168     if (target_sp) {
1169       ProcessSP process_sp(target_sp->GetProcessSP());
1170       if (process_sp) {
1171         const char *signal_cstr = nullptr;
1172         if (signo)
1173           signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo);
1174 
1175         process_sp->SetExitStatus(exit_status, signal_cstr);
1176       }
1177     }
1178     return true;
1179   }
1180   return false;
1181 }
1182 
1183 void Process::UpdateThreadListIfNeeded() {
1184   const uint32_t stop_id = GetStopID();
1185   if (m_thread_list.GetSize(false) == 0 ||
1186       stop_id != m_thread_list.GetStopID()) {
1187     bool clear_unused_threads = true;
1188     const StateType state = GetPrivateState();
1189     if (StateIsStoppedState(state, true)) {
1190       std::lock_guard<std::recursive_mutex> guard(m_thread_list.GetMutex());
1191       m_thread_list.SetStopID(stop_id);
1192 
1193       // m_thread_list does have its own mutex, but we need to hold onto the
1194       // mutex between the call to UpdateThreadList(...) and the
1195       // os->UpdateThreadList(...) so it doesn't change on us
1196       ThreadList &old_thread_list = m_thread_list;
1197       ThreadList real_thread_list(this);
1198       ThreadList new_thread_list(this);
1199       // Always update the thread list with the protocol specific thread list,
1200       // but only update if "true" is returned
1201       if (UpdateThreadList(m_thread_list_real, real_thread_list)) {
1202         // Don't call into the OperatingSystem to update the thread list if we
1203         // are shutting down, since that may call back into the SBAPI's,
1204         // requiring the API lock which is already held by whoever is shutting
1205         // us down, causing a deadlock.
1206         OperatingSystem *os = GetOperatingSystem();
1207         if (os && !m_destroy_in_process) {
1208           // Clear any old backing threads where memory threads might have been
1209           // backed by actual threads from the lldb_private::Process subclass
1210           size_t num_old_threads = old_thread_list.GetSize(false);
1211           for (size_t i = 0; i < num_old_threads; ++i)
1212             old_thread_list.GetThreadAtIndex(i, false)->ClearBackingThread();
1213           // See if the OS plugin reports all threads.  If it does, then
1214           // it is safe to clear unseen thread's plans here.  Otherwise we
1215           // should preserve them in case they show up again:
1216           clear_unused_threads = GetTarget().GetOSPluginReportsAllThreads();
1217 
1218           // Turn off dynamic types to ensure we don't run any expressions.
1219           // Objective-C can run an expression to determine if a SBValue is a
1220           // dynamic type or not and we need to avoid this. OperatingSystem
1221           // plug-ins can't run expressions that require running code...
1222 
1223           Target &target = GetTarget();
1224           const lldb::DynamicValueType saved_prefer_dynamic =
1225               target.GetPreferDynamicValue();
1226           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1227             target.SetPreferDynamicValue(lldb::eNoDynamicValues);
1228 
1229           // Now let the OperatingSystem plug-in update the thread list
1230 
1231           os->UpdateThreadList(
1232               old_thread_list, // Old list full of threads created by OS plug-in
1233               real_thread_list, // The actual thread list full of threads
1234                                 // created by each lldb_private::Process
1235                                 // subclass
1236               new_thread_list); // The new thread list that we will show to the
1237                                 // user that gets filled in
1238 
1239           if (saved_prefer_dynamic != lldb::eNoDynamicValues)
1240             target.SetPreferDynamicValue(saved_prefer_dynamic);
1241         } else {
1242           // No OS plug-in, the new thread list is the same as the real thread
1243           // list.
1244           new_thread_list = real_thread_list;
1245         }
1246 
1247         m_thread_list_real.Update(real_thread_list);
1248         m_thread_list.Update(new_thread_list);
1249         m_thread_list.SetStopID(stop_id);
1250 
1251         if (GetLastNaturalStopID() != m_extended_thread_stop_id) {
1252           // Clear any extended threads that we may have accumulated previously
1253           m_extended_thread_list.Clear();
1254           m_extended_thread_stop_id = GetLastNaturalStopID();
1255 
1256           m_queue_list.Clear();
1257           m_queue_list_stop_id = GetLastNaturalStopID();
1258         }
1259       }
1260       // Now update the plan stack map.
1261       // If we do have an OS plugin, any absent real threads in the
1262       // m_thread_list have already been removed from the ThreadPlanStackMap.
1263       // So any remaining threads are OS Plugin threads, and those we want to
1264       // preserve in case they show up again.
1265       m_thread_plans.Update(m_thread_list, clear_unused_threads);
1266     }
1267   }
1268 }
1269 
1270 ThreadPlanStack *Process::FindThreadPlans(lldb::tid_t tid) {
1271   return m_thread_plans.Find(tid);
1272 }
1273 
1274 bool Process::PruneThreadPlansForTID(lldb::tid_t tid) {
1275   return m_thread_plans.PrunePlansForTID(tid);
1276 }
1277 
1278 void Process::PruneThreadPlans() {
1279   m_thread_plans.Update(GetThreadList(), true, false);
1280 }
1281 
1282 bool Process::DumpThreadPlansForTID(Stream &strm, lldb::tid_t tid,
1283                                     lldb::DescriptionLevel desc_level,
1284                                     bool internal, bool condense_trivial,
1285                                     bool skip_unreported_plans) {
1286   return m_thread_plans.DumpPlansForTID(
1287       strm, tid, desc_level, internal, condense_trivial, skip_unreported_plans);
1288 }
1289 void Process::DumpThreadPlans(Stream &strm, lldb::DescriptionLevel desc_level,
1290                               bool internal, bool condense_trivial,
1291                               bool skip_unreported_plans) {
1292   m_thread_plans.DumpPlans(strm, desc_level, internal, condense_trivial,
1293                            skip_unreported_plans);
1294 }
1295 
1296 void Process::UpdateQueueListIfNeeded() {
1297   if (m_system_runtime_up) {
1298     if (m_queue_list.GetSize() == 0 ||
1299         m_queue_list_stop_id != GetLastNaturalStopID()) {
1300       const StateType state = GetPrivateState();
1301       if (StateIsStoppedState(state, true)) {
1302         m_system_runtime_up->PopulateQueueList(m_queue_list);
1303         m_queue_list_stop_id = GetLastNaturalStopID();
1304       }
1305     }
1306   }
1307 }
1308 
1309 ThreadSP Process::CreateOSPluginThread(lldb::tid_t tid, lldb::addr_t context) {
1310   OperatingSystem *os = GetOperatingSystem();
1311   if (os)
1312     return os->CreateThread(tid, context);
1313   return ThreadSP();
1314 }
1315 
1316 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id) {
1317   return AssignIndexIDToThread(thread_id);
1318 }
1319 
1320 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id) {
1321   return (m_thread_id_to_index_id_map.find(thread_id) !=
1322           m_thread_id_to_index_id_map.end());
1323 }
1324 
1325 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id) {
1326   uint32_t result = 0;
1327   std::map<uint64_t, uint32_t>::iterator iterator =
1328       m_thread_id_to_index_id_map.find(thread_id);
1329   if (iterator == m_thread_id_to_index_id_map.end()) {
1330     result = ++m_thread_index_id;
1331     m_thread_id_to_index_id_map[thread_id] = result;
1332   } else {
1333     result = iterator->second;
1334   }
1335 
1336   return result;
1337 }
1338 
1339 StateType Process::GetState() {
1340   return m_public_state.GetValue();
1341 }
1342 
1343 void Process::SetPublicState(StateType new_state, bool restarted) {
1344   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1345                                                   LIBLLDB_LOG_PROCESS));
1346   LLDB_LOGF(log, "Process::SetPublicState (state = %s, restarted = %i)",
1347             StateAsCString(new_state), restarted);
1348   const StateType old_state = m_public_state.GetValue();
1349   m_public_state.SetValue(new_state);
1350 
1351   // On the transition from Run to Stopped, we unlock the writer end of the run
1352   // lock.  The lock gets locked in Resume, which is the public API to tell the
1353   // program to run.
1354   if (!StateChangedIsExternallyHijacked()) {
1355     if (new_state == eStateDetached) {
1356       LLDB_LOGF(log,
1357                 "Process::SetPublicState (%s) -- unlocking run lock for detach",
1358                 StateAsCString(new_state));
1359       m_public_run_lock.SetStopped();
1360     } else {
1361       const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1362       const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1363       if ((old_state_is_stopped != new_state_is_stopped)) {
1364         if (new_state_is_stopped && !restarted) {
1365           LLDB_LOGF(log, "Process::SetPublicState (%s) -- unlocking run lock",
1366                     StateAsCString(new_state));
1367           m_public_run_lock.SetStopped();
1368         }
1369       }
1370     }
1371   }
1372 }
1373 
1374 Status Process::Resume() {
1375   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1376                                                   LIBLLDB_LOG_PROCESS));
1377   LLDB_LOGF(log, "Process::Resume -- locking run lock");
1378   if (!m_public_run_lock.TrySetRunning()) {
1379     Status error("Resume request failed - process still running.");
1380     LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1381     return error;
1382   }
1383   Status error = PrivateResume();
1384   if (!error.Success()) {
1385     // Undo running state change
1386     m_public_run_lock.SetStopped();
1387   }
1388   return error;
1389 }
1390 
1391 static const char *g_resume_sync_name = "lldb.Process.ResumeSynchronous.hijack";
1392 
1393 Status Process::ResumeSynchronous(Stream *stream) {
1394   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1395                                                   LIBLLDB_LOG_PROCESS));
1396   LLDB_LOGF(log, "Process::ResumeSynchronous -- locking run lock");
1397   if (!m_public_run_lock.TrySetRunning()) {
1398     Status error("Resume request failed - process still running.");
1399     LLDB_LOGF(log, "Process::Resume: -- TrySetRunning failed, not resuming.");
1400     return error;
1401   }
1402 
1403   ListenerSP listener_sp(
1404       Listener::MakeListener(g_resume_sync_name));
1405   HijackProcessEvents(listener_sp);
1406 
1407   Status error = PrivateResume();
1408   if (error.Success()) {
1409     StateType state =
1410         WaitForProcessToStop(llvm::None, nullptr, true, listener_sp, stream);
1411     const bool must_be_alive =
1412         false; // eStateExited is ok, so this must be false
1413     if (!StateIsStoppedState(state, must_be_alive))
1414       error.SetErrorStringWithFormat(
1415           "process not in stopped state after synchronous resume: %s",
1416           StateAsCString(state));
1417   } else {
1418     // Undo running state change
1419     m_public_run_lock.SetStopped();
1420   }
1421 
1422   // Undo the hijacking of process events...
1423   RestoreProcessEvents();
1424 
1425   return error;
1426 }
1427 
1428 bool Process::StateChangedIsExternallyHijacked() {
1429   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1430     const char *hijacking_name = GetHijackingListenerName();
1431     if (hijacking_name &&
1432         strcmp(hijacking_name, g_resume_sync_name))
1433       return true;
1434   }
1435   return false;
1436 }
1437 
1438 bool Process::StateChangedIsHijackedForSynchronousResume() {
1439   if (IsHijackedForEvent(eBroadcastBitStateChanged)) {
1440     const char *hijacking_name = GetHijackingListenerName();
1441     if (hijacking_name &&
1442         strcmp(hijacking_name, g_resume_sync_name) == 0)
1443       return true;
1444   }
1445   return false;
1446 }
1447 
1448 StateType Process::GetPrivateState() { return m_private_state.GetValue(); }
1449 
1450 void Process::SetPrivateState(StateType new_state) {
1451   if (m_finalize_called)
1452     return;
1453 
1454   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STATE |
1455                                                   LIBLLDB_LOG_PROCESS));
1456   bool state_changed = false;
1457 
1458   LLDB_LOGF(log, "Process::SetPrivateState (%s)", StateAsCString(new_state));
1459 
1460   std::lock_guard<std::recursive_mutex> thread_guard(m_thread_list.GetMutex());
1461   std::lock_guard<std::recursive_mutex> guard(m_private_state.GetMutex());
1462 
1463   const StateType old_state = m_private_state.GetValueNoLock();
1464   state_changed = old_state != new_state;
1465 
1466   const bool old_state_is_stopped = StateIsStoppedState(old_state, false);
1467   const bool new_state_is_stopped = StateIsStoppedState(new_state, false);
1468   if (old_state_is_stopped != new_state_is_stopped) {
1469     if (new_state_is_stopped)
1470       m_private_run_lock.SetStopped();
1471     else
1472       m_private_run_lock.SetRunning();
1473   }
1474 
1475   if (state_changed) {
1476     m_private_state.SetValueNoLock(new_state);
1477     EventSP event_sp(
1478         new Event(eBroadcastBitStateChanged,
1479                   new ProcessEventData(shared_from_this(), new_state)));
1480     if (StateIsStoppedState(new_state, false)) {
1481       // Note, this currently assumes that all threads in the list stop when
1482       // the process stops.  In the future we will want to support a debugging
1483       // model where some threads continue to run while others are stopped.
1484       // When that happens we will either need a way for the thread list to
1485       // identify which threads are stopping or create a special thread list
1486       // containing only threads which actually stopped.
1487       //
1488       // The process plugin is responsible for managing the actual behavior of
1489       // the threads and should have stopped any threads that are going to stop
1490       // before we get here.
1491       m_thread_list.DidStop();
1492 
1493       m_mod_id.BumpStopID();
1494       if (!m_mod_id.IsLastResumeForUserExpression())
1495         m_mod_id.SetStopEventForLastNaturalStopID(event_sp);
1496       m_memory_cache.Clear();
1497       LLDB_LOGF(log, "Process::SetPrivateState (%s) stop_id = %u",
1498                 StateAsCString(new_state), m_mod_id.GetStopID());
1499     }
1500 
1501     // Use our target to get a shared pointer to ourselves...
1502     if (m_finalize_called && !PrivateStateThreadIsValid())
1503       BroadcastEvent(event_sp);
1504     else
1505       m_private_state_broadcaster.BroadcastEvent(event_sp);
1506   } else {
1507     LLDB_LOGF(log,
1508               "Process::SetPrivateState (%s) state didn't change. Ignoring...",
1509               StateAsCString(new_state));
1510   }
1511 }
1512 
1513 void Process::SetRunningUserExpression(bool on) {
1514   m_mod_id.SetRunningUserExpression(on);
1515 }
1516 
1517 void Process::SetRunningUtilityFunction(bool on) {
1518   m_mod_id.SetRunningUtilityFunction(on);
1519 }
1520 
1521 addr_t Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS; }
1522 
1523 const lldb::ABISP &Process::GetABI() {
1524   if (!m_abi_sp)
1525     m_abi_sp = ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1526   return m_abi_sp;
1527 }
1528 
1529 std::vector<LanguageRuntime *> Process::GetLanguageRuntimes() {
1530   std::vector<LanguageRuntime *> language_runtimes;
1531 
1532   if (m_finalizing)
1533     return language_runtimes;
1534 
1535   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1536   // Before we pass off a copy of the language runtimes, we must make sure that
1537   // our collection is properly populated. It's possible that some of the
1538   // language runtimes were not loaded yet, either because nobody requested it
1539   // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1540   // hadn't been loaded).
1541   for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
1542     if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
1543       language_runtimes.emplace_back(runtime);
1544   }
1545 
1546   return language_runtimes;
1547 }
1548 
1549 LanguageRuntime *Process::GetLanguageRuntime(lldb::LanguageType language) {
1550   if (m_finalizing)
1551     return nullptr;
1552 
1553   LanguageRuntime *runtime = nullptr;
1554 
1555   std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
1556   LanguageRuntimeCollection::iterator pos;
1557   pos = m_language_runtimes.find(language);
1558   if (pos == m_language_runtimes.end() || !pos->second) {
1559     lldb::LanguageRuntimeSP runtime_sp(
1560         LanguageRuntime::FindPlugin(this, language));
1561 
1562     m_language_runtimes[language] = runtime_sp;
1563     runtime = runtime_sp.get();
1564   } else
1565     runtime = pos->second.get();
1566 
1567   if (runtime)
1568     // It's possible that a language runtime can support multiple LanguageTypes,
1569     // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1570     // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1571     // primary language type and make sure that our runtime supports it.
1572     assert(runtime->GetLanguageType() == Language::GetPrimaryLanguage(language));
1573 
1574   return runtime;
1575 }
1576 
1577 bool Process::IsPossibleDynamicValue(ValueObject &in_value) {
1578   if (m_finalizing)
1579     return false;
1580 
1581   if (in_value.IsDynamic())
1582     return false;
1583   LanguageType known_type = in_value.GetObjectRuntimeLanguage();
1584 
1585   if (known_type != eLanguageTypeUnknown && known_type != eLanguageTypeC) {
1586     LanguageRuntime *runtime = GetLanguageRuntime(known_type);
1587     return runtime ? runtime->CouldHaveDynamicValue(in_value) : false;
1588   }
1589 
1590   for (LanguageRuntime *runtime : GetLanguageRuntimes()) {
1591     if (runtime->CouldHaveDynamicValue(in_value))
1592       return true;
1593   }
1594 
1595   return false;
1596 }
1597 
1598 void Process::SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers) {
1599   m_dynamic_checkers_up.reset(dynamic_checkers);
1600 }
1601 
1602 BreakpointSiteList &Process::GetBreakpointSiteList() {
1603   return m_breakpoint_site_list;
1604 }
1605 
1606 const BreakpointSiteList &Process::GetBreakpointSiteList() const {
1607   return m_breakpoint_site_list;
1608 }
1609 
1610 void Process::DisableAllBreakpointSites() {
1611   m_breakpoint_site_list.ForEach([this](BreakpointSite *bp_site) -> void {
1612     //        bp_site->SetEnabled(true);
1613     DisableBreakpointSite(bp_site);
1614   });
1615 }
1616 
1617 Status Process::ClearBreakpointSiteByID(lldb::user_id_t break_id) {
1618   Status error(DisableBreakpointSiteByID(break_id));
1619 
1620   if (error.Success())
1621     m_breakpoint_site_list.Remove(break_id);
1622 
1623   return error;
1624 }
1625 
1626 Status Process::DisableBreakpointSiteByID(lldb::user_id_t break_id) {
1627   Status error;
1628   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1629   if (bp_site_sp) {
1630     if (bp_site_sp->IsEnabled())
1631       error = DisableBreakpointSite(bp_site_sp.get());
1632   } else {
1633     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1634                                    break_id);
1635   }
1636 
1637   return error;
1638 }
1639 
1640 Status Process::EnableBreakpointSiteByID(lldb::user_id_t break_id) {
1641   Status error;
1642   BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1643   if (bp_site_sp) {
1644     if (!bp_site_sp->IsEnabled())
1645       error = EnableBreakpointSite(bp_site_sp.get());
1646   } else {
1647     error.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64,
1648                                    break_id);
1649   }
1650   return error;
1651 }
1652 
1653 lldb::break_id_t
1654 Process::CreateBreakpointSite(const BreakpointLocationSP &owner,
1655                               bool use_hardware) {
1656   addr_t load_addr = LLDB_INVALID_ADDRESS;
1657 
1658   bool show_error = true;
1659   switch (GetState()) {
1660   case eStateInvalid:
1661   case eStateUnloaded:
1662   case eStateConnected:
1663   case eStateAttaching:
1664   case eStateLaunching:
1665   case eStateDetached:
1666   case eStateExited:
1667     show_error = false;
1668     break;
1669 
1670   case eStateStopped:
1671   case eStateRunning:
1672   case eStateStepping:
1673   case eStateCrashed:
1674   case eStateSuspended:
1675     show_error = IsAlive();
1676     break;
1677   }
1678 
1679   // Reset the IsIndirect flag here, in case the location changes from pointing
1680   // to a indirect symbol to a regular symbol.
1681   owner->SetIsIndirect(false);
1682 
1683   if (owner->ShouldResolveIndirectFunctions()) {
1684     Symbol *symbol = owner->GetAddress().CalculateSymbolContextSymbol();
1685     if (symbol && symbol->IsIndirect()) {
1686       Status error;
1687       Address symbol_address = symbol->GetAddress();
1688       load_addr = ResolveIndirectFunction(&symbol_address, error);
1689       if (!error.Success() && show_error) {
1690         GetTarget().GetDebugger().GetErrorStream().Printf(
1691             "warning: failed to resolve indirect function at 0x%" PRIx64
1692             " for breakpoint %i.%i: %s\n",
1693             symbol->GetLoadAddress(&GetTarget()),
1694             owner->GetBreakpoint().GetID(), owner->GetID(),
1695             error.AsCString() ? error.AsCString() : "unknown error");
1696         return LLDB_INVALID_BREAK_ID;
1697       }
1698       Address resolved_address(load_addr);
1699       load_addr = resolved_address.GetOpcodeLoadAddress(&GetTarget());
1700       owner->SetIsIndirect(true);
1701     } else
1702       load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1703   } else
1704     load_addr = owner->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1705 
1706   if (load_addr != LLDB_INVALID_ADDRESS) {
1707     BreakpointSiteSP bp_site_sp;
1708 
1709     // Look up this breakpoint site.  If it exists, then add this new owner,
1710     // otherwise create a new breakpoint site and add it.
1711 
1712     bp_site_sp = m_breakpoint_site_list.FindByAddress(load_addr);
1713 
1714     if (bp_site_sp) {
1715       bp_site_sp->AddOwner(owner);
1716       owner->SetBreakpointSite(bp_site_sp);
1717       return bp_site_sp->GetID();
1718     } else {
1719       bp_site_sp.reset(new BreakpointSite(&m_breakpoint_site_list, owner,
1720                                           load_addr, use_hardware));
1721       if (bp_site_sp) {
1722         Status error = EnableBreakpointSite(bp_site_sp.get());
1723         if (error.Success()) {
1724           owner->SetBreakpointSite(bp_site_sp);
1725           return m_breakpoint_site_list.Add(bp_site_sp);
1726         } else {
1727           if (show_error || use_hardware) {
1728             // Report error for setting breakpoint...
1729             GetTarget().GetDebugger().GetErrorStream().Printf(
1730                 "warning: failed to set breakpoint site at 0x%" PRIx64
1731                 " for breakpoint %i.%i: %s\n",
1732                 load_addr, owner->GetBreakpoint().GetID(), owner->GetID(),
1733                 error.AsCString() ? error.AsCString() : "unknown error");
1734           }
1735         }
1736       }
1737     }
1738   }
1739   // We failed to enable the breakpoint
1740   return LLDB_INVALID_BREAK_ID;
1741 }
1742 
1743 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id,
1744                                             lldb::user_id_t owner_loc_id,
1745                                             BreakpointSiteSP &bp_site_sp) {
1746   uint32_t num_owners = bp_site_sp->RemoveOwner(owner_id, owner_loc_id);
1747   if (num_owners == 0) {
1748     // Don't try to disable the site if we don't have a live process anymore.
1749     if (IsAlive())
1750       DisableBreakpointSite(bp_site_sp.get());
1751     m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1752   }
1753 }
1754 
1755 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr, size_t size,
1756                                                   uint8_t *buf) const {
1757   size_t bytes_removed = 0;
1758   BreakpointSiteList bp_sites_in_range;
1759 
1760   if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1761                                          bp_sites_in_range)) {
1762     bp_sites_in_range.ForEach([bp_addr, size,
1763                                buf](BreakpointSite *bp_site) -> void {
1764       if (bp_site->GetType() == BreakpointSite::eSoftware) {
1765         addr_t intersect_addr;
1766         size_t intersect_size;
1767         size_t opcode_offset;
1768         if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1769                                      &intersect_size, &opcode_offset)) {
1770           assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1771           assert(bp_addr < intersect_addr + intersect_size &&
1772                  intersect_addr + intersect_size <= bp_addr + size);
1773           assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1774           size_t buf_offset = intersect_addr - bp_addr;
1775           ::memcpy(buf + buf_offset,
1776                    bp_site->GetSavedOpcodeBytes() + opcode_offset,
1777                    intersect_size);
1778         }
1779       }
1780     });
1781   }
1782   return bytes_removed;
1783 }
1784 
1785 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site) {
1786   PlatformSP platform_sp(GetTarget().GetPlatform());
1787   if (platform_sp)
1788     return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1789   return 0;
1790 }
1791 
1792 Status Process::EnableSoftwareBreakpoint(BreakpointSite *bp_site) {
1793   Status error;
1794   assert(bp_site != nullptr);
1795   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1796   const addr_t bp_addr = bp_site->GetLoadAddress();
1797   LLDB_LOGF(
1798       log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1799       bp_site->GetID(), (uint64_t)bp_addr);
1800   if (bp_site->IsEnabled()) {
1801     LLDB_LOGF(
1802         log,
1803         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1804         " -- already enabled",
1805         bp_site->GetID(), (uint64_t)bp_addr);
1806     return error;
1807   }
1808 
1809   if (bp_addr == LLDB_INVALID_ADDRESS) {
1810     error.SetErrorString("BreakpointSite contains an invalid load address.");
1811     return error;
1812   }
1813   // Ask the lldb::Process subclass to fill in the correct software breakpoint
1814   // trap for the breakpoint site
1815   const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1816 
1817   if (bp_opcode_size == 0) {
1818     error.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1819                                    "returned zero, unable to get breakpoint "
1820                                    "trap for address 0x%" PRIx64,
1821                                    bp_addr);
1822   } else {
1823     const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1824 
1825     if (bp_opcode_bytes == nullptr) {
1826       error.SetErrorString(
1827           "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1828       return error;
1829     }
1830 
1831     // Save the original opcode by reading it
1832     if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1833                      error) == bp_opcode_size) {
1834       // Write a software breakpoint in place of the original opcode
1835       if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1836           bp_opcode_size) {
1837         uint8_t verify_bp_opcode_bytes[64];
1838         if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1839                          error) == bp_opcode_size) {
1840           if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1841                        bp_opcode_size) == 0) {
1842             bp_site->SetEnabled(true);
1843             bp_site->SetType(BreakpointSite::eSoftware);
1844             LLDB_LOGF(log,
1845                       "Process::EnableSoftwareBreakpoint (site_id = %d) "
1846                       "addr = 0x%" PRIx64 " -- SUCCESS",
1847                       bp_site->GetID(), (uint64_t)bp_addr);
1848           } else
1849             error.SetErrorString(
1850                 "failed to verify the breakpoint trap in memory.");
1851         } else
1852           error.SetErrorString(
1853               "Unable to read memory to verify breakpoint trap.");
1854       } else
1855         error.SetErrorString("Unable to write breakpoint trap to memory.");
1856     } else
1857       error.SetErrorString("Unable to read memory at breakpoint address.");
1858   }
1859   if (log && error.Fail())
1860     LLDB_LOGF(
1861         log,
1862         "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1863         " -- FAILED: %s",
1864         bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1865   return error;
1866 }
1867 
1868 Status Process::DisableSoftwareBreakpoint(BreakpointSite *bp_site) {
1869   Status error;
1870   assert(bp_site != nullptr);
1871   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
1872   addr_t bp_addr = bp_site->GetLoadAddress();
1873   lldb::user_id_t breakID = bp_site->GetID();
1874   LLDB_LOGF(log,
1875             "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1876             ") addr = 0x%" PRIx64,
1877             breakID, (uint64_t)bp_addr);
1878 
1879   if (bp_site->IsHardware()) {
1880     error.SetErrorString("Breakpoint site is a hardware breakpoint.");
1881   } else if (bp_site->IsEnabled()) {
1882     const size_t break_op_size = bp_site->GetByteSize();
1883     const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1884     if (break_op_size > 0) {
1885       // Clear a software breakpoint instruction
1886       uint8_t curr_break_op[8];
1887       assert(break_op_size <= sizeof(curr_break_op));
1888       bool break_op_found = false;
1889 
1890       // Read the breakpoint opcode
1891       if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1892           break_op_size) {
1893         bool verify = false;
1894         // Make sure the breakpoint opcode exists at this address
1895         if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1896           break_op_found = true;
1897           // We found a valid breakpoint opcode at this address, now restore
1898           // the saved opcode.
1899           if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1900                             break_op_size, error) == break_op_size) {
1901             verify = true;
1902           } else
1903             error.SetErrorString(
1904                 "Memory write failed when restoring original opcode.");
1905         } else {
1906           error.SetErrorString(
1907               "Original breakpoint trap is no longer in memory.");
1908           // Set verify to true and so we can check if the original opcode has
1909           // already been restored
1910           verify = true;
1911         }
1912 
1913         if (verify) {
1914           uint8_t verify_opcode[8];
1915           assert(break_op_size < sizeof(verify_opcode));
1916           // Verify that our original opcode made it back to the inferior
1917           if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1918               break_op_size) {
1919             // compare the memory we just read with the original opcode
1920             if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1921                          break_op_size) == 0) {
1922               // SUCCESS
1923               bp_site->SetEnabled(false);
1924               LLDB_LOGF(log,
1925                         "Process::DisableSoftwareBreakpoint (site_id = %d) "
1926                         "addr = 0x%" PRIx64 " -- SUCCESS",
1927                         bp_site->GetID(), (uint64_t)bp_addr);
1928               return error;
1929             } else {
1930               if (break_op_found)
1931                 error.SetErrorString("Failed to restore original opcode.");
1932             }
1933           } else
1934             error.SetErrorString("Failed to read memory to verify that "
1935                                  "breakpoint trap was restored.");
1936         }
1937       } else
1938         error.SetErrorString(
1939             "Unable to read memory that should contain the breakpoint trap.");
1940     }
1941   } else {
1942     LLDB_LOGF(
1943         log,
1944         "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1945         " -- already disabled",
1946         bp_site->GetID(), (uint64_t)bp_addr);
1947     return error;
1948   }
1949 
1950   LLDB_LOGF(
1951       log,
1952       "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1953       " -- FAILED: %s",
1954       bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1955   return error;
1956 }
1957 
1958 // Uncomment to verify memory caching works after making changes to caching
1959 // code
1960 //#define VERIFY_MEMORY_READS
1961 
1962 size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
1963   error.Clear();
1964   if (!GetDisableMemoryCache()) {
1965 #if defined(VERIFY_MEMORY_READS)
1966     // Memory caching is enabled, with debug verification
1967 
1968     if (buf && size) {
1969       // Uncomment the line below to make sure memory caching is working.
1970       // I ran this through the test suite and got no assertions, so I am
1971       // pretty confident this is working well. If any changes are made to
1972       // memory caching, uncomment the line below and test your changes!
1973 
1974       // Verify all memory reads by using the cache first, then redundantly
1975       // reading the same memory from the inferior and comparing to make sure
1976       // everything is exactly the same.
1977       std::string verify_buf(size, '\0');
1978       assert(verify_buf.size() == size);
1979       const size_t cache_bytes_read =
1980           m_memory_cache.Read(this, addr, buf, size, error);
1981       Status verify_error;
1982       const size_t verify_bytes_read =
1983           ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
1984                                  verify_buf.size(), verify_error);
1985       assert(cache_bytes_read == verify_bytes_read);
1986       assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
1987       assert(verify_error.Success() == error.Success());
1988       return cache_bytes_read;
1989     }
1990     return 0;
1991 #else  // !defined(VERIFY_MEMORY_READS)
1992     // Memory caching is enabled, without debug verification
1993 
1994     return m_memory_cache.Read(addr, buf, size, error);
1995 #endif // defined (VERIFY_MEMORY_READS)
1996   } else {
1997     // Memory caching is disabled
1998 
1999     return ReadMemoryFromInferior(addr, buf, size, error);
2000   }
2001 }
2002 
2003 size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2004                                       Status &error) {
2005   char buf[256];
2006   out_str.clear();
2007   addr_t curr_addr = addr;
2008   while (true) {
2009     size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2010     if (length == 0)
2011       break;
2012     out_str.append(buf, length);
2013     // If we got "length - 1" bytes, we didn't get the whole C string, we need
2014     // to read some more characters
2015     if (length == sizeof(buf) - 1)
2016       curr_addr += length;
2017     else
2018       break;
2019   }
2020   return out_str.size();
2021 }
2022 
2023 size_t Process::ReadStringFromMemory(addr_t addr, char *dst, size_t max_bytes,
2024                                      Status &error, size_t type_width) {
2025   size_t total_bytes_read = 0;
2026   if (dst && max_bytes && type_width && max_bytes >= type_width) {
2027     // Ensure a null terminator independent of the number of bytes that is
2028     // read.
2029     memset(dst, 0, max_bytes);
2030     size_t bytes_left = max_bytes - type_width;
2031 
2032     const char terminator[4] = {'\0', '\0', '\0', '\0'};
2033     assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2034                                                "string with more than 4 bytes "
2035                                                "per character!");
2036 
2037     addr_t curr_addr = addr;
2038     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2039     char *curr_dst = dst;
2040 
2041     error.Clear();
2042     while (bytes_left > 0 && error.Success()) {
2043       addr_t cache_line_bytes_left =
2044           cache_line_size - (curr_addr % cache_line_size);
2045       addr_t bytes_to_read =
2046           std::min<addr_t>(bytes_left, cache_line_bytes_left);
2047       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2048 
2049       if (bytes_read == 0)
2050         break;
2051 
2052       // Search for a null terminator of correct size and alignment in
2053       // bytes_read
2054       size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2055       for (size_t i = aligned_start;
2056            i + type_width <= total_bytes_read + bytes_read; i += type_width)
2057         if (::memcmp(&dst[i], terminator, type_width) == 0) {
2058           error.Clear();
2059           return i;
2060         }
2061 
2062       total_bytes_read += bytes_read;
2063       curr_dst += bytes_read;
2064       curr_addr += bytes_read;
2065       bytes_left -= bytes_read;
2066     }
2067   } else {
2068     if (max_bytes)
2069       error.SetErrorString("invalid arguments");
2070   }
2071   return total_bytes_read;
2072 }
2073 
2074 // Deprecated in favor of ReadStringFromMemory which has wchar support and
2075 // correct code to find null terminators.
2076 size_t Process::ReadCStringFromMemory(addr_t addr, char *dst,
2077                                       size_t dst_max_len,
2078                                       Status &result_error) {
2079   size_t total_cstr_len = 0;
2080   if (dst && dst_max_len) {
2081     result_error.Clear();
2082     // NULL out everything just to be safe
2083     memset(dst, 0, dst_max_len);
2084     Status error;
2085     addr_t curr_addr = addr;
2086     const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2087     size_t bytes_left = dst_max_len - 1;
2088     char *curr_dst = dst;
2089 
2090     while (bytes_left > 0) {
2091       addr_t cache_line_bytes_left =
2092           cache_line_size - (curr_addr % cache_line_size);
2093       addr_t bytes_to_read =
2094           std::min<addr_t>(bytes_left, cache_line_bytes_left);
2095       size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2096 
2097       if (bytes_read == 0) {
2098         result_error = error;
2099         dst[total_cstr_len] = '\0';
2100         break;
2101       }
2102       const size_t len = strlen(curr_dst);
2103 
2104       total_cstr_len += len;
2105 
2106       if (len < bytes_to_read)
2107         break;
2108 
2109       curr_dst += bytes_read;
2110       curr_addr += bytes_read;
2111       bytes_left -= bytes_read;
2112     }
2113   } else {
2114     if (dst == nullptr)
2115       result_error.SetErrorString("invalid arguments");
2116     else
2117       result_error.Clear();
2118   }
2119   return total_cstr_len;
2120 }
2121 
2122 size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2123                                        Status &error) {
2124   if (buf == nullptr || size == 0)
2125     return 0;
2126 
2127   size_t bytes_read = 0;
2128   uint8_t *bytes = (uint8_t *)buf;
2129 
2130   while (bytes_read < size) {
2131     const size_t curr_size = size - bytes_read;
2132     const size_t curr_bytes_read =
2133         DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2134     bytes_read += curr_bytes_read;
2135     if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2136       break;
2137   }
2138 
2139   // Replace any software breakpoint opcodes that fall into this range back
2140   // into "buf" before we return
2141   if (bytes_read > 0)
2142     RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2143   return bytes_read;
2144 }
2145 
2146 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr,
2147                                                 size_t integer_byte_size,
2148                                                 uint64_t fail_value,
2149                                                 Status &error) {
2150   Scalar scalar;
2151   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2152                                   error))
2153     return scalar.ULongLong(fail_value);
2154   return fail_value;
2155 }
2156 
2157 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr,
2158                                              size_t integer_byte_size,
2159                                              int64_t fail_value,
2160                                              Status &error) {
2161   Scalar scalar;
2162   if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2163                                   error))
2164     return scalar.SLongLong(fail_value);
2165   return fail_value;
2166 }
2167 
2168 addr_t Process::ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error) {
2169   Scalar scalar;
2170   if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2171                                   error))
2172     return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2173   return LLDB_INVALID_ADDRESS;
2174 }
2175 
2176 bool Process::WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value,
2177                                    Status &error) {
2178   Scalar scalar;
2179   const uint32_t addr_byte_size = GetAddressByteSize();
2180   if (addr_byte_size <= 4)
2181     scalar = (uint32_t)ptr_value;
2182   else
2183     scalar = ptr_value;
2184   return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2185          addr_byte_size;
2186 }
2187 
2188 size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2189                                    Status &error) {
2190   size_t bytes_written = 0;
2191   const uint8_t *bytes = (const uint8_t *)buf;
2192 
2193   while (bytes_written < size) {
2194     const size_t curr_size = size - bytes_written;
2195     const size_t curr_bytes_written = DoWriteMemory(
2196         addr + bytes_written, bytes + bytes_written, curr_size, error);
2197     bytes_written += curr_bytes_written;
2198     if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2199       break;
2200   }
2201   return bytes_written;
2202 }
2203 
2204 size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2205                             Status &error) {
2206 #if defined(ENABLE_MEMORY_CACHING)
2207   m_memory_cache.Flush(addr, size);
2208 #endif
2209 
2210   if (buf == nullptr || size == 0)
2211     return 0;
2212 
2213   m_mod_id.BumpMemoryID();
2214 
2215   // We need to write any data that would go where any current software traps
2216   // (enabled software breakpoints) any software traps (breakpoints) that we
2217   // may have placed in our tasks memory.
2218 
2219   BreakpointSiteList bp_sites_in_range;
2220   if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2221     return WriteMemoryPrivate(addr, buf, size, error);
2222 
2223   // No breakpoint sites overlap
2224   if (bp_sites_in_range.IsEmpty())
2225     return WriteMemoryPrivate(addr, buf, size, error);
2226 
2227   const uint8_t *ubuf = (const uint8_t *)buf;
2228   uint64_t bytes_written = 0;
2229 
2230   bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2231                              &error](BreakpointSite *bp) -> void {
2232     if (error.Fail())
2233       return;
2234 
2235     addr_t intersect_addr;
2236     size_t intersect_size;
2237     size_t opcode_offset;
2238     const bool intersects = bp->IntersectsRange(
2239         addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2240     UNUSED_IF_ASSERT_DISABLED(intersects);
2241     assert(intersects);
2242     assert(addr <= intersect_addr && intersect_addr < addr + size);
2243     assert(addr < intersect_addr + intersect_size &&
2244            intersect_addr + intersect_size <= addr + size);
2245     assert(opcode_offset + intersect_size <= bp->GetByteSize());
2246 
2247     // Check for bytes before this breakpoint
2248     const addr_t curr_addr = addr + bytes_written;
2249     if (intersect_addr > curr_addr) {
2250       // There are some bytes before this breakpoint that we need to just
2251       // write to memory
2252       size_t curr_size = intersect_addr - curr_addr;
2253       size_t curr_bytes_written =
2254           WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2255       bytes_written += curr_bytes_written;
2256       if (curr_bytes_written != curr_size) {
2257         // We weren't able to write all of the requested bytes, we are
2258         // done looping and will return the number of bytes that we have
2259         // written so far.
2260         if (error.Success())
2261           error.SetErrorToGenericError();
2262       }
2263     }
2264     // Now write any bytes that would cover up any software breakpoints
2265     // directly into the breakpoint opcode buffer
2266     ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2267              intersect_size);
2268     bytes_written += intersect_size;
2269   });
2270 
2271   // Write any remaining bytes after the last breakpoint if we have any left
2272   if (bytes_written < size)
2273     bytes_written +=
2274         WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2275                            size - bytes_written, error);
2276 
2277   return bytes_written;
2278 }
2279 
2280 size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2281                                     size_t byte_size, Status &error) {
2282   if (byte_size == UINT32_MAX)
2283     byte_size = scalar.GetByteSize();
2284   if (byte_size > 0) {
2285     uint8_t buf[32];
2286     const size_t mem_size =
2287         scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2288     if (mem_size > 0)
2289       return WriteMemory(addr, buf, mem_size, error);
2290     else
2291       error.SetErrorString("failed to get scalar as memory data");
2292   } else {
2293     error.SetErrorString("invalid scalar value");
2294   }
2295   return 0;
2296 }
2297 
2298 size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2299                                             bool is_signed, Scalar &scalar,
2300                                             Status &error) {
2301   uint64_t uval = 0;
2302   if (byte_size == 0) {
2303     error.SetErrorString("byte size is zero");
2304   } else if (byte_size & (byte_size - 1)) {
2305     error.SetErrorStringWithFormat("byte size %u is not a power of 2",
2306                                    byte_size);
2307   } else if (byte_size <= sizeof(uval)) {
2308     const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2309     if (bytes_read == byte_size) {
2310       DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2311                          GetAddressByteSize());
2312       lldb::offset_t offset = 0;
2313       if (byte_size <= 4)
2314         scalar = data.GetMaxU32(&offset, byte_size);
2315       else
2316         scalar = data.GetMaxU64(&offset, byte_size);
2317       if (is_signed)
2318         scalar.SignExtend(byte_size * 8);
2319       return bytes_read;
2320     }
2321   } else {
2322     error.SetErrorStringWithFormat(
2323         "byte size of %u is too large for integer scalar type", byte_size);
2324   }
2325   return 0;
2326 }
2327 
2328 Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2329   Status error;
2330   for (const auto &Entry : entries) {
2331     WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2332                 error);
2333     if (!error.Success())
2334       break;
2335   }
2336   return error;
2337 }
2338 
2339 #define USE_ALLOCATE_MEMORY_CACHE 1
2340 addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2341                                Status &error) {
2342   if (GetPrivateState() != eStateStopped) {
2343     error.SetErrorToGenericError();
2344     return LLDB_INVALID_ADDRESS;
2345   }
2346 
2347 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2348   return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2349 #else
2350   addr_t allocated_addr = DoAllocateMemory(size, permissions, error);
2351   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2352   LLDB_LOGF(log,
2353             "Process::AllocateMemory(size=%" PRIu64
2354             ", permissions=%s) => 0x%16.16" PRIx64
2355             " (m_stop_id = %u m_memory_id = %u)",
2356             (uint64_t)size, GetPermissionsAsCString(permissions),
2357             (uint64_t)allocated_addr, m_mod_id.GetStopID(),
2358             m_mod_id.GetMemoryID());
2359   return allocated_addr;
2360 #endif
2361 }
2362 
2363 addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2364                                 Status &error) {
2365   addr_t return_addr = AllocateMemory(size, permissions, error);
2366   if (error.Success()) {
2367     std::string buffer(size, 0);
2368     WriteMemory(return_addr, buffer.c_str(), size, error);
2369   }
2370   return return_addr;
2371 }
2372 
2373 bool Process::CanJIT() {
2374   if (m_can_jit == eCanJITDontKnow) {
2375     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2376     Status err;
2377 
2378     uint64_t allocated_memory = AllocateMemory(
2379         8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2380         err);
2381 
2382     if (err.Success()) {
2383       m_can_jit = eCanJITYes;
2384       LLDB_LOGF(log,
2385                 "Process::%s pid %" PRIu64
2386                 " allocation test passed, CanJIT () is true",
2387                 __FUNCTION__, GetID());
2388     } else {
2389       m_can_jit = eCanJITNo;
2390       LLDB_LOGF(log,
2391                 "Process::%s pid %" PRIu64
2392                 " allocation test failed, CanJIT () is false: %s",
2393                 __FUNCTION__, GetID(), err.AsCString());
2394     }
2395 
2396     DeallocateMemory(allocated_memory);
2397   }
2398 
2399   return m_can_jit == eCanJITYes;
2400 }
2401 
2402 void Process::SetCanJIT(bool can_jit) {
2403   m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2404 }
2405 
2406 void Process::SetCanRunCode(bool can_run_code) {
2407   SetCanJIT(can_run_code);
2408   m_can_interpret_function_calls = can_run_code;
2409 }
2410 
2411 Status Process::DeallocateMemory(addr_t ptr) {
2412   Status error;
2413 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2414   if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2415     error.SetErrorStringWithFormat(
2416         "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2417   }
2418 #else
2419   error = DoDeallocateMemory(ptr);
2420 
2421   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2422   LLDB_LOGF(log,
2423             "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2424             ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2425             ptr, error.AsCString("SUCCESS"), m_mod_id.GetStopID(),
2426             m_mod_id.GetMemoryID());
2427 #endif
2428   return error;
2429 }
2430 
2431 ModuleSP Process::ReadModuleFromMemory(const FileSpec &file_spec,
2432                                        lldb::addr_t header_addr,
2433                                        size_t size_to_read) {
2434   Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
2435   if (log) {
2436     LLDB_LOGF(log,
2437               "Process::ReadModuleFromMemory reading %s binary from memory",
2438               file_spec.GetPath().c_str());
2439   }
2440   ModuleSP module_sp(new Module(file_spec, ArchSpec()));
2441   if (module_sp) {
2442     Status error;
2443     ObjectFile *objfile = module_sp->GetMemoryObjectFile(
2444         shared_from_this(), header_addr, error, size_to_read);
2445     if (objfile)
2446       return module_sp;
2447   }
2448   return ModuleSP();
2449 }
2450 
2451 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr,
2452                                         uint32_t &permissions) {
2453   MemoryRegionInfo range_info;
2454   permissions = 0;
2455   Status error(GetMemoryRegionInfo(load_addr, range_info));
2456   if (!error.Success())
2457     return false;
2458   if (range_info.GetReadable() == MemoryRegionInfo::eDontKnow ||
2459       range_info.GetWritable() == MemoryRegionInfo::eDontKnow ||
2460       range_info.GetExecutable() == MemoryRegionInfo::eDontKnow) {
2461     return false;
2462   }
2463 
2464   if (range_info.GetReadable() == MemoryRegionInfo::eYes)
2465     permissions |= lldb::ePermissionsReadable;
2466 
2467   if (range_info.GetWritable() == MemoryRegionInfo::eYes)
2468     permissions |= lldb::ePermissionsWritable;
2469 
2470   if (range_info.GetExecutable() == MemoryRegionInfo::eYes)
2471     permissions |= lldb::ePermissionsExecutable;
2472 
2473   return true;
2474 }
2475 
2476 Status Process::EnableWatchpoint(Watchpoint *watchpoint, bool notify) {
2477   Status error;
2478   error.SetErrorString("watchpoints are not supported");
2479   return error;
2480 }
2481 
2482 Status Process::DisableWatchpoint(Watchpoint *watchpoint, bool notify) {
2483   Status error;
2484   error.SetErrorString("watchpoints are not supported");
2485   return error;
2486 }
2487 
2488 StateType
2489 Process::WaitForProcessStopPrivate(EventSP &event_sp,
2490                                    const Timeout<std::micro> &timeout) {
2491   StateType state;
2492 
2493   while (true) {
2494     event_sp.reset();
2495     state = GetStateChangedEventsPrivate(event_sp, timeout);
2496 
2497     if (StateIsStoppedState(state, false))
2498       break;
2499 
2500     // If state is invalid, then we timed out
2501     if (state == eStateInvalid)
2502       break;
2503 
2504     if (event_sp)
2505       HandlePrivateEvent(event_sp);
2506   }
2507   return state;
2508 }
2509 
2510 void Process::LoadOperatingSystemPlugin(bool flush) {
2511   if (flush)
2512     m_thread_list.Clear();
2513   m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2514   if (flush)
2515     Flush();
2516 }
2517 
2518 Status Process::Launch(ProcessLaunchInfo &launch_info) {
2519   Status error;
2520   m_abi_sp.reset();
2521   m_dyld_up.reset();
2522   m_jit_loaders_up.reset();
2523   m_system_runtime_up.reset();
2524   m_os_up.reset();
2525   m_process_input_reader.reset();
2526 
2527   Module *exe_module = GetTarget().GetExecutableModulePointer();
2528   if (!exe_module) {
2529     error.SetErrorString("executable module does not exist");
2530     return error;
2531   }
2532 
2533   char local_exec_file_path[PATH_MAX];
2534   char platform_exec_file_path[PATH_MAX];
2535   exe_module->GetFileSpec().GetPath(local_exec_file_path,
2536                                     sizeof(local_exec_file_path));
2537   exe_module->GetPlatformFileSpec().GetPath(platform_exec_file_path,
2538                                             sizeof(platform_exec_file_path));
2539   if (FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2540     // Install anything that might need to be installed prior to launching.
2541     // For host systems, this will do nothing, but if we are connected to a
2542     // remote platform it will install any needed binaries
2543     error = GetTarget().Install(&launch_info);
2544     if (error.Fail())
2545       return error;
2546 
2547     if (PrivateStateThreadIsValid())
2548       PausePrivateStateThread();
2549 
2550     error = WillLaunch(exe_module);
2551     if (error.Success()) {
2552       const bool restarted = false;
2553       SetPublicState(eStateLaunching, restarted);
2554       m_should_detach = false;
2555 
2556       if (m_public_run_lock.TrySetRunning()) {
2557         // Now launch using these arguments.
2558         error = DoLaunch(exe_module, launch_info);
2559       } else {
2560         // This shouldn't happen
2561         error.SetErrorString("failed to acquire process run lock");
2562       }
2563 
2564       if (error.Fail()) {
2565         if (GetID() != LLDB_INVALID_PROCESS_ID) {
2566           SetID(LLDB_INVALID_PROCESS_ID);
2567           const char *error_string = error.AsCString();
2568           if (error_string == nullptr)
2569             error_string = "launch failed";
2570           SetExitStatus(-1, error_string);
2571         }
2572       } else {
2573         EventSP event_sp;
2574 
2575         // Now wait for the process to launch and return control to us, and then
2576         // call DidLaunch:
2577         StateType state = WaitForProcessStopPrivate(event_sp, seconds(10));
2578 
2579         if (state == eStateInvalid || !event_sp) {
2580           // We were able to launch the process, but we failed to catch the
2581           // initial stop.
2582           error.SetErrorString("failed to catch stop after launch");
2583           SetExitStatus(0, "failed to catch stop after launch");
2584           Destroy(false);
2585         } else if (state == eStateStopped || state == eStateCrashed) {
2586           DidLaunch();
2587 
2588           DynamicLoader *dyld = GetDynamicLoader();
2589           if (dyld)
2590             dyld->DidLaunch();
2591 
2592           GetJITLoaders().DidLaunch();
2593 
2594           SystemRuntime *system_runtime = GetSystemRuntime();
2595           if (system_runtime)
2596             system_runtime->DidLaunch();
2597 
2598           if (!m_os_up)
2599             LoadOperatingSystemPlugin(false);
2600 
2601           // We successfully launched the process and stopped, now it the
2602           // right time to set up signal filters before resuming.
2603           UpdateAutomaticSignalFiltering();
2604 
2605           // Note, the stop event was consumed above, but not handled. This
2606           // was done to give DidLaunch a chance to run. The target is either
2607           // stopped or crashed. Directly set the state.  This is done to
2608           // prevent a stop message with a bunch of spurious output on thread
2609           // status, as well as not pop a ProcessIOHandler.
2610           SetPublicState(state, false);
2611 
2612           if (PrivateStateThreadIsValid())
2613             ResumePrivateStateThread();
2614           else
2615             StartPrivateStateThread();
2616 
2617           // Target was stopped at entry as was intended. Need to notify the
2618           // listeners about it.
2619           if (state == eStateStopped &&
2620               launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2621             HandlePrivateEvent(event_sp);
2622         } else if (state == eStateExited) {
2623           // We exited while trying to launch somehow.  Don't call DidLaunch
2624           // as that's not likely to work, and return an invalid pid.
2625           HandlePrivateEvent(event_sp);
2626         }
2627       }
2628     }
2629   } else {
2630     error.SetErrorStringWithFormat("file doesn't exist: '%s'",
2631                                    local_exec_file_path);
2632   }
2633 
2634   return error;
2635 }
2636 
2637 Status Process::LoadCore() {
2638   Status error = DoLoadCore();
2639   if (error.Success()) {
2640     ListenerSP listener_sp(
2641         Listener::MakeListener("lldb.process.load_core_listener"));
2642     HijackProcessEvents(listener_sp);
2643 
2644     if (PrivateStateThreadIsValid())
2645       ResumePrivateStateThread();
2646     else
2647       StartPrivateStateThread();
2648 
2649     DynamicLoader *dyld = GetDynamicLoader();
2650     if (dyld)
2651       dyld->DidAttach();
2652 
2653     GetJITLoaders().DidAttach();
2654 
2655     SystemRuntime *system_runtime = GetSystemRuntime();
2656     if (system_runtime)
2657       system_runtime->DidAttach();
2658 
2659     if (!m_os_up)
2660       LoadOperatingSystemPlugin(false);
2661 
2662     // We successfully loaded a core file, now pretend we stopped so we can
2663     // show all of the threads in the core file and explore the crashed state.
2664     SetPrivateState(eStateStopped);
2665 
2666     // Wait for a stopped event since we just posted one above...
2667     lldb::EventSP event_sp;
2668     StateType state =
2669         WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp);
2670 
2671     if (!StateIsStoppedState(state, false)) {
2672       Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2673       LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
2674                 StateAsCString(state));
2675       error.SetErrorString(
2676           "Did not get stopped event after loading the core file.");
2677     }
2678     RestoreProcessEvents();
2679   }
2680   return error;
2681 }
2682 
2683 DynamicLoader *Process::GetDynamicLoader() {
2684   if (!m_dyld_up)
2685     m_dyld_up.reset(DynamicLoader::FindPlugin(this, nullptr));
2686   return m_dyld_up.get();
2687 }
2688 
2689 DataExtractor Process::GetAuxvData() { return DataExtractor(); }
2690 
2691 JITLoaderList &Process::GetJITLoaders() {
2692   if (!m_jit_loaders_up) {
2693     m_jit_loaders_up.reset(new JITLoaderList());
2694     JITLoader::LoadPlugins(this, *m_jit_loaders_up);
2695   }
2696   return *m_jit_loaders_up;
2697 }
2698 
2699 SystemRuntime *Process::GetSystemRuntime() {
2700   if (!m_system_runtime_up)
2701     m_system_runtime_up.reset(SystemRuntime::FindPlugin(this));
2702   return m_system_runtime_up.get();
2703 }
2704 
2705 Process::AttachCompletionHandler::AttachCompletionHandler(Process *process,
2706                                                           uint32_t exec_count)
2707     : NextEventAction(process), m_exec_count(exec_count) {
2708   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2709   LLDB_LOGF(
2710       log,
2711       "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
2712       __FUNCTION__, static_cast<void *>(process), exec_count);
2713 }
2714 
2715 Process::NextEventAction::EventActionResult
2716 Process::AttachCompletionHandler::PerformAction(lldb::EventSP &event_sp) {
2717   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2718 
2719   StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
2720   LLDB_LOGF(log,
2721             "Process::AttachCompletionHandler::%s called with state %s (%d)",
2722             __FUNCTION__, StateAsCString(state), static_cast<int>(state));
2723 
2724   switch (state) {
2725   case eStateAttaching:
2726     return eEventActionSuccess;
2727 
2728   case eStateRunning:
2729   case eStateConnected:
2730     return eEventActionRetry;
2731 
2732   case eStateStopped:
2733   case eStateCrashed:
2734     // During attach, prior to sending the eStateStopped event,
2735     // lldb_private::Process subclasses must set the new process ID.
2736     assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
2737     // We don't want these events to be reported, so go set the
2738     // ShouldReportStop here:
2739     m_process->GetThreadList().SetShouldReportStop(eVoteNo);
2740 
2741     if (m_exec_count > 0) {
2742       --m_exec_count;
2743 
2744       LLDB_LOGF(log,
2745                 "Process::AttachCompletionHandler::%s state %s: reduced "
2746                 "remaining exec count to %" PRIu32 ", requesting resume",
2747                 __FUNCTION__, StateAsCString(state), m_exec_count);
2748 
2749       RequestResume();
2750       return eEventActionRetry;
2751     } else {
2752       LLDB_LOGF(log,
2753                 "Process::AttachCompletionHandler::%s state %s: no more "
2754                 "execs expected to start, continuing with attach",
2755                 __FUNCTION__, StateAsCString(state));
2756 
2757       m_process->CompleteAttach();
2758       return eEventActionSuccess;
2759     }
2760     break;
2761 
2762   default:
2763   case eStateExited:
2764   case eStateInvalid:
2765     break;
2766   }
2767 
2768   m_exit_string.assign("No valid Process");
2769   return eEventActionExit;
2770 }
2771 
2772 Process::NextEventAction::EventActionResult
2773 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2774   return eEventActionSuccess;
2775 }
2776 
2777 const char *Process::AttachCompletionHandler::GetExitString() {
2778   return m_exit_string.c_str();
2779 }
2780 
2781 ListenerSP ProcessAttachInfo::GetListenerForProcess(Debugger &debugger) {
2782   if (m_listener_sp)
2783     return m_listener_sp;
2784   else
2785     return debugger.GetListener();
2786 }
2787 
2788 Status Process::Attach(ProcessAttachInfo &attach_info) {
2789   m_abi_sp.reset();
2790   m_process_input_reader.reset();
2791   m_dyld_up.reset();
2792   m_jit_loaders_up.reset();
2793   m_system_runtime_up.reset();
2794   m_os_up.reset();
2795 
2796   lldb::pid_t attach_pid = attach_info.GetProcessID();
2797   Status error;
2798   if (attach_pid == LLDB_INVALID_PROCESS_ID) {
2799     char process_name[PATH_MAX];
2800 
2801     if (attach_info.GetExecutableFile().GetPath(process_name,
2802                                                 sizeof(process_name))) {
2803       const bool wait_for_launch = attach_info.GetWaitForLaunch();
2804 
2805       if (wait_for_launch) {
2806         error = WillAttachToProcessWithName(process_name, wait_for_launch);
2807         if (error.Success()) {
2808           if (m_public_run_lock.TrySetRunning()) {
2809             m_should_detach = true;
2810             const bool restarted = false;
2811             SetPublicState(eStateAttaching, restarted);
2812             // Now attach using these arguments.
2813             error = DoAttachToProcessWithName(process_name, attach_info);
2814           } else {
2815             // This shouldn't happen
2816             error.SetErrorString("failed to acquire process run lock");
2817           }
2818 
2819           if (error.Fail()) {
2820             if (GetID() != LLDB_INVALID_PROCESS_ID) {
2821               SetID(LLDB_INVALID_PROCESS_ID);
2822               if (error.AsCString() == nullptr)
2823                 error.SetErrorString("attach failed");
2824 
2825               SetExitStatus(-1, error.AsCString());
2826             }
2827           } else {
2828             SetNextEventAction(new Process::AttachCompletionHandler(
2829                 this, attach_info.GetResumeCount()));
2830             StartPrivateStateThread();
2831           }
2832           return error;
2833         }
2834       } else {
2835         ProcessInstanceInfoList process_infos;
2836         PlatformSP platform_sp(GetTarget().GetPlatform());
2837 
2838         if (platform_sp) {
2839           ProcessInstanceInfoMatch match_info;
2840           match_info.GetProcessInfo() = attach_info;
2841           match_info.SetNameMatchType(NameMatch::Equals);
2842           platform_sp->FindProcesses(match_info, process_infos);
2843           const uint32_t num_matches = process_infos.size();
2844           if (num_matches == 1) {
2845             attach_pid = process_infos[0].GetProcessID();
2846             // Fall through and attach using the above process ID
2847           } else {
2848             match_info.GetProcessInfo().GetExecutableFile().GetPath(
2849                 process_name, sizeof(process_name));
2850             if (num_matches > 1) {
2851               StreamString s;
2852               ProcessInstanceInfo::DumpTableHeader(s, true, false);
2853               for (size_t i = 0; i < num_matches; i++) {
2854                 process_infos[i].DumpAsTableRow(
2855                     s, platform_sp->GetUserIDResolver(), true, false);
2856               }
2857               error.SetErrorStringWithFormat(
2858                   "more than one process named %s:\n%s", process_name,
2859                   s.GetData());
2860             } else
2861               error.SetErrorStringWithFormat(
2862                   "could not find a process named %s", process_name);
2863           }
2864         } else {
2865           error.SetErrorString(
2866               "invalid platform, can't find processes by name");
2867           return error;
2868         }
2869       }
2870     } else {
2871       error.SetErrorString("invalid process name");
2872     }
2873   }
2874 
2875   if (attach_pid != LLDB_INVALID_PROCESS_ID) {
2876     error = WillAttachToProcessWithID(attach_pid);
2877     if (error.Success()) {
2878 
2879       if (m_public_run_lock.TrySetRunning()) {
2880         // Now attach using these arguments.
2881         m_should_detach = true;
2882         const bool restarted = false;
2883         SetPublicState(eStateAttaching, restarted);
2884         error = DoAttachToProcessWithID(attach_pid, attach_info);
2885       } else {
2886         // This shouldn't happen
2887         error.SetErrorString("failed to acquire process run lock");
2888       }
2889 
2890       if (error.Success()) {
2891         SetNextEventAction(new Process::AttachCompletionHandler(
2892             this, attach_info.GetResumeCount()));
2893         StartPrivateStateThread();
2894       } else {
2895         if (GetID() != LLDB_INVALID_PROCESS_ID)
2896           SetID(LLDB_INVALID_PROCESS_ID);
2897 
2898         const char *error_string = error.AsCString();
2899         if (error_string == nullptr)
2900           error_string = "attach failed";
2901 
2902         SetExitStatus(-1, error_string);
2903       }
2904     }
2905   }
2906   return error;
2907 }
2908 
2909 void Process::CompleteAttach() {
2910   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
2911                                                   LIBLLDB_LOG_TARGET));
2912   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
2913 
2914   // Let the process subclass figure out at much as it can about the process
2915   // before we go looking for a dynamic loader plug-in.
2916   ArchSpec process_arch;
2917   DidAttach(process_arch);
2918 
2919   if (process_arch.IsValid()) {
2920     GetTarget().SetArchitecture(process_arch);
2921     if (log) {
2922       const char *triple_str = process_arch.GetTriple().getTriple().c_str();
2923       LLDB_LOGF(log,
2924                 "Process::%s replacing process architecture with DidAttach() "
2925                 "architecture: %s",
2926                 __FUNCTION__, triple_str ? triple_str : "<null>");
2927     }
2928   }
2929 
2930   // We just attached.  If we have a platform, ask it for the process
2931   // architecture, and if it isn't the same as the one we've already set,
2932   // switch architectures.
2933   PlatformSP platform_sp(GetTarget().GetPlatform());
2934   assert(platform_sp);
2935   if (platform_sp) {
2936     const ArchSpec &target_arch = GetTarget().GetArchitecture();
2937     if (target_arch.IsValid() &&
2938         !platform_sp->IsCompatibleArchitecture(target_arch, false, nullptr)) {
2939       ArchSpec platform_arch;
2940       platform_sp =
2941           platform_sp->GetPlatformForArchitecture(target_arch, &platform_arch);
2942       if (platform_sp) {
2943         GetTarget().SetPlatform(platform_sp);
2944         GetTarget().SetArchitecture(platform_arch);
2945         LLDB_LOGF(log,
2946                   "Process::%s switching platform to %s and architecture "
2947                   "to %s based on info from attach",
2948                   __FUNCTION__, platform_sp->GetName().AsCString(""),
2949                   platform_arch.GetTriple().getTriple().c_str());
2950       }
2951     } else if (!process_arch.IsValid()) {
2952       ProcessInstanceInfo process_info;
2953       GetProcessInfo(process_info);
2954       const ArchSpec &process_arch = process_info.GetArchitecture();
2955       if (process_arch.IsValid() &&
2956           !GetTarget().GetArchitecture().IsExactMatch(process_arch)) {
2957         GetTarget().SetArchitecture(process_arch);
2958         LLDB_LOGF(log,
2959                   "Process::%s switching architecture to %s based on info "
2960                   "the platform retrieved for pid %" PRIu64,
2961                   __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
2962                   GetID());
2963       }
2964     }
2965   }
2966 
2967   // We have completed the attach, now it is time to find the dynamic loader
2968   // plug-in
2969   DynamicLoader *dyld = GetDynamicLoader();
2970   if (dyld) {
2971     dyld->DidAttach();
2972     if (log) {
2973       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2974       LLDB_LOGF(log,
2975                 "Process::%s after DynamicLoader::DidAttach(), target "
2976                 "executable is %s (using %s plugin)",
2977                 __FUNCTION__,
2978                 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2979                               : "<none>",
2980                 dyld->GetPluginName().AsCString("<unnamed>"));
2981     }
2982   }
2983 
2984   GetJITLoaders().DidAttach();
2985 
2986   SystemRuntime *system_runtime = GetSystemRuntime();
2987   if (system_runtime) {
2988     system_runtime->DidAttach();
2989     if (log) {
2990       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
2991       LLDB_LOGF(log,
2992                 "Process::%s after SystemRuntime::DidAttach(), target "
2993                 "executable is %s (using %s plugin)",
2994                 __FUNCTION__,
2995                 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
2996                               : "<none>",
2997                 system_runtime->GetPluginName().AsCString("<unnamed>"));
2998     }
2999   }
3000 
3001   if (!m_os_up) {
3002     LoadOperatingSystemPlugin(false);
3003     if (m_os_up) {
3004       // Somebody might have gotten threads before now, but we need to force the
3005       // update after we've loaded the OperatingSystem plugin or it won't get a
3006       // chance to process the threads.
3007       m_thread_list.Clear();
3008       UpdateThreadListIfNeeded();
3009     }
3010   }
3011   // Figure out which one is the executable, and set that in our target:
3012   const ModuleList &target_modules = GetTarget().GetImages();
3013   std::lock_guard<std::recursive_mutex> guard(target_modules.GetMutex());
3014   size_t num_modules = target_modules.GetSize();
3015   ModuleSP new_executable_module_sp;
3016 
3017   for (size_t i = 0; i < num_modules; i++) {
3018     ModuleSP module_sp(target_modules.GetModuleAtIndexUnlocked(i));
3019     if (module_sp && module_sp->IsExecutable()) {
3020       if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3021         new_executable_module_sp = module_sp;
3022       break;
3023     }
3024   }
3025   if (new_executable_module_sp) {
3026     GetTarget().SetExecutableModule(new_executable_module_sp,
3027                                     eLoadDependentsNo);
3028     if (log) {
3029       ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3030       LLDB_LOGF(
3031           log,
3032           "Process::%s after looping through modules, target executable is %s",
3033           __FUNCTION__,
3034           exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3035                         : "<none>");
3036     }
3037   }
3038 }
3039 
3040 Status Process::ConnectRemote(Stream *strm, llvm::StringRef remote_url) {
3041   m_abi_sp.reset();
3042   m_process_input_reader.reset();
3043 
3044   // Find the process and its architecture.  Make sure it matches the
3045   // architecture of the current Target, and if not adjust it.
3046 
3047   Status error(DoConnectRemote(strm, remote_url));
3048   if (error.Success()) {
3049     if (GetID() != LLDB_INVALID_PROCESS_ID) {
3050       EventSP event_sp;
3051       StateType state = WaitForProcessStopPrivate(event_sp, llvm::None);
3052 
3053       if (state == eStateStopped || state == eStateCrashed) {
3054         // If we attached and actually have a process on the other end, then
3055         // this ended up being the equivalent of an attach.
3056         CompleteAttach();
3057 
3058         // This delays passing the stopped event to listeners till
3059         // CompleteAttach gets a chance to complete...
3060         HandlePrivateEvent(event_sp);
3061       }
3062     }
3063 
3064     if (PrivateStateThreadIsValid())
3065       ResumePrivateStateThread();
3066     else
3067       StartPrivateStateThread();
3068   }
3069   return error;
3070 }
3071 
3072 Status Process::PrivateResume() {
3073   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS |
3074                                                   LIBLLDB_LOG_STEP));
3075   LLDB_LOGF(log,
3076             "Process::PrivateResume() m_stop_id = %u, public state: %s "
3077             "private state: %s",
3078             m_mod_id.GetStopID(), StateAsCString(m_public_state.GetValue()),
3079             StateAsCString(m_private_state.GetValue()));
3080 
3081   // If signals handing status changed we might want to update our signal
3082   // filters before resuming.
3083   UpdateAutomaticSignalFiltering();
3084 
3085   Status error(WillResume());
3086   // Tell the process it is about to resume before the thread list
3087   if (error.Success()) {
3088     // Now let the thread list know we are about to resume so it can let all of
3089     // our threads know that they are about to be resumed. Threads will each be
3090     // called with Thread::WillResume(StateType) where StateType contains the
3091     // state that they are supposed to have when the process is resumed
3092     // (suspended/running/stepping). Threads should also check their resume
3093     // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3094     // start back up with a signal.
3095     if (m_thread_list.WillResume()) {
3096       // Last thing, do the PreResumeActions.
3097       if (!RunPreResumeActions()) {
3098         error.SetErrorStringWithFormat(
3099             "Process::PrivateResume PreResumeActions failed, not resuming.");
3100       } else {
3101         m_mod_id.BumpResumeID();
3102         error = DoResume();
3103         if (error.Success()) {
3104           DidResume();
3105           m_thread_list.DidResume();
3106           LLDB_LOGF(log, "Process thinks the process has resumed.");
3107         } else {
3108           LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3109           return error;
3110         }
3111       }
3112     } else {
3113       // Somebody wanted to run without running (e.g. we were faking a step
3114       // from one frame of a set of inlined frames that share the same PC to
3115       // another.)  So generate a continue & a stopped event, and let the world
3116       // handle them.
3117       LLDB_LOGF(log,
3118                 "Process::PrivateResume() asked to simulate a start & stop.");
3119 
3120       SetPrivateState(eStateRunning);
3121       SetPrivateState(eStateStopped);
3122     }
3123   } else
3124     LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3125               error.AsCString("<unknown error>"));
3126   return error;
3127 }
3128 
3129 Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3130   if (!StateIsRunningState(m_public_state.GetValue()))
3131     return Status("Process is not running.");
3132 
3133   // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3134   // case it was already set and some thread plan logic calls halt on its own.
3135   m_clear_thread_plans_on_stop |= clear_thread_plans;
3136 
3137   ListenerSP halt_listener_sp(
3138       Listener::MakeListener("lldb.process.halt_listener"));
3139   HijackProcessEvents(halt_listener_sp);
3140 
3141   EventSP event_sp;
3142 
3143   SendAsyncInterrupt();
3144 
3145   if (m_public_state.GetValue() == eStateAttaching) {
3146     // Don't hijack and eat the eStateExited as the code that was doing the
3147     // attach will be waiting for this event...
3148     RestoreProcessEvents();
3149     SetExitStatus(SIGKILL, "Cancelled async attach.");
3150     Destroy(false);
3151     return Status();
3152   }
3153 
3154   // Wait for 10 second for the process to stop.
3155   StateType state = WaitForProcessToStop(
3156       seconds(10), &event_sp, true, halt_listener_sp, nullptr, use_run_lock);
3157   RestoreProcessEvents();
3158 
3159   if (state == eStateInvalid || !event_sp) {
3160     // We timed out and didn't get a stop event...
3161     return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3162   }
3163 
3164   BroadcastEvent(event_sp);
3165 
3166   return Status();
3167 }
3168 
3169 Status Process::StopForDestroyOrDetach(lldb::EventSP &exit_event_sp) {
3170   Status error;
3171 
3172   // Check both the public & private states here.  If we're hung evaluating an
3173   // expression, for instance, then the public state will be stopped, but we
3174   // still need to interrupt.
3175   if (m_public_state.GetValue() == eStateRunning ||
3176       m_private_state.GetValue() == eStateRunning) {
3177     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3178     LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3179 
3180     ListenerSP listener_sp(
3181         Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3182     HijackProcessEvents(listener_sp);
3183 
3184     SendAsyncInterrupt();
3185 
3186     // Consume the interrupt event.
3187     StateType state =
3188         WaitForProcessToStop(seconds(10), &exit_event_sp, true, listener_sp);
3189 
3190     RestoreProcessEvents();
3191 
3192     // If the process exited while we were waiting for it to stop, put the
3193     // exited event into the shared pointer passed in and return.  Our caller
3194     // doesn't need to do anything else, since they don't have a process
3195     // anymore...
3196 
3197     if (state == eStateExited || m_private_state.GetValue() == eStateExited) {
3198       LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3199                 __FUNCTION__);
3200       return error;
3201     } else
3202       exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3203 
3204     if (state != eStateStopped) {
3205       LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3206                 StateAsCString(state));
3207       // If we really couldn't stop the process then we should just error out
3208       // here, but if the lower levels just bobbled sending the event and we
3209       // really are stopped, then continue on.
3210       StateType private_state = m_private_state.GetValue();
3211       if (private_state != eStateStopped) {
3212         return Status(
3213             "Attempt to stop the target in order to detach timed out. "
3214             "State = %s",
3215             StateAsCString(GetState()));
3216       }
3217     }
3218   }
3219   return error;
3220 }
3221 
3222 Status Process::Detach(bool keep_stopped) {
3223   EventSP exit_event_sp;
3224   Status error;
3225   m_destroy_in_process = true;
3226 
3227   error = WillDetach();
3228 
3229   if (error.Success()) {
3230     if (DetachRequiresHalt()) {
3231       error = StopForDestroyOrDetach(exit_event_sp);
3232       if (!error.Success()) {
3233         m_destroy_in_process = false;
3234         return error;
3235       } else if (exit_event_sp) {
3236         // We shouldn't need to do anything else here.  There's no process left
3237         // to detach from...
3238         StopPrivateStateThread();
3239         m_destroy_in_process = false;
3240         return error;
3241       }
3242     }
3243 
3244     m_thread_list.DiscardThreadPlans();
3245     DisableAllBreakpointSites();
3246 
3247     error = DoDetach(keep_stopped);
3248     if (error.Success()) {
3249       DidDetach();
3250       StopPrivateStateThread();
3251     } else {
3252       return error;
3253     }
3254   }
3255   m_destroy_in_process = false;
3256 
3257   // If we exited when we were waiting for a process to stop, then forward the
3258   // event here so we don't lose the event
3259   if (exit_event_sp) {
3260     // Directly broadcast our exited event because we shut down our private
3261     // state thread above
3262     BroadcastEvent(exit_event_sp);
3263   }
3264 
3265   // If we have been interrupted (to kill us) in the middle of running, we may
3266   // not end up propagating the last events through the event system, in which
3267   // case we might strand the write lock.  Unlock it here so when we do to tear
3268   // down the process we don't get an error destroying the lock.
3269 
3270   m_public_run_lock.SetStopped();
3271   return error;
3272 }
3273 
3274 Status Process::Destroy(bool force_kill) {
3275   // If we've already called Process::Finalize then there's nothing useful to
3276   // be done here.  Finalize has actually called Destroy already.
3277   if (m_finalize_called)
3278     return {};
3279 
3280   // Tell ourselves we are in the process of destroying the process, so that we
3281   // don't do any unnecessary work that might hinder the destruction.  Remember
3282   // to set this back to false when we are done.  That way if the attempt
3283   // failed and the process stays around for some reason it won't be in a
3284   // confused state.
3285 
3286   if (force_kill)
3287     m_should_detach = false;
3288 
3289   if (GetShouldDetach()) {
3290     // FIXME: This will have to be a process setting:
3291     bool keep_stopped = false;
3292     Detach(keep_stopped);
3293   }
3294 
3295   m_destroy_in_process = true;
3296 
3297   Status error(WillDestroy());
3298   if (error.Success()) {
3299     EventSP exit_event_sp;
3300     if (DestroyRequiresHalt()) {
3301       error = StopForDestroyOrDetach(exit_event_sp);
3302     }
3303 
3304     if (m_public_state.GetValue() != eStateRunning) {
3305       // Ditch all thread plans, and remove all our breakpoints: in case we
3306       // have to restart the target to kill it, we don't want it hitting a
3307       // breakpoint... Only do this if we've stopped, however, since if we
3308       // didn't manage to halt it above, then we're not going to have much luck
3309       // doing this now.
3310       m_thread_list.DiscardThreadPlans();
3311       DisableAllBreakpointSites();
3312     }
3313 
3314     error = DoDestroy();
3315     if (error.Success()) {
3316       DidDestroy();
3317       StopPrivateStateThread();
3318     }
3319     m_stdio_communication.Disconnect();
3320     m_stdio_communication.StopReadThread();
3321     m_stdin_forward = false;
3322 
3323     if (m_process_input_reader) {
3324       m_process_input_reader->SetIsDone(true);
3325       m_process_input_reader->Cancel();
3326       m_process_input_reader.reset();
3327     }
3328 
3329     // If we exited when we were waiting for a process to stop, then forward
3330     // the event here so we don't lose the event
3331     if (exit_event_sp) {
3332       // Directly broadcast our exited event because we shut down our private
3333       // state thread above
3334       BroadcastEvent(exit_event_sp);
3335     }
3336 
3337     // If we have been interrupted (to kill us) in the middle of running, we
3338     // may not end up propagating the last events through the event system, in
3339     // which case we might strand the write lock.  Unlock it here so when we do
3340     // to tear down the process we don't get an error destroying the lock.
3341     m_public_run_lock.SetStopped();
3342   }
3343 
3344   m_destroy_in_process = false;
3345 
3346   return error;
3347 }
3348 
3349 Status Process::Signal(int signal) {
3350   Status error(WillSignal());
3351   if (error.Success()) {
3352     error = DoSignal(signal);
3353     if (error.Success())
3354       DidSignal();
3355   }
3356   return error;
3357 }
3358 
3359 void Process::SetUnixSignals(UnixSignalsSP &&signals_sp) {
3360   assert(signals_sp && "null signals_sp");
3361   m_unix_signals_sp = signals_sp;
3362 }
3363 
3364 const lldb::UnixSignalsSP &Process::GetUnixSignals() {
3365   assert(m_unix_signals_sp && "null m_unix_signals_sp");
3366   return m_unix_signals_sp;
3367 }
3368 
3369 lldb::ByteOrder Process::GetByteOrder() const {
3370   return GetTarget().GetArchitecture().GetByteOrder();
3371 }
3372 
3373 uint32_t Process::GetAddressByteSize() const {
3374   return GetTarget().GetArchitecture().GetAddressByteSize();
3375 }
3376 
3377 bool Process::ShouldBroadcastEvent(Event *event_ptr) {
3378   const StateType state =
3379       Process::ProcessEventData::GetStateFromEvent(event_ptr);
3380   bool return_value = true;
3381   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_EVENTS |
3382                                                   LIBLLDB_LOG_PROCESS));
3383 
3384   switch (state) {
3385   case eStateDetached:
3386   case eStateExited:
3387   case eStateUnloaded:
3388     m_stdio_communication.SynchronizeWithReadThread();
3389     m_stdio_communication.Disconnect();
3390     m_stdio_communication.StopReadThread();
3391     m_stdin_forward = false;
3392 
3393     LLVM_FALLTHROUGH;
3394   case eStateConnected:
3395   case eStateAttaching:
3396   case eStateLaunching:
3397     // These events indicate changes in the state of the debugging session,
3398     // always report them.
3399     return_value = true;
3400     break;
3401   case eStateInvalid:
3402     // We stopped for no apparent reason, don't report it.
3403     return_value = false;
3404     break;
3405   case eStateRunning:
3406   case eStateStepping:
3407     // If we've started the target running, we handle the cases where we are
3408     // already running and where there is a transition from stopped to running
3409     // differently. running -> running: Automatically suppress extra running
3410     // events stopped -> running: Report except when there is one or more no
3411     // votes
3412     //     and no yes votes.
3413     SynchronouslyNotifyStateChanged(state);
3414     if (m_force_next_event_delivery)
3415       return_value = true;
3416     else {
3417       switch (m_last_broadcast_state) {
3418       case eStateRunning:
3419       case eStateStepping:
3420         // We always suppress multiple runnings with no PUBLIC stop in between.
3421         return_value = false;
3422         break;
3423       default:
3424         // TODO: make this work correctly. For now always report
3425         // run if we aren't running so we don't miss any running events. If I
3426         // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3427         // and hit the breakpoints on multiple threads, then somehow during the
3428         // stepping over of all breakpoints no run gets reported.
3429 
3430         // This is a transition from stop to run.
3431         switch (m_thread_list.ShouldReportRun(event_ptr)) {
3432         case eVoteYes:
3433         case eVoteNoOpinion:
3434           return_value = true;
3435           break;
3436         case eVoteNo:
3437           return_value = false;
3438           break;
3439         }
3440         break;
3441       }
3442     }
3443     break;
3444   case eStateStopped:
3445   case eStateCrashed:
3446   case eStateSuspended:
3447     // We've stopped.  First see if we're going to restart the target. If we
3448     // are going to stop, then we always broadcast the event. If we aren't
3449     // going to stop, let the thread plans decide if we're going to report this
3450     // event. If no thread has an opinion, we don't report it.
3451 
3452     m_stdio_communication.SynchronizeWithReadThread();
3453     RefreshStateAfterStop();
3454     if (ProcessEventData::GetInterruptedFromEvent(event_ptr)) {
3455       LLDB_LOGF(log,
3456                 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3457                 "interrupt, state: %s",
3458                 static_cast<void *>(event_ptr), StateAsCString(state));
3459       // Even though we know we are going to stop, we should let the threads
3460       // have a look at the stop, so they can properly set their state.
3461       m_thread_list.ShouldStop(event_ptr);
3462       return_value = true;
3463     } else {
3464       bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3465       bool should_resume = false;
3466 
3467       // It makes no sense to ask "ShouldStop" if we've already been
3468       // restarted... Asking the thread list is also not likely to go well,
3469       // since we are running again. So in that case just report the event.
3470 
3471       if (!was_restarted)
3472         should_resume = !m_thread_list.ShouldStop(event_ptr);
3473 
3474       if (was_restarted || should_resume || m_resume_requested) {
3475         Vote stop_vote = m_thread_list.ShouldReportStop(event_ptr);
3476         LLDB_LOGF(log,
3477                   "Process::ShouldBroadcastEvent: should_resume: %i state: "
3478                   "%s was_restarted: %i stop_vote: %d.",
3479                   should_resume, StateAsCString(state), was_restarted,
3480                   stop_vote);
3481 
3482         switch (stop_vote) {
3483         case eVoteYes:
3484           return_value = true;
3485           break;
3486         case eVoteNoOpinion:
3487         case eVoteNo:
3488           return_value = false;
3489           break;
3490         }
3491 
3492         if (!was_restarted) {
3493           LLDB_LOGF(log,
3494                     "Process::ShouldBroadcastEvent (%p) Restarting process "
3495                     "from state: %s",
3496                     static_cast<void *>(event_ptr), StateAsCString(state));
3497           ProcessEventData::SetRestartedInEvent(event_ptr, true);
3498           PrivateResume();
3499         }
3500       } else {
3501         return_value = true;
3502         SynchronouslyNotifyStateChanged(state);
3503       }
3504     }
3505     break;
3506   }
3507 
3508   // Forcing the next event delivery is a one shot deal.  So reset it here.
3509   m_force_next_event_delivery = false;
3510 
3511   // We do some coalescing of events (for instance two consecutive running
3512   // events get coalesced.) But we only coalesce against events we actually
3513   // broadcast.  So we use m_last_broadcast_state to track that.  NB - you
3514   // can't use "m_public_state.GetValue()" for that purpose, as was originally
3515   // done, because the PublicState reflects the last event pulled off the
3516   // queue, and there may be several events stacked up on the queue unserviced.
3517   // So the PublicState may not reflect the last broadcasted event yet.
3518   // m_last_broadcast_state gets updated here.
3519 
3520   if (return_value)
3521     m_last_broadcast_state = state;
3522 
3523   LLDB_LOGF(log,
3524             "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3525             "broadcast state: %s - %s",
3526             static_cast<void *>(event_ptr), StateAsCString(state),
3527             StateAsCString(m_last_broadcast_state),
3528             return_value ? "YES" : "NO");
3529   return return_value;
3530 }
3531 
3532 bool Process::StartPrivateStateThread(bool is_secondary_thread) {
3533   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EVENTS));
3534 
3535   bool already_running = PrivateStateThreadIsValid();
3536   LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
3537             already_running ? " already running"
3538                             : " starting private state thread");
3539 
3540   if (!is_secondary_thread && already_running)
3541     return true;
3542 
3543   // Create a thread that watches our internal state and controls which events
3544   // make it to clients (into the DCProcess event queue).
3545   char thread_name[1024];
3546   uint32_t max_len = llvm::get_max_thread_name_length();
3547   if (max_len > 0 && max_len <= 30) {
3548     // On platforms with abbreviated thread name lengths, choose thread names
3549     // that fit within the limit.
3550     if (already_running)
3551       snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
3552     else
3553       snprintf(thread_name, sizeof(thread_name), "intern-state");
3554   } else {
3555     if (already_running)
3556       snprintf(thread_name, sizeof(thread_name),
3557                "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
3558                GetID());
3559     else
3560       snprintf(thread_name, sizeof(thread_name),
3561                "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
3562   }
3563 
3564   // Create the private state thread, and start it running.
3565   PrivateStateThreadArgs *args_ptr =
3566       new PrivateStateThreadArgs(this, is_secondary_thread);
3567   llvm::Expected<HostThread> private_state_thread =
3568       ThreadLauncher::LaunchThread(thread_name, Process::PrivateStateThread,
3569                                    (void *)args_ptr, 8 * 1024 * 1024);
3570   if (!private_state_thread) {
3571     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
3572              "failed to launch host thread: {}",
3573              llvm::toString(private_state_thread.takeError()));
3574     return false;
3575   }
3576 
3577   assert(private_state_thread->IsJoinable());
3578   m_private_state_thread = *private_state_thread;
3579   ResumePrivateStateThread();
3580   return true;
3581 }
3582 
3583 void Process::PausePrivateStateThread() {
3584   ControlPrivateStateThread(eBroadcastInternalStateControlPause);
3585 }
3586 
3587 void Process::ResumePrivateStateThread() {
3588   ControlPrivateStateThread(eBroadcastInternalStateControlResume);
3589 }
3590 
3591 void Process::StopPrivateStateThread() {
3592   if (m_private_state_thread.IsJoinable())
3593     ControlPrivateStateThread(eBroadcastInternalStateControlStop);
3594   else {
3595     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3596     LLDB_LOGF(
3597         log,
3598         "Went to stop the private state thread, but it was already invalid.");
3599   }
3600 }
3601 
3602 void Process::ControlPrivateStateThread(uint32_t signal) {
3603   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3604 
3605   assert(signal == eBroadcastInternalStateControlStop ||
3606          signal == eBroadcastInternalStateControlPause ||
3607          signal == eBroadcastInternalStateControlResume);
3608 
3609   LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
3610 
3611   // Signal the private state thread
3612   if (m_private_state_thread.IsJoinable()) {
3613     // Broadcast the event.
3614     // It is important to do this outside of the if below, because it's
3615     // possible that the thread state is invalid but that the thread is waiting
3616     // on a control event instead of simply being on its way out (this should
3617     // not happen, but it apparently can).
3618     LLDB_LOGF(log, "Sending control event of type: %d.", signal);
3619     std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
3620     m_private_state_control_broadcaster.BroadcastEvent(signal,
3621                                                        event_receipt_sp);
3622 
3623     // Wait for the event receipt or for the private state thread to exit
3624     bool receipt_received = false;
3625     if (PrivateStateThreadIsValid()) {
3626       while (!receipt_received) {
3627         // Check for a receipt for n seconds and then check if the private
3628         // state thread is still around.
3629         receipt_received =
3630           event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
3631         if (!receipt_received) {
3632           // Check if the private state thread is still around. If it isn't
3633           // then we are done waiting
3634           if (!PrivateStateThreadIsValid())
3635             break; // Private state thread exited or is exiting, we are done
3636         }
3637       }
3638     }
3639 
3640     if (signal == eBroadcastInternalStateControlStop) {
3641       thread_result_t result = {};
3642       m_private_state_thread.Join(&result);
3643       m_private_state_thread.Reset();
3644     }
3645   } else {
3646     LLDB_LOGF(
3647         log,
3648         "Private state thread already dead, no need to signal it to stop.");
3649   }
3650 }
3651 
3652 void Process::SendAsyncInterrupt() {
3653   if (PrivateStateThreadIsValid())
3654     m_private_state_broadcaster.BroadcastEvent(Process::eBroadcastBitInterrupt,
3655                                                nullptr);
3656   else
3657     BroadcastEvent(Process::eBroadcastBitInterrupt, nullptr);
3658 }
3659 
3660 void Process::HandlePrivateEvent(EventSP &event_sp) {
3661   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3662   m_resume_requested = false;
3663 
3664   const StateType new_state =
3665       Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3666 
3667   // First check to see if anybody wants a shot at this event:
3668   if (m_next_event_action_up) {
3669     NextEventAction::EventActionResult action_result =
3670         m_next_event_action_up->PerformAction(event_sp);
3671     LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
3672 
3673     switch (action_result) {
3674     case NextEventAction::eEventActionSuccess:
3675       SetNextEventAction(nullptr);
3676       break;
3677 
3678     case NextEventAction::eEventActionRetry:
3679       break;
3680 
3681     case NextEventAction::eEventActionExit:
3682       // Handle Exiting Here.  If we already got an exited event, we should
3683       // just propagate it.  Otherwise, swallow this event, and set our state
3684       // to exit so the next event will kill us.
3685       if (new_state != eStateExited) {
3686         // FIXME: should cons up an exited event, and discard this one.
3687         SetExitStatus(0, m_next_event_action_up->GetExitString());
3688         SetNextEventAction(nullptr);
3689         return;
3690       }
3691       SetNextEventAction(nullptr);
3692       break;
3693     }
3694   }
3695 
3696   // See if we should broadcast this state to external clients?
3697   const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
3698 
3699   if (should_broadcast) {
3700     const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
3701     if (log) {
3702       LLDB_LOGF(log,
3703                 "Process::%s (pid = %" PRIu64
3704                 ") broadcasting new state %s (old state %s) to %s",
3705                 __FUNCTION__, GetID(), StateAsCString(new_state),
3706                 StateAsCString(GetState()),
3707                 is_hijacked ? "hijacked" : "public");
3708     }
3709     Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp.get());
3710     if (StateIsRunningState(new_state)) {
3711       // Only push the input handler if we aren't fowarding events, as this
3712       // means the curses GUI is in use... Or don't push it if we are launching
3713       // since it will come up stopped.
3714       if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3715           new_state != eStateLaunching && new_state != eStateAttaching) {
3716         PushProcessIOHandler();
3717         m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
3718                                   eBroadcastAlways);
3719         LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
3720                   __FUNCTION__, m_iohandler_sync.GetValue());
3721       }
3722     } else if (StateIsStoppedState(new_state, false)) {
3723       if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp.get())) {
3724         // If the lldb_private::Debugger is handling the events, we don't want
3725         // to pop the process IOHandler here, we want to do it when we receive
3726         // the stopped event so we can carefully control when the process
3727         // IOHandler is popped because when we stop we want to display some
3728         // text stating how and why we stopped, then maybe some
3729         // process/thread/frame info, and then we want the "(lldb) " prompt to
3730         // show up. If we pop the process IOHandler here, then we will cause
3731         // the command interpreter to become the top IOHandler after the
3732         // process pops off and it will update its prompt right away... See the
3733         // Debugger.cpp file where it calls the function as
3734         // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3735         // Otherwise we end up getting overlapping "(lldb) " prompts and
3736         // garbled output.
3737         //
3738         // If we aren't handling the events in the debugger (which is indicated
3739         // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3740         // we are hijacked, then we always pop the process IO handler manually.
3741         // Hijacking happens when the internal process state thread is running
3742         // thread plans, or when commands want to run in synchronous mode and
3743         // they call "process->WaitForProcessToStop()". An example of something
3744         // that will hijack the events is a simple expression:
3745         //
3746         //  (lldb) expr (int)puts("hello")
3747         //
3748         // This will cause the internal process state thread to resume and halt
3749         // the process (and _it_ will hijack the eBroadcastBitStateChanged
3750         // events) and we do need the IO handler to be pushed and popped
3751         // correctly.
3752 
3753         if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
3754           PopProcessIOHandler();
3755       }
3756     }
3757 
3758     BroadcastEvent(event_sp);
3759   } else {
3760     if (log) {
3761       LLDB_LOGF(
3762           log,
3763           "Process::%s (pid = %" PRIu64
3764           ") suppressing state %s (old state %s): should_broadcast == false",
3765           __FUNCTION__, GetID(), StateAsCString(new_state),
3766           StateAsCString(GetState()));
3767     }
3768   }
3769 }
3770 
3771 Status Process::HaltPrivate() {
3772   EventSP event_sp;
3773   Status error(WillHalt());
3774   if (error.Fail())
3775     return error;
3776 
3777   // Ask the process subclass to actually halt our process
3778   bool caused_stop;
3779   error = DoHalt(caused_stop);
3780 
3781   DidHalt();
3782   return error;
3783 }
3784 
3785 thread_result_t Process::PrivateStateThread(void *arg) {
3786   std::unique_ptr<PrivateStateThreadArgs> args_up(
3787       static_cast<PrivateStateThreadArgs *>(arg));
3788   thread_result_t result =
3789       args_up->process->RunPrivateStateThread(args_up->is_secondary_thread);
3790   return result;
3791 }
3792 
3793 thread_result_t Process::RunPrivateStateThread(bool is_secondary_thread) {
3794   bool control_only = true;
3795 
3796   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3797   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
3798             __FUNCTION__, static_cast<void *>(this), GetID());
3799 
3800   bool exit_now = false;
3801   bool interrupt_requested = false;
3802   while (!exit_now) {
3803     EventSP event_sp;
3804     GetEventsPrivate(event_sp, llvm::None, control_only);
3805     if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
3806       LLDB_LOGF(log,
3807                 "Process::%s (arg = %p, pid = %" PRIu64
3808                 ") got a control event: %d",
3809                 __FUNCTION__, static_cast<void *>(this), GetID(),
3810                 event_sp->GetType());
3811 
3812       switch (event_sp->GetType()) {
3813       case eBroadcastInternalStateControlStop:
3814         exit_now = true;
3815         break; // doing any internal state management below
3816 
3817       case eBroadcastInternalStateControlPause:
3818         control_only = true;
3819         break;
3820 
3821       case eBroadcastInternalStateControlResume:
3822         control_only = false;
3823         break;
3824       }
3825 
3826       continue;
3827     } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
3828       if (m_public_state.GetValue() == eStateAttaching) {
3829         LLDB_LOGF(log,
3830                   "Process::%s (arg = %p, pid = %" PRIu64
3831                   ") woke up with an interrupt while attaching - "
3832                   "forwarding interrupt.",
3833                   __FUNCTION__, static_cast<void *>(this), GetID());
3834         BroadcastEvent(eBroadcastBitInterrupt, nullptr);
3835       } else if (StateIsRunningState(m_last_broadcast_state)) {
3836         LLDB_LOGF(log,
3837                   "Process::%s (arg = %p, pid = %" PRIu64
3838                   ") woke up with an interrupt - Halting.",
3839                   __FUNCTION__, static_cast<void *>(this), GetID());
3840         Status error = HaltPrivate();
3841         if (error.Fail() && log)
3842           LLDB_LOGF(log,
3843                     "Process::%s (arg = %p, pid = %" PRIu64
3844                     ") failed to halt the process: %s",
3845                     __FUNCTION__, static_cast<void *>(this), GetID(),
3846                     error.AsCString());
3847         // Halt should generate a stopped event. Make a note of the fact that
3848         // we were doing the interrupt, so we can set the interrupted flag
3849         // after we receive the event. We deliberately set this to true even if
3850         // HaltPrivate failed, so that we can interrupt on the next natural
3851         // stop.
3852         interrupt_requested = true;
3853       } else {
3854         // This can happen when someone (e.g. Process::Halt) sees that we are
3855         // running and sends an interrupt request, but the process actually
3856         // stops before we receive it. In that case, we can just ignore the
3857         // request. We use m_last_broadcast_state, because the Stopped event
3858         // may not have been popped of the event queue yet, which is when the
3859         // public state gets updated.
3860         LLDB_LOGF(log,
3861                   "Process::%s ignoring interrupt as we have already stopped.",
3862                   __FUNCTION__);
3863       }
3864       continue;
3865     }
3866 
3867     const StateType internal_state =
3868         Process::ProcessEventData::GetStateFromEvent(event_sp.get());
3869 
3870     if (internal_state != eStateInvalid) {
3871       if (m_clear_thread_plans_on_stop &&
3872           StateIsStoppedState(internal_state, true)) {
3873         m_clear_thread_plans_on_stop = false;
3874         m_thread_list.DiscardThreadPlans();
3875       }
3876 
3877       if (interrupt_requested) {
3878         if (StateIsStoppedState(internal_state, true)) {
3879           // We requested the interrupt, so mark this as such in the stop event
3880           // so clients can tell an interrupted process from a natural stop
3881           ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
3882           interrupt_requested = false;
3883         } else if (log) {
3884           LLDB_LOGF(log,
3885                     "Process::%s interrupt_requested, but a non-stopped "
3886                     "state '%s' received.",
3887                     __FUNCTION__, StateAsCString(internal_state));
3888         }
3889       }
3890 
3891       HandlePrivateEvent(event_sp);
3892     }
3893 
3894     if (internal_state == eStateInvalid || internal_state == eStateExited ||
3895         internal_state == eStateDetached) {
3896       LLDB_LOGF(log,
3897                 "Process::%s (arg = %p, pid = %" PRIu64
3898                 ") about to exit with internal state %s...",
3899                 __FUNCTION__, static_cast<void *>(this), GetID(),
3900                 StateAsCString(internal_state));
3901 
3902       break;
3903     }
3904   }
3905 
3906   // Verify log is still enabled before attempting to write to it...
3907   LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
3908             __FUNCTION__, static_cast<void *>(this), GetID());
3909 
3910   // If we are a secondary thread, then the primary thread we are working for
3911   // will have already acquired the public_run_lock, and isn't done with what
3912   // it was doing yet, so don't try to change it on the way out.
3913   if (!is_secondary_thread)
3914     m_public_run_lock.SetStopped();
3915   return {};
3916 }
3917 
3918 // Process Event Data
3919 
3920 Process::ProcessEventData::ProcessEventData()
3921     : EventData(), m_process_wp(), m_state(eStateInvalid), m_restarted(false),
3922       m_update_state(0), m_interrupted(false) {}
3923 
3924 Process::ProcessEventData::ProcessEventData(const ProcessSP &process_sp,
3925                                             StateType state)
3926     : EventData(), m_process_wp(), m_state(state), m_restarted(false),
3927       m_update_state(0), m_interrupted(false) {
3928   if (process_sp)
3929     m_process_wp = process_sp;
3930 }
3931 
3932 Process::ProcessEventData::~ProcessEventData() = default;
3933 
3934 ConstString Process::ProcessEventData::GetFlavorString() {
3935   static ConstString g_flavor("Process::ProcessEventData");
3936   return g_flavor;
3937 }
3938 
3939 ConstString Process::ProcessEventData::GetFlavor() const {
3940   return ProcessEventData::GetFlavorString();
3941 }
3942 
3943 void Process::ProcessEventData::DoOnRemoval(Event *event_ptr) {
3944   ProcessSP process_sp(m_process_wp.lock());
3945 
3946   if (!process_sp)
3947     return;
3948 
3949   // This function gets called twice for each event, once when the event gets
3950   // pulled off of the private process event queue, and then any number of
3951   // times, first when it gets pulled off of the public event queue, then other
3952   // times when we're pretending that this is where we stopped at the end of
3953   // expression evaluation.  m_update_state is used to distinguish these three
3954   // cases; it is 0 when we're just pulling it off for private handling, and >
3955   // 1 for expression evaluation, and we don't want to do the breakpoint
3956   // command handling then.
3957   if (m_update_state != 1)
3958     return;
3959 
3960   process_sp->SetPublicState(
3961       m_state, Process::ProcessEventData::GetRestartedFromEvent(event_ptr));
3962 
3963   if (m_state == eStateStopped && !m_restarted) {
3964     // Let process subclasses know we are about to do a public stop and do
3965     // anything they might need to in order to speed up register and memory
3966     // accesses.
3967     process_sp->WillPublicStop();
3968   }
3969 
3970   // If this is a halt event, even if the halt stopped with some reason other
3971   // than a plain interrupt (e.g. we had already stopped for a breakpoint when
3972   // the halt request came through) don't do the StopInfo actions, as they may
3973   // end up restarting the process.
3974   if (m_interrupted)
3975     return;
3976 
3977   // If we're stopped and haven't restarted, then do the StopInfo actions here:
3978   if (m_state == eStateStopped && !m_restarted) {
3979     ThreadList &curr_thread_list = process_sp->GetThreadList();
3980     uint32_t num_threads = curr_thread_list.GetSize();
3981     uint32_t idx;
3982 
3983     // The actions might change one of the thread's stop_info's opinions about
3984     // whether we should stop the process, so we need to query that as we go.
3985 
3986     // One other complication here, is that we try to catch any case where the
3987     // target has run (except for expressions) and immediately exit, but if we
3988     // get that wrong (which is possible) then the thread list might have
3989     // changed, and that would cause our iteration here to crash.  We could
3990     // make a copy of the thread list, but we'd really like to also know if it
3991     // has changed at all, so we make up a vector of the thread ID's and check
3992     // what we get back against this list & bag out if anything differs.
3993     std::vector<uint32_t> thread_index_array(num_threads);
3994     for (idx = 0; idx < num_threads; ++idx)
3995       thread_index_array[idx] =
3996           curr_thread_list.GetThreadAtIndex(idx)->GetIndexID();
3997 
3998     // Use this to track whether we should continue from here.  We will only
3999     // continue the target running if no thread says we should stop.  Of course
4000     // if some thread's PerformAction actually sets the target running, then it
4001     // doesn't matter what the other threads say...
4002 
4003     bool still_should_stop = false;
4004 
4005     // Sometimes - for instance if we have a bug in the stub we are talking to,
4006     // we stop but no thread has a valid stop reason.  In that case we should
4007     // just stop, because we have no way of telling what the right thing to do
4008     // is, and it's better to let the user decide than continue behind their
4009     // backs.
4010 
4011     bool does_anybody_have_an_opinion = false;
4012 
4013     for (idx = 0; idx < num_threads; ++idx) {
4014       curr_thread_list = process_sp->GetThreadList();
4015       if (curr_thread_list.GetSize() != num_threads) {
4016         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4017                                                         LIBLLDB_LOG_PROCESS));
4018         LLDB_LOGF(
4019             log,
4020             "Number of threads changed from %u to %u while processing event.",
4021             num_threads, curr_thread_list.GetSize());
4022         break;
4023       }
4024 
4025       lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4026 
4027       if (thread_sp->GetIndexID() != thread_index_array[idx]) {
4028         Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4029                                                         LIBLLDB_LOG_PROCESS));
4030         LLDB_LOGF(log,
4031                   "The thread at position %u changed from %u to %u while "
4032                   "processing event.",
4033                   idx, thread_index_array[idx], thread_sp->GetIndexID());
4034         break;
4035       }
4036 
4037       StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4038       if (stop_info_sp && stop_info_sp->IsValid()) {
4039         does_anybody_have_an_opinion = true;
4040         bool this_thread_wants_to_stop;
4041         if (stop_info_sp->GetOverrideShouldStop()) {
4042           this_thread_wants_to_stop =
4043               stop_info_sp->GetOverriddenShouldStopValue();
4044         } else {
4045           stop_info_sp->PerformAction(event_ptr);
4046           // The stop action might restart the target.  If it does, then we
4047           // want to mark that in the event so that whoever is receiving it
4048           // will know to wait for the running event and reflect that state
4049           // appropriately. We also need to stop processing actions, since they
4050           // aren't expecting the target to be running.
4051 
4052           // FIXME: we might have run.
4053           if (stop_info_sp->HasTargetRunSinceMe()) {
4054             SetRestarted(true);
4055             break;
4056           }
4057 
4058           this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4059         }
4060 
4061         if (!still_should_stop)
4062           still_should_stop = this_thread_wants_to_stop;
4063       }
4064     }
4065 
4066     if (!GetRestarted()) {
4067       if (!still_should_stop && does_anybody_have_an_opinion) {
4068         // We've been asked to continue, so do that here.
4069         SetRestarted(true);
4070         // Use the public resume method here, since this is just extending a
4071         // public resume.
4072         process_sp->PrivateResume();
4073       } else {
4074         bool hijacked =
4075             process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4076             !process_sp->StateChangedIsHijackedForSynchronousResume();
4077 
4078         if (!hijacked) {
4079           // If we didn't restart, run the Stop Hooks here.
4080           // Don't do that if state changed events aren't hooked up to the
4081           // public (or SyncResume) broadcasters.  StopHooks are just for
4082           // real public stops.  They might also restart the target,
4083           // so watch for that.
4084           process_sp->GetTarget().RunStopHooks();
4085           if (process_sp->GetPrivateState() == eStateRunning)
4086             SetRestarted(true);
4087       }
4088     }
4089   }
4090 }
4091 }
4092 
4093 void Process::ProcessEventData::Dump(Stream *s) const {
4094   ProcessSP process_sp(m_process_wp.lock());
4095 
4096   if (process_sp)
4097     s->Printf(" process = %p (pid = %" PRIu64 "), ",
4098               static_cast<void *>(process_sp.get()), process_sp->GetID());
4099   else
4100     s->PutCString(" process = NULL, ");
4101 
4102   s->Printf("state = %s", StateAsCString(GetState()));
4103 }
4104 
4105 const Process::ProcessEventData *
4106 Process::ProcessEventData::GetEventDataFromEvent(const Event *event_ptr) {
4107   if (event_ptr) {
4108     const EventData *event_data = event_ptr->GetData();
4109     if (event_data &&
4110         event_data->GetFlavor() == ProcessEventData::GetFlavorString())
4111       return static_cast<const ProcessEventData *>(event_ptr->GetData());
4112   }
4113   return nullptr;
4114 }
4115 
4116 ProcessSP
4117 Process::ProcessEventData::GetProcessFromEvent(const Event *event_ptr) {
4118   ProcessSP process_sp;
4119   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4120   if (data)
4121     process_sp = data->GetProcessSP();
4122   return process_sp;
4123 }
4124 
4125 StateType Process::ProcessEventData::GetStateFromEvent(const Event *event_ptr) {
4126   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4127   if (data == nullptr)
4128     return eStateInvalid;
4129   else
4130     return data->GetState();
4131 }
4132 
4133 bool Process::ProcessEventData::GetRestartedFromEvent(const Event *event_ptr) {
4134   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4135   if (data == nullptr)
4136     return false;
4137   else
4138     return data->GetRestarted();
4139 }
4140 
4141 void Process::ProcessEventData::SetRestartedInEvent(Event *event_ptr,
4142                                                     bool new_value) {
4143   ProcessEventData *data =
4144       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4145   if (data != nullptr)
4146     data->SetRestarted(new_value);
4147 }
4148 
4149 size_t
4150 Process::ProcessEventData::GetNumRestartedReasons(const Event *event_ptr) {
4151   ProcessEventData *data =
4152       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4153   if (data != nullptr)
4154     return data->GetNumRestartedReasons();
4155   else
4156     return 0;
4157 }
4158 
4159 const char *
4160 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event *event_ptr,
4161                                                      size_t idx) {
4162   ProcessEventData *data =
4163       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4164   if (data != nullptr)
4165     return data->GetRestartedReasonAtIndex(idx);
4166   else
4167     return nullptr;
4168 }
4169 
4170 void Process::ProcessEventData::AddRestartedReason(Event *event_ptr,
4171                                                    const char *reason) {
4172   ProcessEventData *data =
4173       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4174   if (data != nullptr)
4175     data->AddRestartedReason(reason);
4176 }
4177 
4178 bool Process::ProcessEventData::GetInterruptedFromEvent(
4179     const Event *event_ptr) {
4180   const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4181   if (data == nullptr)
4182     return false;
4183   else
4184     return data->GetInterrupted();
4185 }
4186 
4187 void Process::ProcessEventData::SetInterruptedInEvent(Event *event_ptr,
4188                                                       bool new_value) {
4189   ProcessEventData *data =
4190       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4191   if (data != nullptr)
4192     data->SetInterrupted(new_value);
4193 }
4194 
4195 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event *event_ptr) {
4196   ProcessEventData *data =
4197       const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4198   if (data) {
4199     data->SetUpdateStateOnRemoval();
4200     return true;
4201   }
4202   return false;
4203 }
4204 
4205 lldb::TargetSP Process::CalculateTarget() { return m_target_wp.lock(); }
4206 
4207 void Process::CalculateExecutionContext(ExecutionContext &exe_ctx) {
4208   exe_ctx.SetTargetPtr(&GetTarget());
4209   exe_ctx.SetProcessPtr(this);
4210   exe_ctx.SetThreadPtr(nullptr);
4211   exe_ctx.SetFramePtr(nullptr);
4212 }
4213 
4214 // uint32_t
4215 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4216 // std::vector<lldb::pid_t> &pids)
4217 //{
4218 //    return 0;
4219 //}
4220 //
4221 // ArchSpec
4222 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4223 //{
4224 //    return Host::GetArchSpecForExistingProcess (pid);
4225 //}
4226 //
4227 // ArchSpec
4228 // Process::GetArchSpecForExistingProcess (const char *process_name)
4229 //{
4230 //    return Host::GetArchSpecForExistingProcess (process_name);
4231 //}
4232 
4233 void Process::AppendSTDOUT(const char *s, size_t len) {
4234   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4235   m_stdout_data.append(s, len);
4236   BroadcastEventIfUnique(eBroadcastBitSTDOUT,
4237                          new ProcessEventData(shared_from_this(), GetState()));
4238 }
4239 
4240 void Process::AppendSTDERR(const char *s, size_t len) {
4241   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4242   m_stderr_data.append(s, len);
4243   BroadcastEventIfUnique(eBroadcastBitSTDERR,
4244                          new ProcessEventData(shared_from_this(), GetState()));
4245 }
4246 
4247 void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4248   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4249   m_profile_data.push_back(one_profile_data);
4250   BroadcastEventIfUnique(eBroadcastBitProfileData,
4251                          new ProcessEventData(shared_from_this(), GetState()));
4252 }
4253 
4254 void Process::BroadcastStructuredData(const StructuredData::ObjectSP &object_sp,
4255                                       const StructuredDataPluginSP &plugin_sp) {
4256   BroadcastEvent(
4257       eBroadcastBitStructuredData,
4258       new EventDataStructuredData(shared_from_this(), object_sp, plugin_sp));
4259 }
4260 
4261 StructuredDataPluginSP
4262 Process::GetStructuredDataPlugin(ConstString type_name) const {
4263   auto find_it = m_structured_data_plugin_map.find(type_name);
4264   if (find_it != m_structured_data_plugin_map.end())
4265     return find_it->second;
4266   else
4267     return StructuredDataPluginSP();
4268 }
4269 
4270 size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4271   std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4272   if (m_profile_data.empty())
4273     return 0;
4274 
4275   std::string &one_profile_data = m_profile_data.front();
4276   size_t bytes_available = one_profile_data.size();
4277   if (bytes_available > 0) {
4278     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4279     LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4280               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4281     if (bytes_available > buf_size) {
4282       memcpy(buf, one_profile_data.c_str(), buf_size);
4283       one_profile_data.erase(0, buf_size);
4284       bytes_available = buf_size;
4285     } else {
4286       memcpy(buf, one_profile_data.c_str(), bytes_available);
4287       m_profile_data.erase(m_profile_data.begin());
4288     }
4289   }
4290   return bytes_available;
4291 }
4292 
4293 // Process STDIO
4294 
4295 size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4296   std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4297   size_t bytes_available = m_stdout_data.size();
4298   if (bytes_available > 0) {
4299     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4300     LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4301               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4302     if (bytes_available > buf_size) {
4303       memcpy(buf, m_stdout_data.c_str(), buf_size);
4304       m_stdout_data.erase(0, buf_size);
4305       bytes_available = buf_size;
4306     } else {
4307       memcpy(buf, m_stdout_data.c_str(), bytes_available);
4308       m_stdout_data.clear();
4309     }
4310   }
4311   return bytes_available;
4312 }
4313 
4314 size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4315   std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4316   size_t bytes_available = m_stderr_data.size();
4317   if (bytes_available > 0) {
4318     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4319     LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4320               static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4321     if (bytes_available > buf_size) {
4322       memcpy(buf, m_stderr_data.c_str(), buf_size);
4323       m_stderr_data.erase(0, buf_size);
4324       bytes_available = buf_size;
4325     } else {
4326       memcpy(buf, m_stderr_data.c_str(), bytes_available);
4327       m_stderr_data.clear();
4328     }
4329   }
4330   return bytes_available;
4331 }
4332 
4333 void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4334                                            size_t src_len) {
4335   Process *process = (Process *)baton;
4336   process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4337 }
4338 
4339 class IOHandlerProcessSTDIO : public IOHandler {
4340 public:
4341   IOHandlerProcessSTDIO(Process *process, int write_fd)
4342       : IOHandler(process->GetTarget().GetDebugger(),
4343                   IOHandler::Type::ProcessIO),
4344         m_process(process),
4345         m_read_file(GetInputFD(), File::eOpenOptionRead, false),
4346         m_write_file(write_fd, File::eOpenOptionWrite, false) {
4347     m_pipe.CreateNew(false);
4348   }
4349 
4350   ~IOHandlerProcessSTDIO() override = default;
4351 
4352   // Each IOHandler gets to run until it is done. It should read data from the
4353   // "in" and place output into "out" and "err and return when done.
4354   void Run() override {
4355     if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4356         !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4357       SetIsDone(true);
4358       return;
4359     }
4360 
4361     SetIsDone(false);
4362     const int read_fd = m_read_file.GetDescriptor();
4363     TerminalState terminal_state;
4364     terminal_state.Save(read_fd, false);
4365     Terminal terminal(read_fd);
4366     terminal.SetCanonical(false);
4367     terminal.SetEcho(false);
4368 // FD_ZERO, FD_SET are not supported on windows
4369 #ifndef _WIN32
4370     const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4371     m_is_running = true;
4372     while (!GetIsDone()) {
4373       SelectHelper select_helper;
4374       select_helper.FDSetRead(read_fd);
4375       select_helper.FDSetRead(pipe_read_fd);
4376       Status error = select_helper.Select();
4377 
4378       if (error.Fail()) {
4379         SetIsDone(true);
4380       } else {
4381         char ch = 0;
4382         size_t n;
4383         if (select_helper.FDIsSetRead(read_fd)) {
4384           n = 1;
4385           if (m_read_file.Read(&ch, n).Success() && n == 1) {
4386             if (m_write_file.Write(&ch, n).Fail() || n != 1)
4387               SetIsDone(true);
4388           } else
4389             SetIsDone(true);
4390         }
4391         if (select_helper.FDIsSetRead(pipe_read_fd)) {
4392           size_t bytes_read;
4393           // Consume the interrupt byte
4394           Status error = m_pipe.Read(&ch, 1, bytes_read);
4395           if (error.Success()) {
4396             switch (ch) {
4397             case 'q':
4398               SetIsDone(true);
4399               break;
4400             case 'i':
4401               if (StateIsRunningState(m_process->GetState()))
4402                 m_process->SendAsyncInterrupt();
4403               break;
4404             }
4405           }
4406         }
4407       }
4408     }
4409     m_is_running = false;
4410 #endif
4411     terminal_state.Restore();
4412   }
4413 
4414   void Cancel() override {
4415     SetIsDone(true);
4416     // Only write to our pipe to cancel if we are in
4417     // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4418     // is being run from the command interpreter:
4419     //
4420     // (lldb) step_process_thousands_of_times
4421     //
4422     // In this case the command interpreter will be in the middle of handling
4423     // the command and if the process pushes and pops the IOHandler thousands
4424     // of times, we can end up writing to m_pipe without ever consuming the
4425     // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4426     // deadlocking when the pipe gets fed up and blocks until data is consumed.
4427     if (m_is_running) {
4428       char ch = 'q'; // Send 'q' for quit
4429       size_t bytes_written = 0;
4430       m_pipe.Write(&ch, 1, bytes_written);
4431     }
4432   }
4433 
4434   bool Interrupt() override {
4435     // Do only things that are safe to do in an interrupt context (like in a
4436     // SIGINT handler), like write 1 byte to a file descriptor. This will
4437     // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4438     // that was written to the pipe and then call
4439     // m_process->SendAsyncInterrupt() from a much safer location in code.
4440     if (m_active) {
4441       char ch = 'i'; // Send 'i' for interrupt
4442       size_t bytes_written = 0;
4443       Status result = m_pipe.Write(&ch, 1, bytes_written);
4444       return result.Success();
4445     } else {
4446       // This IOHandler might be pushed on the stack, but not being run
4447       // currently so do the right thing if we aren't actively watching for
4448       // STDIN by sending the interrupt to the process. Otherwise the write to
4449       // the pipe above would do nothing. This can happen when the command
4450       // interpreter is running and gets a "expression ...". It will be on the
4451       // IOHandler thread and sending the input is complete to the delegate
4452       // which will cause the expression to run, which will push the process IO
4453       // handler, but not run it.
4454 
4455       if (StateIsRunningState(m_process->GetState())) {
4456         m_process->SendAsyncInterrupt();
4457         return true;
4458       }
4459     }
4460     return false;
4461   }
4462 
4463   void GotEOF() override {}
4464 
4465 protected:
4466   Process *m_process;
4467   NativeFile m_read_file;  // Read from this file (usually actual STDIN for LLDB
4468   NativeFile m_write_file; // Write to this file (usually the master pty for
4469                            // getting io to debuggee)
4470   Pipe m_pipe;
4471   std::atomic<bool> m_is_running{false};
4472 };
4473 
4474 void Process::SetSTDIOFileDescriptor(int fd) {
4475   // First set up the Read Thread for reading/handling process I/O
4476   m_stdio_communication.SetConnection(
4477       std::make_unique<ConnectionFileDescriptor>(fd, true));
4478   if (m_stdio_communication.IsConnected()) {
4479     m_stdio_communication.SetReadThreadBytesReceivedCallback(
4480         STDIOReadThreadBytesReceived, this);
4481     m_stdio_communication.StartReadThread();
4482 
4483     // Now read thread is set up, set up input reader.
4484 
4485     if (!m_process_input_reader)
4486       m_process_input_reader =
4487           std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4488   }
4489 }
4490 
4491 bool Process::ProcessIOHandlerIsActive() {
4492   IOHandlerSP io_handler_sp(m_process_input_reader);
4493   if (io_handler_sp)
4494     return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
4495   return false;
4496 }
4497 bool Process::PushProcessIOHandler() {
4498   IOHandlerSP io_handler_sp(m_process_input_reader);
4499   if (io_handler_sp) {
4500     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
4501     LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
4502 
4503     io_handler_sp->SetIsDone(false);
4504     // If we evaluate an utility function, then we don't cancel the current
4505     // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4506     // existing IOHandler that potentially provides the user interface (e.g.
4507     // the IOHandler for Editline).
4508     bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
4509     GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
4510                                                 cancel_top_handler);
4511     return true;
4512   }
4513   return false;
4514 }
4515 
4516 bool Process::PopProcessIOHandler() {
4517   IOHandlerSP io_handler_sp(m_process_input_reader);
4518   if (io_handler_sp)
4519     return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
4520   return false;
4521 }
4522 
4523 // The process needs to know about installed plug-ins
4524 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4525 
4526 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4527 
4528 namespace {
4529 // RestorePlanState is used to record the "is private", "is master" and "okay
4530 // to discard" fields of the plan we are running, and reset it on Clean or on
4531 // destruction. It will only reset the state once, so you can call Clean and
4532 // then monkey with the state and it won't get reset on you again.
4533 
4534 class RestorePlanState {
4535 public:
4536   RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
4537       : m_thread_plan_sp(thread_plan_sp), m_already_reset(false) {
4538     if (m_thread_plan_sp) {
4539       m_private = m_thread_plan_sp->GetPrivate();
4540       m_is_master = m_thread_plan_sp->IsMasterPlan();
4541       m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
4542     }
4543   }
4544 
4545   ~RestorePlanState() { Clean(); }
4546 
4547   void Clean() {
4548     if (!m_already_reset && m_thread_plan_sp) {
4549       m_already_reset = true;
4550       m_thread_plan_sp->SetPrivate(m_private);
4551       m_thread_plan_sp->SetIsMasterPlan(m_is_master);
4552       m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
4553     }
4554   }
4555 
4556 private:
4557   lldb::ThreadPlanSP m_thread_plan_sp;
4558   bool m_already_reset;
4559   bool m_private;
4560   bool m_is_master;
4561   bool m_okay_to_discard;
4562 };
4563 } // anonymous namespace
4564 
4565 static microseconds
4566 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options) {
4567   const milliseconds default_one_thread_timeout(250);
4568 
4569   // If the overall wait is forever, then we don't need to worry about it.
4570   if (!options.GetTimeout()) {
4571     return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
4572                                          : default_one_thread_timeout;
4573   }
4574 
4575   // If the one thread timeout is set, use it.
4576   if (options.GetOneThreadTimeout())
4577     return *options.GetOneThreadTimeout();
4578 
4579   // Otherwise use half the total timeout, bounded by the
4580   // default_one_thread_timeout.
4581   return std::min<microseconds>(default_one_thread_timeout,
4582                                 *options.GetTimeout() / 2);
4583 }
4584 
4585 static Timeout<std::micro>
4586 GetExpressionTimeout(const EvaluateExpressionOptions &options,
4587                      bool before_first_timeout) {
4588   // If we are going to run all threads the whole time, or if we are only going
4589   // to run one thread, we can just return the overall timeout.
4590   if (!options.GetStopOthers() || !options.GetTryAllThreads())
4591     return options.GetTimeout();
4592 
4593   if (before_first_timeout)
4594     return GetOneThreadExpressionTimeout(options);
4595 
4596   if (!options.GetTimeout())
4597     return llvm::None;
4598   else
4599     return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
4600 }
4601 
4602 static llvm::Optional<ExpressionResults>
4603 HandleStoppedEvent(Thread &thread, const ThreadPlanSP &thread_plan_sp,
4604                    RestorePlanState &restorer, const EventSP &event_sp,
4605                    EventSP &event_to_broadcast_sp,
4606                    const EvaluateExpressionOptions &options, bool handle_interrupts) {
4607   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP | LIBLLDB_LOG_PROCESS);
4608 
4609   ThreadPlanSP plan = thread.GetCompletedPlan();
4610   if (plan == thread_plan_sp && plan->PlanSucceeded()) {
4611     LLDB_LOG(log, "execution completed successfully");
4612 
4613     // Restore the plan state so it will get reported as intended when we are
4614     // done.
4615     restorer.Clean();
4616     return eExpressionCompleted;
4617   }
4618 
4619   StopInfoSP stop_info_sp = thread.GetStopInfo();
4620   if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
4621       stop_info_sp->ShouldNotify(event_sp.get())) {
4622     LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
4623     if (!options.DoesIgnoreBreakpoints()) {
4624       // Restore the plan state and then force Private to false.  We are going
4625       // to stop because of this plan so we need it to become a public plan or
4626       // it won't report correctly when we continue to its termination later
4627       // on.
4628       restorer.Clean();
4629       thread_plan_sp->SetPrivate(false);
4630       event_to_broadcast_sp = event_sp;
4631     }
4632     return eExpressionHitBreakpoint;
4633   }
4634 
4635   if (!handle_interrupts &&
4636       Process::ProcessEventData::GetInterruptedFromEvent(event_sp.get()))
4637     return llvm::None;
4638 
4639   LLDB_LOG(log, "thread plan did not successfully complete");
4640   if (!options.DoesUnwindOnError())
4641     event_to_broadcast_sp = event_sp;
4642   return eExpressionInterrupted;
4643 }
4644 
4645 ExpressionResults
4646 Process::RunThreadPlan(ExecutionContext &exe_ctx,
4647                        lldb::ThreadPlanSP &thread_plan_sp,
4648                        const EvaluateExpressionOptions &options,
4649                        DiagnosticManager &diagnostic_manager) {
4650   ExpressionResults return_value = eExpressionSetupError;
4651 
4652   std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
4653 
4654   if (!thread_plan_sp) {
4655     diagnostic_manager.PutString(
4656         eDiagnosticSeverityError,
4657         "RunThreadPlan called with empty thread plan.");
4658     return eExpressionSetupError;
4659   }
4660 
4661   if (!thread_plan_sp->ValidatePlan(nullptr)) {
4662     diagnostic_manager.PutString(
4663         eDiagnosticSeverityError,
4664         "RunThreadPlan called with an invalid thread plan.");
4665     return eExpressionSetupError;
4666   }
4667 
4668   if (exe_ctx.GetProcessPtr() != this) {
4669     diagnostic_manager.PutString(eDiagnosticSeverityError,
4670                                  "RunThreadPlan called on wrong process.");
4671     return eExpressionSetupError;
4672   }
4673 
4674   Thread *thread = exe_ctx.GetThreadPtr();
4675   if (thread == nullptr) {
4676     diagnostic_manager.PutString(eDiagnosticSeverityError,
4677                                  "RunThreadPlan called with invalid thread.");
4678     return eExpressionSetupError;
4679   }
4680 
4681   // We need to change some of the thread plan attributes for the thread plan
4682   // runner.  This will restore them when we are done:
4683 
4684   RestorePlanState thread_plan_restorer(thread_plan_sp);
4685 
4686   // We rely on the thread plan we are running returning "PlanCompleted" if
4687   // when it successfully completes. For that to be true the plan can't be
4688   // private - since private plans suppress themselves in the GetCompletedPlan
4689   // call.
4690 
4691   thread_plan_sp->SetPrivate(false);
4692 
4693   // The plans run with RunThreadPlan also need to be terminal master plans or
4694   // when they are done we will end up asking the plan above us whether we
4695   // should stop, which may give the wrong answer.
4696 
4697   thread_plan_sp->SetIsMasterPlan(true);
4698   thread_plan_sp->SetOkayToDiscard(false);
4699 
4700   // If we are running some utility expression for LLDB, we now have to mark
4701   // this in the ProcesModID of this process. This RAII takes care of marking
4702   // and reverting the mark it once we are done running the expression.
4703   UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
4704 
4705   if (m_private_state.GetValue() != eStateStopped) {
4706     diagnostic_manager.PutString(
4707         eDiagnosticSeverityError,
4708         "RunThreadPlan called while the private state was not stopped.");
4709     return eExpressionSetupError;
4710   }
4711 
4712   // Save the thread & frame from the exe_ctx for restoration after we run
4713   const uint32_t thread_idx_id = thread->GetIndexID();
4714   StackFrameSP selected_frame_sp = thread->GetSelectedFrame();
4715   if (!selected_frame_sp) {
4716     thread->SetSelectedFrame(nullptr);
4717     selected_frame_sp = thread->GetSelectedFrame();
4718     if (!selected_frame_sp) {
4719       diagnostic_manager.Printf(
4720           eDiagnosticSeverityError,
4721           "RunThreadPlan called without a selected frame on thread %d",
4722           thread_idx_id);
4723       return eExpressionSetupError;
4724     }
4725   }
4726 
4727   // Make sure the timeout values make sense. The one thread timeout needs to
4728   // be smaller than the overall timeout.
4729   if (options.GetOneThreadTimeout() && options.GetTimeout() &&
4730       *options.GetTimeout() < *options.GetOneThreadTimeout()) {
4731     diagnostic_manager.PutString(eDiagnosticSeverityError,
4732                                  "RunThreadPlan called with one thread "
4733                                  "timeout greater than total timeout");
4734     return eExpressionSetupError;
4735   }
4736 
4737   StackID ctx_frame_id = selected_frame_sp->GetStackID();
4738 
4739   // N.B. Running the target may unset the currently selected thread and frame.
4740   // We don't want to do that either, so we should arrange to reset them as
4741   // well.
4742 
4743   lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
4744 
4745   uint32_t selected_tid;
4746   StackID selected_stack_id;
4747   if (selected_thread_sp) {
4748     selected_tid = selected_thread_sp->GetIndexID();
4749     selected_stack_id = selected_thread_sp->GetSelectedFrame()->GetStackID();
4750   } else {
4751     selected_tid = LLDB_INVALID_THREAD_ID;
4752   }
4753 
4754   HostThread backup_private_state_thread;
4755   lldb::StateType old_state = eStateInvalid;
4756   lldb::ThreadPlanSP stopper_base_plan_sp;
4757 
4758   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_STEP |
4759                                                   LIBLLDB_LOG_PROCESS));
4760   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread())) {
4761     // Yikes, we are running on the private state thread!  So we can't wait for
4762     // public events on this thread, since we are the thread that is generating
4763     // public events. The simplest thing to do is to spin up a temporary thread
4764     // to handle private state thread events while we are fielding public
4765     // events here.
4766     LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
4767                    "another state thread to handle the events.");
4768 
4769     backup_private_state_thread = m_private_state_thread;
4770 
4771     // One other bit of business: we want to run just this thread plan and
4772     // anything it pushes, and then stop, returning control here. But in the
4773     // normal course of things, the plan above us on the stack would be given a
4774     // shot at the stop event before deciding to stop, and we don't want that.
4775     // So we insert a "stopper" base plan on the stack before the plan we want
4776     // to run.  Since base plans always stop and return control to the user,
4777     // that will do just what we want.
4778     stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
4779     thread->QueueThreadPlan(stopper_base_plan_sp, false);
4780     // Have to make sure our public state is stopped, since otherwise the
4781     // reporting logic below doesn't work correctly.
4782     old_state = m_public_state.GetValue();
4783     m_public_state.SetValueNoLock(eStateStopped);
4784 
4785     // Now spin up the private state thread:
4786     StartPrivateStateThread(true);
4787   }
4788 
4789   thread->QueueThreadPlan(
4790       thread_plan_sp, false); // This used to pass "true" does that make sense?
4791 
4792   if (options.GetDebug()) {
4793     // In this case, we aren't actually going to run, we just want to stop
4794     // right away. Flush this thread so we will refetch the stacks and show the
4795     // correct backtrace.
4796     // FIXME: To make this prettier we should invent some stop reason for this,
4797     // but that
4798     // is only cosmetic, and this functionality is only of use to lldb
4799     // developers who can live with not pretty...
4800     thread->Flush();
4801     return eExpressionStoppedForDebug;
4802   }
4803 
4804   ListenerSP listener_sp(
4805       Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4806 
4807   lldb::EventSP event_to_broadcast_sp;
4808 
4809   {
4810     // This process event hijacker Hijacks the Public events and its destructor
4811     // makes sure that the process events get restored on exit to the function.
4812     //
4813     // If the event needs to propagate beyond the hijacker (e.g., the process
4814     // exits during execution), then the event is put into
4815     // event_to_broadcast_sp for rebroadcasting.
4816 
4817     ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
4818 
4819     if (log) {
4820       StreamString s;
4821       thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
4822       LLDB_LOGF(log,
4823                 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4824                 " to run thread plan \"%s\".",
4825                 thread->GetIndexID(), thread->GetID(), s.GetData());
4826     }
4827 
4828     bool got_event;
4829     lldb::EventSP event_sp;
4830     lldb::StateType stop_state = lldb::eStateInvalid;
4831 
4832     bool before_first_timeout = true; // This is set to false the first time
4833                                       // that we have to halt the target.
4834     bool do_resume = true;
4835     bool handle_running_event = true;
4836 
4837     // This is just for accounting:
4838     uint32_t num_resumes = 0;
4839 
4840     // If we are going to run all threads the whole time, or if we are only
4841     // going to run one thread, then we don't need the first timeout.  So we
4842     // pretend we are after the first timeout already.
4843     if (!options.GetStopOthers() || !options.GetTryAllThreads())
4844       before_first_timeout = false;
4845 
4846     LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
4847               options.GetStopOthers(), options.GetTryAllThreads(),
4848               before_first_timeout);
4849 
4850     // This isn't going to work if there are unfetched events on the queue. Are
4851     // there cases where we might want to run the remaining events here, and
4852     // then try to call the function?  That's probably being too tricky for our
4853     // own good.
4854 
4855     Event *other_events = listener_sp->PeekAtNextEvent();
4856     if (other_events != nullptr) {
4857       diagnostic_manager.PutString(
4858           eDiagnosticSeverityError,
4859           "RunThreadPlan called with pending events on the queue.");
4860       return eExpressionSetupError;
4861     }
4862 
4863     // We also need to make sure that the next event is delivered.  We might be
4864     // calling a function as part of a thread plan, in which case the last
4865     // delivered event could be the running event, and we don't want event
4866     // coalescing to cause us to lose OUR running event...
4867     ForceNextEventDelivery();
4868 
4869 // This while loop must exit out the bottom, there's cleanup that we need to do
4870 // when we are done. So don't call return anywhere within it.
4871 
4872 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4873     // It's pretty much impossible to write test cases for things like: One
4874     // thread timeout expires, I go to halt, but the process already stopped on
4875     // the function call stop breakpoint.  Turning on this define will make us
4876     // not fetch the first event till after the halt.  So if you run a quick
4877     // function, it will have completed, and the completion event will be
4878     // waiting, when you interrupt for halt. The expression evaluation should
4879     // still succeed.
4880     bool miss_first_event = true;
4881 #endif
4882     while (true) {
4883       // We usually want to resume the process if we get to the top of the
4884       // loop. The only exception is if we get two running events with no
4885       // intervening stop, which can happen, we will just wait for then next
4886       // stop event.
4887       LLDB_LOGF(log,
4888                 "Top of while loop: do_resume: %i handle_running_event: %i "
4889                 "before_first_timeout: %i.",
4890                 do_resume, handle_running_event, before_first_timeout);
4891 
4892       if (do_resume || handle_running_event) {
4893         // Do the initial resume and wait for the running event before going
4894         // further.
4895 
4896         if (do_resume) {
4897           num_resumes++;
4898           Status resume_error = PrivateResume();
4899           if (!resume_error.Success()) {
4900             diagnostic_manager.Printf(
4901                 eDiagnosticSeverityError,
4902                 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
4903                 resume_error.AsCString());
4904             return_value = eExpressionSetupError;
4905             break;
4906           }
4907         }
4908 
4909         got_event =
4910             listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
4911         if (!got_event) {
4912           LLDB_LOGF(log,
4913                     "Process::RunThreadPlan(): didn't get any event after "
4914                     "resume %" PRIu32 ", exiting.",
4915                     num_resumes);
4916 
4917           diagnostic_manager.Printf(eDiagnosticSeverityError,
4918                                     "didn't get any event after resume %" PRIu32
4919                                     ", exiting.",
4920                                     num_resumes);
4921           return_value = eExpressionSetupError;
4922           break;
4923         }
4924 
4925         stop_state =
4926             Process::ProcessEventData::GetStateFromEvent(event_sp.get());
4927 
4928         if (stop_state != eStateRunning) {
4929           bool restarted = false;
4930 
4931           if (stop_state == eStateStopped) {
4932             restarted = Process::ProcessEventData::GetRestartedFromEvent(
4933                 event_sp.get());
4934             LLDB_LOGF(
4935                 log,
4936                 "Process::RunThreadPlan(): didn't get running event after "
4937                 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
4938                 "handle_running_event: %i).",
4939                 num_resumes, StateAsCString(stop_state), restarted, do_resume,
4940                 handle_running_event);
4941           }
4942 
4943           if (restarted) {
4944             // This is probably an overabundance of caution, I don't think I
4945             // should ever get a stopped & restarted event here.  But if I do,
4946             // the best thing is to Halt and then get out of here.
4947             const bool clear_thread_plans = false;
4948             const bool use_run_lock = false;
4949             Halt(clear_thread_plans, use_run_lock);
4950           }
4951 
4952           diagnostic_manager.Printf(
4953               eDiagnosticSeverityError,
4954               "didn't get running event after initial resume, got %s instead.",
4955               StateAsCString(stop_state));
4956           return_value = eExpressionSetupError;
4957           break;
4958         }
4959 
4960         if (log)
4961           log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
4962         // We need to call the function synchronously, so spin waiting for it
4963         // to return. If we get interrupted while executing, we're going to
4964         // lose our context, and won't be able to gather the result at this
4965         // point. We set the timeout AFTER the resume, since the resume takes
4966         // some time and we don't want to charge that to the timeout.
4967       } else {
4968         if (log)
4969           log->PutCString("Process::RunThreadPlan(): waiting for next event.");
4970       }
4971 
4972       do_resume = true;
4973       handle_running_event = true;
4974 
4975       // Now wait for the process to stop again:
4976       event_sp.reset();
4977 
4978       Timeout<std::micro> timeout =
4979           GetExpressionTimeout(options, before_first_timeout);
4980       if (log) {
4981         if (timeout) {
4982           auto now = system_clock::now();
4983           LLDB_LOGF(log,
4984                     "Process::RunThreadPlan(): about to wait - now is %s - "
4985                     "endpoint is %s",
4986                     llvm::to_string(now).c_str(),
4987                     llvm::to_string(now + *timeout).c_str());
4988         } else {
4989           LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
4990         }
4991       }
4992 
4993 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4994       // See comment above...
4995       if (miss_first_event) {
4996         std::this_thread::sleep_for(std::chrono::milliseconds(1));
4997         miss_first_event = false;
4998         got_event = false;
4999       } else
5000 #endif
5001         got_event = listener_sp->GetEvent(event_sp, timeout);
5002 
5003       if (got_event) {
5004         if (event_sp) {
5005           bool keep_going = false;
5006           if (event_sp->GetType() == eBroadcastBitInterrupt) {
5007             const bool clear_thread_plans = false;
5008             const bool use_run_lock = false;
5009             Halt(clear_thread_plans, use_run_lock);
5010             return_value = eExpressionInterrupted;
5011             diagnostic_manager.PutString(eDiagnosticSeverityRemark,
5012                                          "execution halted by user interrupt.");
5013             LLDB_LOGF(log, "Process::RunThreadPlan(): Got  interrupted by "
5014                            "eBroadcastBitInterrupted, exiting.");
5015             break;
5016           } else {
5017             stop_state =
5018                 Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5019             LLDB_LOGF(log,
5020                       "Process::RunThreadPlan(): in while loop, got event: %s.",
5021                       StateAsCString(stop_state));
5022 
5023             switch (stop_state) {
5024             case lldb::eStateStopped: {
5025               // We stopped, figure out what we are going to do now.
5026               ThreadSP thread_sp =
5027                   GetThreadList().FindThreadByIndexID(thread_idx_id);
5028               if (!thread_sp) {
5029                 // Ooh, our thread has vanished.  Unlikely that this was
5030                 // successful execution...
5031                 LLDB_LOGF(log,
5032                           "Process::RunThreadPlan(): execution completed "
5033                           "but our thread (index-id=%u) has vanished.",
5034                           thread_idx_id);
5035                 return_value = eExpressionInterrupted;
5036               } else if (Process::ProcessEventData::GetRestartedFromEvent(
5037                              event_sp.get())) {
5038                 // If we were restarted, we just need to go back up to fetch
5039                 // another event.
5040                 if (log) {
5041                   LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5042                                  "restart, so we'll continue waiting.");
5043                 }
5044                 keep_going = true;
5045                 do_resume = false;
5046                 handle_running_event = true;
5047               } else {
5048                 const bool handle_interrupts = true;
5049                 return_value = *HandleStoppedEvent(
5050                     *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5051                     event_to_broadcast_sp, options, handle_interrupts);
5052               }
5053             } break;
5054 
5055             case lldb::eStateRunning:
5056               // This shouldn't really happen, but sometimes we do get two
5057               // running events without an intervening stop, and in that case
5058               // we should just go back to waiting for the stop.
5059               do_resume = false;
5060               keep_going = true;
5061               handle_running_event = false;
5062               break;
5063 
5064             default:
5065               LLDB_LOGF(log,
5066                         "Process::RunThreadPlan(): execution stopped with "
5067                         "unexpected state: %s.",
5068                         StateAsCString(stop_state));
5069 
5070               if (stop_state == eStateExited)
5071                 event_to_broadcast_sp = event_sp;
5072 
5073               diagnostic_manager.PutString(
5074                   eDiagnosticSeverityError,
5075                   "execution stopped with unexpected state.");
5076               return_value = eExpressionInterrupted;
5077               break;
5078             }
5079           }
5080 
5081           if (keep_going)
5082             continue;
5083           else
5084             break;
5085         } else {
5086           if (log)
5087             log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5088                             "the event pointer was null.  How odd...");
5089           return_value = eExpressionInterrupted;
5090           break;
5091         }
5092       } else {
5093         // If we didn't get an event that means we've timed out... We will
5094         // interrupt the process here.  Depending on what we were asked to do
5095         // we will either exit, or try with all threads running for the same
5096         // timeout.
5097 
5098         if (log) {
5099           if (options.GetTryAllThreads()) {
5100             if (before_first_timeout) {
5101               LLDB_LOG(log,
5102                        "Running function with one thread timeout timed out.");
5103             } else
5104               LLDB_LOG(log, "Restarting function with all threads enabled and "
5105                             "timeout: {0} timed out, abandoning execution.",
5106                        timeout);
5107           } else
5108             LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5109                           "abandoning execution.",
5110                      timeout);
5111         }
5112 
5113         // It is possible that between the time we issued the Halt, and we get
5114         // around to calling Halt the target could have stopped.  That's fine,
5115         // Halt will figure that out and send the appropriate Stopped event.
5116         // BUT it is also possible that we stopped & restarted (e.g. hit a
5117         // signal with "stop" set to false.)  In
5118         // that case, we'll get the stopped & restarted event, and we should go
5119         // back to waiting for the Halt's stopped event.  That's what this
5120         // while loop does.
5121 
5122         bool back_to_top = true;
5123         uint32_t try_halt_again = 0;
5124         bool do_halt = true;
5125         const uint32_t num_retries = 5;
5126         while (try_halt_again < num_retries) {
5127           Status halt_error;
5128           if (do_halt) {
5129             LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5130             const bool clear_thread_plans = false;
5131             const bool use_run_lock = false;
5132             Halt(clear_thread_plans, use_run_lock);
5133           }
5134           if (halt_error.Success()) {
5135             if (log)
5136               log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5137 
5138             got_event =
5139                 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5140 
5141             if (got_event) {
5142               stop_state =
5143                   Process::ProcessEventData::GetStateFromEvent(event_sp.get());
5144               if (log) {
5145                 LLDB_LOGF(log,
5146                           "Process::RunThreadPlan(): Stopped with event: %s",
5147                           StateAsCString(stop_state));
5148                 if (stop_state == lldb::eStateStopped &&
5149                     Process::ProcessEventData::GetInterruptedFromEvent(
5150                         event_sp.get()))
5151                   log->PutCString("    Event was the Halt interruption event.");
5152               }
5153 
5154               if (stop_state == lldb::eStateStopped) {
5155                 if (Process::ProcessEventData::GetRestartedFromEvent(
5156                         event_sp.get())) {
5157                   if (log)
5158                     log->PutCString("Process::RunThreadPlan(): Went to halt "
5159                                     "but got a restarted event, there must be "
5160                                     "an un-restarted stopped event so try "
5161                                     "again...  "
5162                                     "Exiting wait loop.");
5163                   try_halt_again++;
5164                   do_halt = false;
5165                   continue;
5166                 }
5167 
5168                 // Between the time we initiated the Halt and the time we
5169                 // delivered it, the process could have already finished its
5170                 // job.  Check that here:
5171                 const bool handle_interrupts = false;
5172                 if (auto result = HandleStoppedEvent(
5173                         *thread, thread_plan_sp, thread_plan_restorer, event_sp,
5174                         event_to_broadcast_sp, options, handle_interrupts)) {
5175                   return_value = *result;
5176                   back_to_top = false;
5177                   break;
5178                 }
5179 
5180                 if (!options.GetTryAllThreads()) {
5181                   if (log)
5182                     log->PutCString("Process::RunThreadPlan(): try_all_threads "
5183                                     "was false, we stopped so now we're "
5184                                     "quitting.");
5185                   return_value = eExpressionInterrupted;
5186                   back_to_top = false;
5187                   break;
5188                 }
5189 
5190                 if (before_first_timeout) {
5191                   // Set all the other threads to run, and return to the top of
5192                   // the loop, which will continue;
5193                   before_first_timeout = false;
5194                   thread_plan_sp->SetStopOthers(false);
5195                   if (log)
5196                     log->PutCString(
5197                         "Process::RunThreadPlan(): about to resume.");
5198 
5199                   back_to_top = true;
5200                   break;
5201                 } else {
5202                   // Running all threads failed, so return Interrupted.
5203                   if (log)
5204                     log->PutCString("Process::RunThreadPlan(): running all "
5205                                     "threads timed out.");
5206                   return_value = eExpressionInterrupted;
5207                   back_to_top = false;
5208                   break;
5209                 }
5210               }
5211             } else {
5212               if (log)
5213                 log->PutCString("Process::RunThreadPlan(): halt said it "
5214                                 "succeeded, but I got no event.  "
5215                                 "I'm getting out of here passing Interrupted.");
5216               return_value = eExpressionInterrupted;
5217               back_to_top = false;
5218               break;
5219             }
5220           } else {
5221             try_halt_again++;
5222             continue;
5223           }
5224         }
5225 
5226         if (!back_to_top || try_halt_again > num_retries)
5227           break;
5228         else
5229           continue;
5230       }
5231     } // END WAIT LOOP
5232 
5233     // If we had to start up a temporary private state thread to run this
5234     // thread plan, shut it down now.
5235     if (backup_private_state_thread.IsJoinable()) {
5236       StopPrivateStateThread();
5237       Status error;
5238       m_private_state_thread = backup_private_state_thread;
5239       if (stopper_base_plan_sp) {
5240         thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5241       }
5242       if (old_state != eStateInvalid)
5243         m_public_state.SetValueNoLock(old_state);
5244     }
5245 
5246     if (return_value != eExpressionCompleted && log) {
5247       // Print a backtrace into the log so we can figure out where we are:
5248       StreamString s;
5249       s.PutCString("Thread state after unsuccessful completion: \n");
5250       thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX);
5251       log->PutString(s.GetString());
5252     }
5253     // Restore the thread state if we are going to discard the plan execution.
5254     // There are three cases where this could happen: 1) The execution
5255     // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5256     // was true 3) We got some other error, and discard_on_error was true
5257     bool should_unwind = (return_value == eExpressionInterrupted &&
5258                           options.DoesUnwindOnError()) ||
5259                          (return_value == eExpressionHitBreakpoint &&
5260                           options.DoesIgnoreBreakpoints());
5261 
5262     if (return_value == eExpressionCompleted || should_unwind) {
5263       thread_plan_sp->RestoreThreadState();
5264     }
5265 
5266     // Now do some processing on the results of the run:
5267     if (return_value == eExpressionInterrupted ||
5268         return_value == eExpressionHitBreakpoint) {
5269       if (log) {
5270         StreamString s;
5271         if (event_sp)
5272           event_sp->Dump(&s);
5273         else {
5274           log->PutCString("Process::RunThreadPlan(): Stop event that "
5275                           "interrupted us is NULL.");
5276         }
5277 
5278         StreamString ts;
5279 
5280         const char *event_explanation = nullptr;
5281 
5282         do {
5283           if (!event_sp) {
5284             event_explanation = "<no event>";
5285             break;
5286           } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5287             event_explanation = "<user interrupt>";
5288             break;
5289           } else {
5290             const Process::ProcessEventData *event_data =
5291                 Process::ProcessEventData::GetEventDataFromEvent(
5292                     event_sp.get());
5293 
5294             if (!event_data) {
5295               event_explanation = "<no event data>";
5296               break;
5297             }
5298 
5299             Process *process = event_data->GetProcessSP().get();
5300 
5301             if (!process) {
5302               event_explanation = "<no process>";
5303               break;
5304             }
5305 
5306             ThreadList &thread_list = process->GetThreadList();
5307 
5308             uint32_t num_threads = thread_list.GetSize();
5309             uint32_t thread_index;
5310 
5311             ts.Printf("<%u threads> ", num_threads);
5312 
5313             for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5314               Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5315 
5316               if (!thread) {
5317                 ts.Printf("<?> ");
5318                 continue;
5319               }
5320 
5321               ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5322               RegisterContext *register_context =
5323                   thread->GetRegisterContext().get();
5324 
5325               if (register_context)
5326                 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5327               else
5328                 ts.Printf("[ip unknown] ");
5329 
5330               // Show the private stop info here, the public stop info will be
5331               // from the last natural stop.
5332               lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5333               if (stop_info_sp) {
5334                 const char *stop_desc = stop_info_sp->GetDescription();
5335                 if (stop_desc)
5336                   ts.PutCString(stop_desc);
5337               }
5338               ts.Printf(">");
5339             }
5340 
5341             event_explanation = ts.GetData();
5342           }
5343         } while (false);
5344 
5345         if (event_explanation)
5346           LLDB_LOGF(log,
5347                     "Process::RunThreadPlan(): execution interrupted: %s %s",
5348                     s.GetData(), event_explanation);
5349         else
5350           LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5351                     s.GetData());
5352       }
5353 
5354       if (should_unwind) {
5355         LLDB_LOGF(log,
5356                   "Process::RunThreadPlan: ExecutionInterrupted - "
5357                   "discarding thread plans up to %p.",
5358                   static_cast<void *>(thread_plan_sp.get()));
5359         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5360       } else {
5361         LLDB_LOGF(log,
5362                   "Process::RunThreadPlan: ExecutionInterrupted - for "
5363                   "plan: %p not discarding.",
5364                   static_cast<void *>(thread_plan_sp.get()));
5365       }
5366     } else if (return_value == eExpressionSetupError) {
5367       if (log)
5368         log->PutCString("Process::RunThreadPlan(): execution set up error.");
5369 
5370       if (options.DoesUnwindOnError()) {
5371         thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5372       }
5373     } else {
5374       if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5375         if (log)
5376           log->PutCString("Process::RunThreadPlan(): thread plan is done");
5377         return_value = eExpressionCompleted;
5378       } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5379         if (log)
5380           log->PutCString(
5381               "Process::RunThreadPlan(): thread plan was discarded");
5382         return_value = eExpressionDiscarded;
5383       } else {
5384         if (log)
5385           log->PutCString(
5386               "Process::RunThreadPlan(): thread plan stopped in mid course");
5387         if (options.DoesUnwindOnError() && thread_plan_sp) {
5388           if (log)
5389             log->PutCString("Process::RunThreadPlan(): discarding thread plan "
5390                             "'cause unwind_on_error is set.");
5391           thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5392         }
5393       }
5394     }
5395 
5396     // Thread we ran the function in may have gone away because we ran the
5397     // target Check that it's still there, and if it is put it back in the
5398     // context. Also restore the frame in the context if it is still present.
5399     thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
5400     if (thread) {
5401       exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
5402     }
5403 
5404     // Also restore the current process'es selected frame & thread, since this
5405     // function calling may be done behind the user's back.
5406 
5407     if (selected_tid != LLDB_INVALID_THREAD_ID) {
5408       if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
5409           selected_stack_id.IsValid()) {
5410         // We were able to restore the selected thread, now restore the frame:
5411         std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5412         StackFrameSP old_frame_sp =
5413             GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5414                 selected_stack_id);
5415         if (old_frame_sp)
5416           GetThreadList().GetSelectedThread()->SetSelectedFrame(
5417               old_frame_sp.get());
5418       }
5419     }
5420   }
5421 
5422   // If the process exited during the run of the thread plan, notify everyone.
5423 
5424   if (event_to_broadcast_sp) {
5425     if (log)
5426       log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5427     BroadcastEvent(event_to_broadcast_sp);
5428   }
5429 
5430   return return_value;
5431 }
5432 
5433 const char *Process::ExecutionResultAsCString(ExpressionResults result) {
5434   const char *result_name;
5435 
5436   switch (result) {
5437   case eExpressionCompleted:
5438     result_name = "eExpressionCompleted";
5439     break;
5440   case eExpressionDiscarded:
5441     result_name = "eExpressionDiscarded";
5442     break;
5443   case eExpressionInterrupted:
5444     result_name = "eExpressionInterrupted";
5445     break;
5446   case eExpressionHitBreakpoint:
5447     result_name = "eExpressionHitBreakpoint";
5448     break;
5449   case eExpressionSetupError:
5450     result_name = "eExpressionSetupError";
5451     break;
5452   case eExpressionParseError:
5453     result_name = "eExpressionParseError";
5454     break;
5455   case eExpressionResultUnavailable:
5456     result_name = "eExpressionResultUnavailable";
5457     break;
5458   case eExpressionTimedOut:
5459     result_name = "eExpressionTimedOut";
5460     break;
5461   case eExpressionStoppedForDebug:
5462     result_name = "eExpressionStoppedForDebug";
5463     break;
5464   }
5465   return result_name;
5466 }
5467 
5468 void Process::GetStatus(Stream &strm) {
5469   const StateType state = GetState();
5470   if (StateIsStoppedState(state, false)) {
5471     if (state == eStateExited) {
5472       int exit_status = GetExitStatus();
5473       const char *exit_description = GetExitDescription();
5474       strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
5475                   GetID(), exit_status, exit_status,
5476                   exit_description ? exit_description : "");
5477     } else {
5478       if (state == eStateConnected)
5479         strm.Printf("Connected to remote target.\n");
5480       else
5481         strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
5482     }
5483   } else {
5484     strm.Printf("Process %" PRIu64 " is running.\n", GetID());
5485   }
5486 }
5487 
5488 size_t Process::GetThreadStatus(Stream &strm,
5489                                 bool only_threads_with_stop_reason,
5490                                 uint32_t start_frame, uint32_t num_frames,
5491                                 uint32_t num_frames_with_source,
5492                                 bool stop_format) {
5493   size_t num_thread_infos_dumped = 0;
5494 
5495   // You can't hold the thread list lock while calling Thread::GetStatus.  That
5496   // very well might run code (e.g. if we need it to get return values or
5497   // arguments.)  For that to work the process has to be able to acquire it.
5498   // So instead copy the thread ID's, and look them up one by one:
5499 
5500   uint32_t num_threads;
5501   std::vector<lldb::tid_t> thread_id_array;
5502   // Scope for thread list locker;
5503   {
5504     std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
5505     ThreadList &curr_thread_list = GetThreadList();
5506     num_threads = curr_thread_list.GetSize();
5507     uint32_t idx;
5508     thread_id_array.resize(num_threads);
5509     for (idx = 0; idx < num_threads; ++idx)
5510       thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
5511   }
5512 
5513   for (uint32_t i = 0; i < num_threads; i++) {
5514     ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
5515     if (thread_sp) {
5516       if (only_threads_with_stop_reason) {
5517         StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5518         if (!stop_info_sp || !stop_info_sp->IsValid())
5519           continue;
5520       }
5521       thread_sp->GetStatus(strm, start_frame, num_frames,
5522                            num_frames_with_source,
5523                            stop_format);
5524       ++num_thread_infos_dumped;
5525     } else {
5526       Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5527       LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
5528                      " vanished while running Thread::GetStatus.");
5529     }
5530   }
5531   return num_thread_infos_dumped;
5532 }
5533 
5534 void Process::AddInvalidMemoryRegion(const LoadRange &region) {
5535   m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
5536 }
5537 
5538 bool Process::RemoveInvalidMemoryRange(const LoadRange &region) {
5539   return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
5540                                            region.GetByteSize());
5541 }
5542 
5543 void Process::AddPreResumeAction(PreResumeActionCallback callback,
5544                                  void *baton) {
5545   m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
5546 }
5547 
5548 bool Process::RunPreResumeActions() {
5549   bool result = true;
5550   while (!m_pre_resume_actions.empty()) {
5551     struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
5552     m_pre_resume_actions.pop_back();
5553     bool this_result = action.callback(action.baton);
5554     if (result)
5555       result = this_result;
5556   }
5557   return result;
5558 }
5559 
5560 void Process::ClearPreResumeActions() { m_pre_resume_actions.clear(); }
5561 
5562 void Process::ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
5563 {
5564     PreResumeCallbackAndBaton element(callback, baton);
5565     auto found_iter = std::find(m_pre_resume_actions.begin(), m_pre_resume_actions.end(), element);
5566     if (found_iter != m_pre_resume_actions.end())
5567     {
5568         m_pre_resume_actions.erase(found_iter);
5569     }
5570 }
5571 
5572 ProcessRunLock &Process::GetRunLock() {
5573   if (m_private_state_thread.EqualsThread(Host::GetCurrentThread()))
5574     return m_private_run_lock;
5575   else
5576     return m_public_run_lock;
5577 }
5578 
5579 bool Process::CurrentThreadIsPrivateStateThread()
5580 {
5581   return m_private_state_thread.EqualsThread(Host::GetCurrentThread());
5582 }
5583 
5584 
5585 void Process::Flush() {
5586   m_thread_list.Flush();
5587   m_extended_thread_list.Flush();
5588   m_extended_thread_stop_id = 0;
5589   m_queue_list.Clear();
5590   m_queue_list_stop_id = 0;
5591 }
5592 
5593 void Process::DidExec() {
5594   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
5595   LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
5596 
5597   Target &target = GetTarget();
5598   target.CleanupProcess();
5599   target.ClearModules(false);
5600   m_dynamic_checkers_up.reset();
5601   m_abi_sp.reset();
5602   m_system_runtime_up.reset();
5603   m_os_up.reset();
5604   m_dyld_up.reset();
5605   m_jit_loaders_up.reset();
5606   m_image_tokens.clear();
5607   m_allocated_memory_cache.Clear();
5608   {
5609     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5610     m_language_runtimes.clear();
5611   }
5612   m_instrumentation_runtimes.clear();
5613   m_thread_list.DiscardThreadPlans();
5614   m_memory_cache.Clear(true);
5615   DoDidExec();
5616   CompleteAttach();
5617   // Flush the process (threads and all stack frames) after running
5618   // CompleteAttach() in case the dynamic loader loaded things in new
5619   // locations.
5620   Flush();
5621 
5622   // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5623   // let the target know so it can do any cleanup it needs to.
5624   target.DidExec();
5625 }
5626 
5627 addr_t Process::ResolveIndirectFunction(const Address *address, Status &error) {
5628   if (address == nullptr) {
5629     error.SetErrorString("Invalid address argument");
5630     return LLDB_INVALID_ADDRESS;
5631   }
5632 
5633   addr_t function_addr = LLDB_INVALID_ADDRESS;
5634 
5635   addr_t addr = address->GetLoadAddress(&GetTarget());
5636   std::map<addr_t, addr_t>::const_iterator iter =
5637       m_resolved_indirect_addresses.find(addr);
5638   if (iter != m_resolved_indirect_addresses.end()) {
5639     function_addr = (*iter).second;
5640   } else {
5641     if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
5642       Symbol *symbol = address->CalculateSymbolContextSymbol();
5643       error.SetErrorStringWithFormat(
5644           "Unable to call resolver for indirect function %s",
5645           symbol ? symbol->GetName().AsCString() : "<UNKNOWN>");
5646       function_addr = LLDB_INVALID_ADDRESS;
5647     } else {
5648       m_resolved_indirect_addresses.insert(
5649           std::pair<addr_t, addr_t>(addr, function_addr));
5650     }
5651   }
5652   return function_addr;
5653 }
5654 
5655 void Process::ModulesDidLoad(ModuleList &module_list) {
5656   SystemRuntime *sys_runtime = GetSystemRuntime();
5657   if (sys_runtime) {
5658     sys_runtime->ModulesDidLoad(module_list);
5659   }
5660 
5661   GetJITLoaders().ModulesDidLoad(module_list);
5662 
5663   // Give runtimes a chance to be created.
5664   InstrumentationRuntime::ModulesDidLoad(module_list, this,
5665                                          m_instrumentation_runtimes);
5666 
5667   // Tell runtimes about new modules.
5668   for (auto pos = m_instrumentation_runtimes.begin();
5669        pos != m_instrumentation_runtimes.end(); ++pos) {
5670     InstrumentationRuntimeSP runtime = pos->second;
5671     runtime->ModulesDidLoad(module_list);
5672   }
5673 
5674   // Let any language runtimes we have already created know about the modules
5675   // that loaded.
5676 
5677   // Iterate over a copy of this language runtime list in case the language
5678   // runtime ModulesDidLoad somehow causes the language runtime to be
5679   // unloaded.
5680   {
5681     std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
5682     LanguageRuntimeCollection language_runtimes(m_language_runtimes);
5683     for (const auto &pair : language_runtimes) {
5684       // We must check language_runtime_sp to make sure it is not nullptr as we
5685       // might cache the fact that we didn't have a language runtime for a
5686       // language.
5687       LanguageRuntimeSP language_runtime_sp = pair.second;
5688       if (language_runtime_sp)
5689         language_runtime_sp->ModulesDidLoad(module_list);
5690     }
5691   }
5692 
5693   // If we don't have an operating system plug-in, try to load one since
5694   // loading shared libraries might cause a new one to try and load
5695   if (!m_os_up)
5696     LoadOperatingSystemPlugin(false);
5697 
5698   // Give structured-data plugins a chance to see the modified modules.
5699   for (auto pair : m_structured_data_plugin_map) {
5700     if (pair.second)
5701       pair.second->ModulesDidLoad(*this, module_list);
5702   }
5703 }
5704 
5705 void Process::PrintWarning(uint64_t warning_type, const void *repeat_key,
5706                            const char *fmt, ...) {
5707   bool print_warning = true;
5708 
5709   StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream();
5710   if (!stream_sp)
5711     return;
5712   if (warning_type == eWarningsOptimization && !GetWarningsOptimization()) {
5713     return;
5714   }
5715 
5716   if (repeat_key != nullptr) {
5717     WarningsCollection::iterator it = m_warnings_issued.find(warning_type);
5718     if (it == m_warnings_issued.end()) {
5719       m_warnings_issued[warning_type] = WarningsPointerSet();
5720       m_warnings_issued[warning_type].insert(repeat_key);
5721     } else {
5722       if (it->second.find(repeat_key) != it->second.end()) {
5723         print_warning = false;
5724       } else {
5725         it->second.insert(repeat_key);
5726       }
5727     }
5728   }
5729 
5730   if (print_warning) {
5731     va_list args;
5732     va_start(args, fmt);
5733     stream_sp->PrintfVarArg(fmt, args);
5734     va_end(args);
5735   }
5736 }
5737 
5738 void Process::PrintWarningOptimization(const SymbolContext &sc) {
5739   if (GetWarningsOptimization() && sc.module_sp &&
5740       !sc.module_sp->GetFileSpec().GetFilename().IsEmpty() && sc.function &&
5741       sc.function->GetIsOptimized()) {
5742     PrintWarning(Process::Warnings::eWarningsOptimization, sc.module_sp.get(),
5743                  "%s was compiled with optimization - stepping may behave "
5744                  "oddly; variables may not be available.\n",
5745                  sc.module_sp->GetFileSpec().GetFilename().GetCString());
5746   }
5747 }
5748 
5749 bool Process::GetProcessInfo(ProcessInstanceInfo &info) {
5750   info.Clear();
5751 
5752   PlatformSP platform_sp = GetTarget().GetPlatform();
5753   if (!platform_sp)
5754     return false;
5755 
5756   return platform_sp->GetProcessInfo(GetID(), info);
5757 }
5758 
5759 ThreadCollectionSP Process::GetHistoryThreads(lldb::addr_t addr) {
5760   ThreadCollectionSP threads;
5761 
5762   const MemoryHistorySP &memory_history =
5763       MemoryHistory::FindPlugin(shared_from_this());
5764 
5765   if (!memory_history) {
5766     return threads;
5767   }
5768 
5769   threads = std::make_shared<ThreadCollection>(
5770       memory_history->GetHistoryThreads(addr));
5771 
5772   return threads;
5773 }
5774 
5775 InstrumentationRuntimeSP
5776 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type) {
5777   InstrumentationRuntimeCollection::iterator pos;
5778   pos = m_instrumentation_runtimes.find(type);
5779   if (pos == m_instrumentation_runtimes.end()) {
5780     return InstrumentationRuntimeSP();
5781   } else
5782     return (*pos).second;
5783 }
5784 
5785 bool Process::GetModuleSpec(const FileSpec &module_file_spec,
5786                             const ArchSpec &arch, ModuleSpec &module_spec) {
5787   module_spec.Clear();
5788   return false;
5789 }
5790 
5791 size_t Process::AddImageToken(lldb::addr_t image_ptr) {
5792   m_image_tokens.push_back(image_ptr);
5793   return m_image_tokens.size() - 1;
5794 }
5795 
5796 lldb::addr_t Process::GetImagePtrFromToken(size_t token) const {
5797   if (token < m_image_tokens.size())
5798     return m_image_tokens[token];
5799   return LLDB_INVALID_IMAGE_TOKEN;
5800 }
5801 
5802 void Process::ResetImageToken(size_t token) {
5803   if (token < m_image_tokens.size())
5804     m_image_tokens[token] = LLDB_INVALID_IMAGE_TOKEN;
5805 }
5806 
5807 Address
5808 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr,
5809                                                AddressRange range_bounds) {
5810   Target &target = GetTarget();
5811   DisassemblerSP disassembler_sp;
5812   InstructionList *insn_list = nullptr;
5813 
5814   Address retval = default_stop_addr;
5815 
5816   if (!target.GetUseFastStepping())
5817     return retval;
5818   if (!default_stop_addr.IsValid())
5819     return retval;
5820 
5821   const char *plugin_name = nullptr;
5822   const char *flavor = nullptr;
5823   const bool prefer_file_cache = true;
5824   disassembler_sp = Disassembler::DisassembleRange(
5825       target.GetArchitecture(), plugin_name, flavor, GetTarget(), range_bounds,
5826       prefer_file_cache);
5827   if (disassembler_sp)
5828     insn_list = &disassembler_sp->GetInstructionList();
5829 
5830   if (insn_list == nullptr) {
5831     return retval;
5832   }
5833 
5834   size_t insn_offset =
5835       insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
5836   if (insn_offset == UINT32_MAX) {
5837     return retval;
5838   }
5839 
5840   uint32_t branch_index =
5841       insn_list->GetIndexOfNextBranchInstruction(insn_offset, target,
5842                                                  false /* ignore_calls*/,
5843                                                  nullptr);
5844   if (branch_index == UINT32_MAX) {
5845     return retval;
5846   }
5847 
5848   if (branch_index > insn_offset) {
5849     Address next_branch_insn_address =
5850         insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
5851     if (next_branch_insn_address.IsValid() &&
5852         range_bounds.ContainsFileAddress(next_branch_insn_address)) {
5853       retval = next_branch_insn_address;
5854     }
5855   }
5856 
5857   return retval;
5858 }
5859 
5860 Status
5861 Process::GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list) {
5862 
5863   Status error;
5864 
5865   lldb::addr_t range_end = 0;
5866 
5867   region_list.clear();
5868   do {
5869     lldb_private::MemoryRegionInfo region_info;
5870     error = GetMemoryRegionInfo(range_end, region_info);
5871     // GetMemoryRegionInfo should only return an error if it is unimplemented.
5872     if (error.Fail()) {
5873       region_list.clear();
5874       break;
5875     }
5876 
5877     range_end = region_info.GetRange().GetRangeEnd();
5878     if (region_info.GetMapped() == MemoryRegionInfo::eYes) {
5879       region_list.push_back(std::move(region_info));
5880     }
5881   } while (range_end != LLDB_INVALID_ADDRESS);
5882 
5883   return error;
5884 }
5885 
5886 Status
5887 Process::ConfigureStructuredData(ConstString type_name,
5888                                  const StructuredData::ObjectSP &config_sp) {
5889   // If you get this, the Process-derived class needs to implement a method to
5890   // enable an already-reported asynchronous structured data feature. See
5891   // ProcessGDBRemote for an example implementation over gdb-remote.
5892   return Status("unimplemented");
5893 }
5894 
5895 void Process::MapSupportedStructuredDataPlugins(
5896     const StructuredData::Array &supported_type_names) {
5897   Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
5898 
5899   // Bail out early if there are no type names to map.
5900   if (supported_type_names.GetSize() == 0) {
5901     LLDB_LOGF(log, "Process::%s(): no structured data types supported",
5902               __FUNCTION__);
5903     return;
5904   }
5905 
5906   // Convert StructuredData type names to ConstString instances.
5907   std::set<ConstString> const_type_names;
5908 
5909   LLDB_LOGF(log,
5910             "Process::%s(): the process supports the following async "
5911             "structured data types:",
5912             __FUNCTION__);
5913 
5914   supported_type_names.ForEach(
5915       [&const_type_names, &log](StructuredData::Object *object) {
5916         if (!object) {
5917           // Invalid - shouldn't be null objects in the array.
5918           return false;
5919         }
5920 
5921         auto type_name = object->GetAsString();
5922         if (!type_name) {
5923           // Invalid format - all type names should be strings.
5924           return false;
5925         }
5926 
5927         const_type_names.insert(ConstString(type_name->GetValue()));
5928         LLDB_LOG(log, "- {0}", type_name->GetValue());
5929         return true;
5930       });
5931 
5932   // For each StructuredDataPlugin, if the plugin handles any of the types in
5933   // the supported_type_names, map that type name to that plugin. Stop when
5934   // we've consumed all the type names.
5935   // FIXME: should we return an error if there are type names nobody
5936   // supports?
5937   for (uint32_t plugin_index = 0; !const_type_names.empty(); plugin_index++) {
5938     auto create_instance =
5939            PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
5940                plugin_index);
5941     if (!create_instance)
5942       break;
5943 
5944     // Create the plugin.
5945     StructuredDataPluginSP plugin_sp = (*create_instance)(*this);
5946     if (!plugin_sp) {
5947       // This plugin doesn't think it can work with the process. Move on to the
5948       // next.
5949       continue;
5950     }
5951 
5952     // For any of the remaining type names, map any that this plugin supports.
5953     std::vector<ConstString> names_to_remove;
5954     for (auto &type_name : const_type_names) {
5955       if (plugin_sp->SupportsStructuredDataType(type_name)) {
5956         m_structured_data_plugin_map.insert(
5957             std::make_pair(type_name, plugin_sp));
5958         names_to_remove.push_back(type_name);
5959         LLDB_LOGF(log,
5960                   "Process::%s(): using plugin %s for type name "
5961                   "%s",
5962                   __FUNCTION__, plugin_sp->GetPluginName().GetCString(),
5963                   type_name.GetCString());
5964       }
5965     }
5966 
5967     // Remove the type names that were consumed by this plugin.
5968     for (auto &type_name : names_to_remove)
5969       const_type_names.erase(type_name);
5970   }
5971 }
5972 
5973 bool Process::RouteAsyncStructuredData(
5974     const StructuredData::ObjectSP object_sp) {
5975   // Nothing to do if there's no data.
5976   if (!object_sp)
5977     return false;
5978 
5979   // The contract is this must be a dictionary, so we can look up the routing
5980   // key via the top-level 'type' string value within the dictionary.
5981   StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
5982   if (!dictionary)
5983     return false;
5984 
5985   // Grab the async structured type name (i.e. the feature/plugin name).
5986   ConstString type_name;
5987   if (!dictionary->GetValueForKeyAsString("type", type_name))
5988     return false;
5989 
5990   // Check if there's a plugin registered for this type name.
5991   auto find_it = m_structured_data_plugin_map.find(type_name);
5992   if (find_it == m_structured_data_plugin_map.end()) {
5993     // We don't have a mapping for this structured data type.
5994     return false;
5995   }
5996 
5997   // Route the structured data to the plugin.
5998   find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
5999   return true;
6000 }
6001 
6002 Status Process::UpdateAutomaticSignalFiltering() {
6003   // Default implementation does nothign.
6004   // No automatic signal filtering to speak of.
6005   return Status();
6006 }
6007 
6008 UtilityFunction *Process::GetLoadImageUtilityFunction(
6009     Platform *platform,
6010     llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
6011   if (platform != GetTarget().GetPlatform().get())
6012     return nullptr;
6013   llvm::call_once(m_dlopen_utility_func_flag_once,
6014                   [&] { m_dlopen_utility_func_up = factory(); });
6015   return m_dlopen_utility_func_up.get();
6016 }
6017 
6018 bool Process::CallVoidArgVoidPtrReturn(const Address *address,
6019                                        addr_t &returned_func,
6020                                        bool trap_exceptions) {
6021   Thread *thread = GetThreadList().GetExpressionExecutionThread().get();
6022   if (thread == nullptr || address == nullptr)
6023     return false;
6024 
6025   EvaluateExpressionOptions options;
6026   options.SetStopOthers(true);
6027   options.SetUnwindOnError(true);
6028   options.SetIgnoreBreakpoints(true);
6029   options.SetTryAllThreads(true);
6030   options.SetDebug(false);
6031   options.SetTimeout(GetUtilityExpressionTimeout());
6032   options.SetTrapExceptions(trap_exceptions);
6033 
6034   auto type_system_or_err =
6035       GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC);
6036   if (!type_system_or_err) {
6037     llvm::consumeError(type_system_or_err.takeError());
6038     return false;
6039   }
6040   CompilerType void_ptr_type =
6041       type_system_or_err->GetBasicTypeFromAST(eBasicTypeVoid).GetPointerType();
6042   lldb::ThreadPlanSP call_plan_sp(new ThreadPlanCallFunction(
6043       *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6044   if (call_plan_sp) {
6045     DiagnosticManager diagnostics;
6046 
6047     StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6048     if (frame) {
6049       ExecutionContext exe_ctx;
6050       frame->CalculateExecutionContext(exe_ctx);
6051       ExpressionResults result =
6052           RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6053       if (result == eExpressionCompleted) {
6054         returned_func =
6055             call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6056                 LLDB_INVALID_ADDRESS);
6057 
6058         if (GetAddressByteSize() == 4) {
6059           if (returned_func == UINT32_MAX)
6060             return false;
6061         } else if (GetAddressByteSize() == 8) {
6062           if (returned_func == UINT64_MAX)
6063             return false;
6064         }
6065         return true;
6066       }
6067     }
6068   }
6069 
6070   return false;
6071 }
6072