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