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