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