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