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