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