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