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