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