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