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