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