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