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