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