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