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