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