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