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