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