1 //===-- Process.cpp -------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/ScopeExit.h"
15 #include "llvm/Support/ScopedPrinter.h"
16 #include "llvm/Support/Threading.h"
18 #include "lldb/Breakpoint/BreakpointLocation.h"
19 #include "lldb/Breakpoint/StoppointCallbackContext.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Expression/DiagnosticManager.h"
25 #include "lldb/Expression/DynamicCheckerFunctions.h"
26 #include "lldb/Expression/UserExpression.h"
27 #include "lldb/Expression/UtilityFunction.h"
28 #include "lldb/Host/ConnectionFileDescriptor.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/OptionParser.h"
33 #include "lldb/Host/Pipe.h"
34 #include "lldb/Host/Terminal.h"
35 #include "lldb/Host/ThreadLauncher.h"
36 #include "lldb/Interpreter/CommandInterpreter.h"
37 #include "lldb/Interpreter/OptionArgParser.h"
38 #include "lldb/Interpreter/OptionValueProperties.h"
39 #include "lldb/Symbol/Function.h"
40 #include "lldb/Symbol/Symbol.h"
41 #include "lldb/Target/ABI.h"
42 #include "lldb/Target/AssertFrameRecognizer.h"
43 #include "lldb/Target/DynamicLoader.h"
44 #include "lldb/Target/InstrumentationRuntime.h"
45 #include "lldb/Target/JITLoader.h"
46 #include "lldb/Target/JITLoaderList.h"
47 #include "lldb/Target/Language.h"
48 #include "lldb/Target/LanguageRuntime.h"
49 #include "lldb/Target/MemoryHistory.h"
50 #include "lldb/Target/MemoryRegionInfo.h"
51 #include "lldb/Target/OperatingSystem.h"
52 #include "lldb/Target/Platform.h"
53 #include "lldb/Target/Process.h"
54 #include "lldb/Target/RegisterContext.h"
55 #include "lldb/Target/StopInfo.h"
56 #include "lldb/Target/StructuredDataPlugin.h"
57 #include "lldb/Target/SystemRuntime.h"
58 #include "lldb/Target/Target.h"
59 #include "lldb/Target/TargetList.h"
60 #include "lldb/Target/Thread.h"
61 #include "lldb/Target/ThreadPlan.h"
62 #include "lldb/Target/ThreadPlanBase.h"
63 #include "lldb/Target/ThreadPlanCallFunction.h"
64 #include "lldb/Target/ThreadPlanStack.h"
65 #include "lldb/Target/UnixSignals.h"
66 #include "lldb/Utility/Event.h"
67 #include "lldb/Utility/LLDBLog.h"
68 #include "lldb/Utility/Log.h"
69 #include "lldb/Utility/NameMatches.h"
70 #include "lldb/Utility/ProcessInfo.h"
71 #include "lldb/Utility/SelectHelper.h"
72 #include "lldb/Utility/State.h"
73 #include "lldb/Utility/Timer.h"
76 using namespace lldb_private
;
77 using namespace std::chrono
;
79 // Comment out line below to disable memory caching, overriding the process
80 // setting target.process.disable-memory-cache
81 #define ENABLE_MEMORY_CACHING
83 #ifdef ENABLE_MEMORY_CACHING
84 #define DISABLE_MEM_CACHE_DEFAULT false
86 #define DISABLE_MEM_CACHE_DEFAULT true
89 class ProcessOptionValueProperties
90 : public Cloneable
<ProcessOptionValueProperties
, OptionValueProperties
> {
92 ProcessOptionValueProperties(llvm::StringRef name
) : Cloneable(name
) {}
95 GetPropertyAtIndex(size_t idx
,
96 const ExecutionContext
*exe_ctx
) const override
{
97 // When getting the value for a key from the process options, we will
98 // always try and grab the setting from the current process if there is
99 // one. Else we just use the one from this instance.
101 Process
*process
= exe_ctx
->GetProcessPtr();
103 ProcessOptionValueProperties
*instance_properties
=
104 static_cast<ProcessOptionValueProperties
*>(
105 process
->GetValueProperties().get());
106 if (this != instance_properties
)
107 return instance_properties
->ProtectedGetPropertyAtIndex(idx
);
110 return ProtectedGetPropertyAtIndex(idx
);
114 static constexpr OptionEnumValueElement g_follow_fork_mode_values
[] = {
118 "Continue tracing the parent process and detach the child.",
123 "Trace the child process and detach the parent.",
127 #define LLDB_PROPERTIES_process
128 #include "TargetProperties.inc"
131 #define LLDB_PROPERTIES_process
132 #include "TargetPropertiesEnum.inc"
133 ePropertyExperimental
,
136 #define LLDB_PROPERTIES_process_experimental
137 #include "TargetProperties.inc"
140 #define LLDB_PROPERTIES_process_experimental
141 #include "TargetPropertiesEnum.inc"
144 class ProcessExperimentalOptionValueProperties
145 : public Cloneable
<ProcessExperimentalOptionValueProperties
,
146 OptionValueProperties
> {
148 ProcessExperimentalOptionValueProperties()
149 : Cloneable(Properties::GetExperimentalSettingsName()) {}
152 ProcessExperimentalProperties::ProcessExperimentalProperties()
153 : Properties(OptionValuePropertiesSP(
154 new ProcessExperimentalOptionValueProperties())) {
155 m_collection_sp
->Initialize(g_process_experimental_properties
);
158 ProcessProperties::ProcessProperties(lldb_private::Process
*process
)
160 m_process(process
) // Can be nullptr for global ProcessProperties
162 if (process
== nullptr) {
163 // Global process properties, set them up one time
164 m_collection_sp
= std::make_shared
<ProcessOptionValueProperties
>("process");
165 m_collection_sp
->Initialize(g_process_properties
);
166 m_collection_sp
->AppendProperty(
167 "thread", "Settings specific to threads.", true,
168 Thread::GetGlobalProperties().GetValueProperties());
171 OptionValueProperties::CreateLocalCopy(Process::GetGlobalProperties());
172 m_collection_sp
->SetValueChangedCallback(
173 ePropertyPythonOSPluginPath
,
174 [this] { m_process
->LoadOperatingSystemPlugin(true); });
177 m_experimental_properties_up
=
178 std::make_unique
<ProcessExperimentalProperties
>();
179 m_collection_sp
->AppendProperty(
180 Properties::GetExperimentalSettingsName(),
181 "Experimental settings - setting these won't produce "
182 "errors if the setting is not present.",
183 true, m_experimental_properties_up
->GetValueProperties());
186 ProcessProperties::~ProcessProperties() = default;
188 bool ProcessProperties::GetDisableMemoryCache() const {
189 const uint32_t idx
= ePropertyDisableMemCache
;
190 return GetPropertyAtIndexAs
<bool>(
191 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
194 uint64_t ProcessProperties::GetMemoryCacheLineSize() const {
195 const uint32_t idx
= ePropertyMemCacheLineSize
;
196 return GetPropertyAtIndexAs
<uint64_t>(
197 idx
, g_process_properties
[idx
].default_uint_value
);
200 Args
ProcessProperties::GetExtraStartupCommands() const {
202 const uint32_t idx
= ePropertyExtraStartCommand
;
203 m_collection_sp
->GetPropertyAtIndexAsArgs(idx
, args
);
207 void ProcessProperties::SetExtraStartupCommands(const Args
&args
) {
208 const uint32_t idx
= ePropertyExtraStartCommand
;
209 m_collection_sp
->SetPropertyAtIndexFromArgs(idx
, args
);
212 FileSpec
ProcessProperties::GetPythonOSPluginPath() const {
213 const uint32_t idx
= ePropertyPythonOSPluginPath
;
214 return GetPropertyAtIndexAs
<FileSpec
>(idx
, {});
217 uint32_t ProcessProperties::GetVirtualAddressableBits() const {
218 const uint32_t idx
= ePropertyVirtualAddressableBits
;
219 return GetPropertyAtIndexAs
<uint64_t>(
220 idx
, g_process_properties
[idx
].default_uint_value
);
223 void ProcessProperties::SetVirtualAddressableBits(uint32_t bits
) {
224 const uint32_t idx
= ePropertyVirtualAddressableBits
;
225 SetPropertyAtIndex(idx
, static_cast<uint64_t>(bits
));
228 uint32_t ProcessProperties::GetHighmemVirtualAddressableBits() const {
229 const uint32_t idx
= ePropertyHighmemVirtualAddressableBits
;
230 return GetPropertyAtIndexAs
<uint64_t>(
231 idx
, g_process_properties
[idx
].default_uint_value
);
234 void ProcessProperties::SetHighmemVirtualAddressableBits(uint32_t bits
) {
235 const uint32_t idx
= ePropertyHighmemVirtualAddressableBits
;
236 SetPropertyAtIndex(idx
, static_cast<uint64_t>(bits
));
239 void ProcessProperties::SetPythonOSPluginPath(const FileSpec
&file
) {
240 const uint32_t idx
= ePropertyPythonOSPluginPath
;
241 SetPropertyAtIndex(idx
, file
);
244 bool ProcessProperties::GetIgnoreBreakpointsInExpressions() const {
245 const uint32_t idx
= ePropertyIgnoreBreakpointsInExpressions
;
246 return GetPropertyAtIndexAs
<bool>(
247 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
250 void ProcessProperties::SetIgnoreBreakpointsInExpressions(bool ignore
) {
251 const uint32_t idx
= ePropertyIgnoreBreakpointsInExpressions
;
252 SetPropertyAtIndex(idx
, ignore
);
255 bool ProcessProperties::GetUnwindOnErrorInExpressions() const {
256 const uint32_t idx
= ePropertyUnwindOnErrorInExpressions
;
257 return GetPropertyAtIndexAs
<bool>(
258 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
261 void ProcessProperties::SetUnwindOnErrorInExpressions(bool ignore
) {
262 const uint32_t idx
= ePropertyUnwindOnErrorInExpressions
;
263 SetPropertyAtIndex(idx
, ignore
);
266 bool ProcessProperties::GetStopOnSharedLibraryEvents() const {
267 const uint32_t idx
= ePropertyStopOnSharedLibraryEvents
;
268 return GetPropertyAtIndexAs
<bool>(
269 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
272 void ProcessProperties::SetStopOnSharedLibraryEvents(bool stop
) {
273 const uint32_t idx
= ePropertyStopOnSharedLibraryEvents
;
274 SetPropertyAtIndex(idx
, stop
);
277 bool ProcessProperties::GetDisableLangRuntimeUnwindPlans() const {
278 const uint32_t idx
= ePropertyDisableLangRuntimeUnwindPlans
;
279 return GetPropertyAtIndexAs
<bool>(
280 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
283 void ProcessProperties::SetDisableLangRuntimeUnwindPlans(bool disable
) {
284 const uint32_t idx
= ePropertyDisableLangRuntimeUnwindPlans
;
285 SetPropertyAtIndex(idx
, disable
);
289 bool ProcessProperties::GetDetachKeepsStopped() const {
290 const uint32_t idx
= ePropertyDetachKeepsStopped
;
291 return GetPropertyAtIndexAs
<bool>(
292 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
295 void ProcessProperties::SetDetachKeepsStopped(bool stop
) {
296 const uint32_t idx
= ePropertyDetachKeepsStopped
;
297 SetPropertyAtIndex(idx
, stop
);
300 bool ProcessProperties::GetWarningsOptimization() const {
301 const uint32_t idx
= ePropertyWarningOptimization
;
302 return GetPropertyAtIndexAs
<bool>(
303 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
306 bool ProcessProperties::GetWarningsUnsupportedLanguage() const {
307 const uint32_t idx
= ePropertyWarningUnsupportedLanguage
;
308 return GetPropertyAtIndexAs
<bool>(
309 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
312 bool ProcessProperties::GetStopOnExec() const {
313 const uint32_t idx
= ePropertyStopOnExec
;
314 return GetPropertyAtIndexAs
<bool>(
315 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
318 std::chrono::seconds
ProcessProperties::GetUtilityExpressionTimeout() const {
319 const uint32_t idx
= ePropertyUtilityExpressionTimeout
;
320 uint64_t value
= GetPropertyAtIndexAs
<uint64_t>(
321 idx
, g_process_properties
[idx
].default_uint_value
);
322 return std::chrono::seconds(value
);
325 std::chrono::seconds
ProcessProperties::GetInterruptTimeout() const {
326 const uint32_t idx
= ePropertyInterruptTimeout
;
327 uint64_t value
= GetPropertyAtIndexAs
<uint64_t>(
328 idx
, g_process_properties
[idx
].default_uint_value
);
329 return std::chrono::seconds(value
);
332 bool ProcessProperties::GetSteppingRunsAllThreads() const {
333 const uint32_t idx
= ePropertySteppingRunsAllThreads
;
334 return GetPropertyAtIndexAs
<bool>(
335 idx
, g_process_properties
[idx
].default_uint_value
!= 0);
338 bool ProcessProperties::GetOSPluginReportsAllThreads() const {
339 const bool fail_value
= true;
340 const Property
*exp_property
=
341 m_collection_sp
->GetPropertyAtIndex(ePropertyExperimental
);
342 OptionValueProperties
*exp_values
=
343 exp_property
->GetValue()->GetAsProperties();
348 ->GetPropertyAtIndexAs
<bool>(ePropertyOSPluginReportsAllThreads
)
349 .value_or(fail_value
);
352 void ProcessProperties::SetOSPluginReportsAllThreads(bool does_report
) {
353 const Property
*exp_property
=
354 m_collection_sp
->GetPropertyAtIndex(ePropertyExperimental
);
355 OptionValueProperties
*exp_values
=
356 exp_property
->GetValue()->GetAsProperties();
358 exp_values
->SetPropertyAtIndex(ePropertyOSPluginReportsAllThreads
,
362 FollowForkMode
ProcessProperties::GetFollowForkMode() const {
363 const uint32_t idx
= ePropertyFollowForkMode
;
364 return GetPropertyAtIndexAs
<FollowForkMode
>(
365 idx
, static_cast<FollowForkMode
>(
366 g_process_properties
[idx
].default_uint_value
));
369 ProcessSP
Process::FindPlugin(lldb::TargetSP target_sp
,
370 llvm::StringRef plugin_name
,
371 ListenerSP listener_sp
,
372 const FileSpec
*crash_file_path
,
374 static uint32_t g_process_unique_id
= 0;
376 ProcessSP process_sp
;
377 ProcessCreateInstance create_callback
= nullptr;
378 if (!plugin_name
.empty()) {
380 PluginManager::GetProcessCreateCallbackForPluginName(plugin_name
);
381 if (create_callback
) {
382 process_sp
= create_callback(target_sp
, listener_sp
, crash_file_path
,
385 if (process_sp
->CanDebug(target_sp
, true)) {
386 process_sp
->m_process_unique_id
= ++g_process_unique_id
;
392 for (uint32_t idx
= 0;
394 PluginManager::GetProcessCreateCallbackAtIndex(idx
)) != nullptr;
396 process_sp
= create_callback(target_sp
, listener_sp
, crash_file_path
,
399 if (process_sp
->CanDebug(target_sp
, false)) {
400 process_sp
->m_process_unique_id
= ++g_process_unique_id
;
410 ConstString
&Process::GetStaticBroadcasterClass() {
411 static ConstString
class_name("lldb.process");
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.
421 Process::Process(lldb::TargetSP target_sp
, ListenerSP listener_sp
,
422 const UnixSignalsSP
&unix_signals_sp
)
423 : ProcessProperties(this),
424 Broadcaster((target_sp
->GetDebugger().GetBroadcasterManager()),
425 Process::GetStaticBroadcasterClass().AsCString()),
426 m_target_wp(target_sp
), m_public_state(eStateUnloaded
),
427 m_private_state(eStateUnloaded
),
428 m_private_state_broadcaster(nullptr,
429 "lldb.process.internal_state_broadcaster"),
430 m_private_state_control_broadcaster(
431 nullptr, "lldb.process.internal_state_control_broadcaster"),
432 m_private_state_listener_sp(
433 Listener::MakeListener("lldb.process.internal_state_listener")),
434 m_mod_id(), m_process_unique_id(0), m_thread_index_id(0),
435 m_thread_id_to_index_id_map(), m_exit_status(-1), m_exit_string(),
436 m_exit_status_mutex(), m_thread_mutex(), m_thread_list_real(this),
437 m_thread_list(this), m_thread_plans(*this), m_extended_thread_list(this),
438 m_extended_thread_stop_id(0), m_queue_list(this), m_queue_list_stop_id(0),
439 m_notifications(), m_image_tokens(),
440 m_breakpoint_site_list(), m_dynamic_checkers_up(),
441 m_unix_signals_sp(unix_signals_sp
), m_abi_sp(), m_process_input_reader(),
442 m_stdio_communication("process.stdio"), m_stdio_communication_mutex(),
443 m_stdin_forward(false), m_stdout_data(), m_stderr_data(),
444 m_profile_data_comm_mutex(), m_profile_data(), m_iohandler_sync(0),
445 m_memory_cache(*this), m_allocated_memory_cache(*this),
446 m_should_detach(false), m_next_event_action_up(), m_public_run_lock(),
447 m_private_run_lock(), m_currently_handling_do_on_removals(false),
448 m_resume_requested(false), m_finalizing(false),
449 m_clear_thread_plans_on_stop(false), m_force_next_event_delivery(false),
450 m_last_broadcast_state(eStateInvalid
), m_destroy_in_process(false),
451 m_can_interpret_function_calls(false), m_run_thread_plan_lock(),
452 m_can_jit(eCanJITDontKnow
) {
453 CheckInWithManager();
455 Log
*log
= GetLog(LLDBLog::Object
);
456 LLDB_LOGF(log
, "%p Process::Process()", static_cast<void *>(this));
458 if (!m_unix_signals_sp
)
459 m_unix_signals_sp
= std::make_shared
<UnixSignals
>();
461 SetEventName(eBroadcastBitStateChanged
, "state-changed");
462 SetEventName(eBroadcastBitInterrupt
, "interrupt");
463 SetEventName(eBroadcastBitSTDOUT
, "stdout-available");
464 SetEventName(eBroadcastBitSTDERR
, "stderr-available");
465 SetEventName(eBroadcastBitProfileData
, "profile-data-available");
466 SetEventName(eBroadcastBitStructuredData
, "structured-data-available");
468 m_private_state_control_broadcaster
.SetEventName(
469 eBroadcastInternalStateControlStop
, "control-stop");
470 m_private_state_control_broadcaster
.SetEventName(
471 eBroadcastInternalStateControlPause
, "control-pause");
472 m_private_state_control_broadcaster
.SetEventName(
473 eBroadcastInternalStateControlResume
, "control-resume");
475 // The listener passed into process creation is the primary listener:
476 // It always listens for all the event bits for Process:
477 SetPrimaryListener(listener_sp
);
479 m_private_state_listener_sp
->StartListeningForEvents(
480 &m_private_state_broadcaster
,
481 eBroadcastBitStateChanged
| eBroadcastBitInterrupt
);
483 m_private_state_listener_sp
->StartListeningForEvents(
484 &m_private_state_control_broadcaster
,
485 eBroadcastInternalStateControlStop
| eBroadcastInternalStateControlPause
|
486 eBroadcastInternalStateControlResume
);
487 // We need something valid here, even if just the default UnixSignalsSP.
488 assert(m_unix_signals_sp
&& "null m_unix_signals_sp after initialization");
490 // Allow the platform to override the default cache line size
491 OptionValueSP value_sp
=
492 m_collection_sp
->GetPropertyAtIndex(ePropertyMemCacheLineSize
)
494 uint64_t platform_cache_line_size
=
495 target_sp
->GetPlatform()->GetDefaultMemoryCacheLineSize();
496 if (!value_sp
->OptionWasSet() && platform_cache_line_size
!= 0)
497 value_sp
->SetValueAs(platform_cache_line_size
);
499 RegisterAssertFrameRecognizer(this);
502 Process::~Process() {
503 Log
*log
= GetLog(LLDBLog::Object
);
504 LLDB_LOGF(log
, "%p Process::~Process()", static_cast<void *>(this));
505 StopPrivateStateThread();
507 // ThreadList::Clear() will try to acquire this process's mutex, so
508 // explicitly clear the thread list here to ensure that the mutex is not
509 // destroyed before the thread list.
510 m_thread_list
.Clear();
513 ProcessProperties
&Process::GetGlobalProperties() {
514 // NOTE: intentional leak so we don't crash if global destructor chain gets
515 // called as other threads still use the result of this function
516 static ProcessProperties
*g_settings_ptr
=
517 new ProcessProperties(nullptr);
518 return *g_settings_ptr
;
521 void Process::Finalize() {
522 if (m_finalizing
.exchange(true))
525 // Destroy the process. This will call the virtual function DoDestroy under
526 // the hood, giving our derived class a chance to do the ncessary tear down.
529 // Clear our broadcaster before we proceed with destroying
530 Broadcaster::Clear();
532 // Do any cleanup needed prior to being destructed... Subclasses that
533 // override this method should call this superclass method as well.
535 // We need to destroy the loader before the derived Process class gets
536 // destroyed since it is very likely that undoing the loader will require
537 // access to the real process.
538 m_dynamic_checkers_up
.reset();
541 m_system_runtime_up
.reset();
543 m_jit_loaders_up
.reset();
544 m_thread_plans
.Clear();
545 m_thread_list_real
.Destroy();
546 m_thread_list
.Destroy();
547 m_extended_thread_list
.Destroy();
548 m_queue_list
.Clear();
549 m_queue_list_stop_id
= 0;
550 std::vector
<Notifications
> empty_notifications
;
551 m_notifications
.swap(empty_notifications
);
552 m_image_tokens
.clear();
553 m_memory_cache
.Clear();
554 m_allocated_memory_cache
.Clear(/*deallocate_memory=*/true);
556 std::lock_guard
<std::recursive_mutex
> guard(m_language_runtimes_mutex
);
557 m_language_runtimes
.clear();
559 m_instrumentation_runtimes
.clear();
560 m_next_event_action_up
.reset();
561 // Clear the last natural stop ID since it has a strong reference to this
563 m_mod_id
.SetStopEventForLastNaturalStopID(EventSP());
564 // We have to be very careful here as the m_private_state_listener might
565 // contain events that have ProcessSP values in them which can keep this
566 // process around forever. These events need to be cleared out.
567 m_private_state_listener_sp
->Clear();
568 m_public_run_lock
.TrySetRunning(); // This will do nothing if already locked
569 m_public_run_lock
.SetStopped();
570 m_private_run_lock
.TrySetRunning(); // This will do nothing if already locked
571 m_private_run_lock
.SetStopped();
572 m_structured_data_plugin_map
.clear();
575 void Process::RegisterNotificationCallbacks(const Notifications
&callbacks
) {
576 m_notifications
.push_back(callbacks
);
577 if (callbacks
.initialize
!= nullptr)
578 callbacks
.initialize(callbacks
.baton
, this);
581 bool Process::UnregisterNotificationCallbacks(const Notifications
&callbacks
) {
582 std::vector
<Notifications
>::iterator pos
, end
= m_notifications
.end();
583 for (pos
= m_notifications
.begin(); pos
!= end
; ++pos
) {
584 if (pos
->baton
== callbacks
.baton
&&
585 pos
->initialize
== callbacks
.initialize
&&
586 pos
->process_state_changed
== callbacks
.process_state_changed
) {
587 m_notifications
.erase(pos
);
594 void Process::SynchronouslyNotifyStateChanged(StateType state
) {
595 std::vector
<Notifications
>::iterator notification_pos
,
596 notification_end
= m_notifications
.end();
597 for (notification_pos
= m_notifications
.begin();
598 notification_pos
!= notification_end
; ++notification_pos
) {
599 if (notification_pos
->process_state_changed
)
600 notification_pos
->process_state_changed(notification_pos
->baton
, this,
605 // FIXME: We need to do some work on events before the general Listener sees
607 // For instance if we are continuing from a breakpoint, we need to ensure that
608 // we do the little "insert real insn, step & stop" trick. But we can't do
609 // that when the event is delivered by the broadcaster - since that is done on
610 // the thread that is waiting for new events, so if we needed more than one
611 // event for our handling, we would stall. So instead we do it when we fetch
612 // the event off of the queue.
615 StateType
Process::GetNextEvent(EventSP
&event_sp
) {
616 StateType state
= eStateInvalid
;
618 if (GetPrimaryListener()->GetEventForBroadcaster(this, event_sp
,
619 std::chrono::seconds(0)) &&
621 state
= Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
626 void Process::SyncIOHandler(uint32_t iohandler_id
,
627 const Timeout
<std::micro
> &timeout
) {
628 // don't sync (potentially context switch) in case where there is no process
630 if (!ProcessIOHandlerExists())
633 auto Result
= m_iohandler_sync
.WaitForValueNotEqualTo(iohandler_id
, timeout
);
635 Log
*log
= GetLog(LLDBLog::Process
);
639 "waited from m_iohandler_sync to change from {0}. New value is {1}.",
640 iohandler_id
, *Result
);
642 LLDB_LOG(log
, "timed out waiting for m_iohandler_sync to change from {0}.",
647 StateType
Process::WaitForProcessToStop(
648 const Timeout
<std::micro
> &timeout
, EventSP
*event_sp_ptr
, bool wait_always
,
649 ListenerSP hijack_listener_sp
, Stream
*stream
, bool use_run_lock
,
650 SelectMostRelevant select_most_relevant
) {
651 // We can't just wait for a "stopped" event, because the stopped event may
652 // have restarted the target. We have to actually check each event, and in
653 // the case of a stopped event check the restarted flag on the event.
655 event_sp_ptr
->reset();
656 StateType state
= GetState();
657 // If we are exited or detached, we won't ever get back to any other valid
659 if (state
== eStateDetached
|| state
== eStateExited
)
662 Log
*log
= GetLog(LLDBLog::Process
);
663 LLDB_LOG(log
, "timeout = {0}", timeout
);
665 if (!wait_always
&& StateIsStoppedState(state
, true) &&
666 StateIsStoppedState(GetPrivateState(), true)) {
668 "Process::%s returning without waiting for events; process "
669 "private and public states are already 'stopped'.",
671 // We need to toggle the run lock as this won't get done in
672 // SetPublicState() if the process is hijacked.
673 if (hijack_listener_sp
&& use_run_lock
)
674 m_public_run_lock
.SetStopped();
678 while (state
!= eStateInvalid
) {
680 state
= GetStateChangedEvents(event_sp
, timeout
, hijack_listener_sp
);
681 if (event_sp_ptr
&& event_sp
)
682 *event_sp_ptr
= event_sp
;
684 bool pop_process_io_handler
= (hijack_listener_sp
.get() != nullptr);
685 Process::HandleProcessStateChangedEvent(
686 event_sp
, stream
, select_most_relevant
, pop_process_io_handler
);
693 // We need to toggle the run lock as this won't get done in
694 // SetPublicState() if the process is hijacked.
695 if (hijack_listener_sp
&& use_run_lock
)
696 m_public_run_lock
.SetStopped();
699 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp
.get()))
702 // We need to toggle the run lock as this won't get done in
703 // SetPublicState() if the process is hijacked.
704 if (hijack_listener_sp
&& use_run_lock
)
705 m_public_run_lock
.SetStopped();
715 bool Process::HandleProcessStateChangedEvent(
716 const EventSP
&event_sp
, Stream
*stream
,
717 SelectMostRelevant select_most_relevant
,
718 bool &pop_process_io_handler
) {
719 const bool handle_pop
= pop_process_io_handler
;
721 pop_process_io_handler
= false;
722 ProcessSP process_sp
=
723 Process::ProcessEventData::GetProcessFromEvent(event_sp
.get());
728 StateType event_state
=
729 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
730 if (event_state
== eStateInvalid
)
733 switch (event_state
) {
736 case eStateAttaching
:
737 case eStateLaunching
:
741 stream
->Printf("Process %" PRIu64
" %s\n", process_sp
->GetID(),
742 StateAsCString(event_state
));
743 if (event_state
== eStateDetached
)
744 pop_process_io_handler
= true;
747 case eStateConnected
:
749 // Don't be chatty when we run...
754 process_sp
->GetStatus(*stream
);
755 pop_process_io_handler
= true;
760 case eStateSuspended
:
761 // Make sure the program hasn't been auto-restarted:
762 if (Process::ProcessEventData::GetRestartedFromEvent(event_sp
.get())) {
765 Process::ProcessEventData::GetNumRestartedReasons(event_sp
.get());
766 if (num_reasons
> 0) {
767 // FIXME: Do we want to report this, or would that just be annoyingly
769 if (num_reasons
== 1) {
771 Process::ProcessEventData::GetRestartedReasonAtIndex(
773 stream
->Printf("Process %" PRIu64
" stopped and restarted: %s\n",
775 reason
? reason
: "<UNKNOWN REASON>");
777 stream
->Printf("Process %" PRIu64
778 " stopped and restarted, reasons:\n",
779 process_sp
->GetID());
781 for (size_t i
= 0; i
< num_reasons
; i
++) {
783 Process::ProcessEventData::GetRestartedReasonAtIndex(
785 stream
->Printf("\t%s\n", reason
? reason
: "<UNKNOWN REASON>");
791 StopInfoSP curr_thread_stop_info_sp
;
792 // Lock the thread list so it doesn't change on us, this is the scope for
795 ThreadList
&thread_list
= process_sp
->GetThreadList();
796 std::lock_guard
<std::recursive_mutex
> guard(thread_list
.GetMutex());
798 ThreadSP
curr_thread(thread_list
.GetSelectedThread());
800 StopReason curr_thread_stop_reason
= eStopReasonInvalid
;
801 bool prefer_curr_thread
= false;
802 if (curr_thread
&& curr_thread
->IsValid()) {
803 curr_thread_stop_reason
= curr_thread
->GetStopReason();
804 switch (curr_thread_stop_reason
) {
805 case eStopReasonNone
:
806 case eStopReasonInvalid
:
807 // Don't prefer the current thread if it didn't stop for a reason.
809 case eStopReasonSignal
: {
810 // We need to do the same computation we do for other threads
811 // below in case the current thread happens to be the one that
812 // stopped for the no-stop signal.
813 uint64_t signo
= curr_thread
->GetStopInfo()->GetValue();
814 if (process_sp
->GetUnixSignals()->GetShouldStop(signo
))
815 prefer_curr_thread
= true;
818 prefer_curr_thread
= true;
821 curr_thread_stop_info_sp
= curr_thread
->GetStopInfo();
824 if (!prefer_curr_thread
) {
825 // Prefer a thread that has just completed its plan over another
826 // thread as current thread.
827 ThreadSP plan_thread
;
828 ThreadSP other_thread
;
830 const size_t num_threads
= thread_list
.GetSize();
832 for (i
= 0; i
< num_threads
; ++i
) {
833 thread
= thread_list
.GetThreadAtIndex(i
);
834 StopReason thread_stop_reason
= thread
->GetStopReason();
835 switch (thread_stop_reason
) {
836 case eStopReasonInvalid
:
837 case eStopReasonNone
:
840 case eStopReasonSignal
: {
841 // Don't select a signal thread if we weren't going to stop at
842 // that signal. We have to have had another reason for stopping
843 // here, and the user doesn't want to see this thread.
844 uint64_t signo
= thread
->GetStopInfo()->GetValue();
845 if (process_sp
->GetUnixSignals()->GetShouldStop(signo
)) {
847 other_thread
= thread
;
851 case eStopReasonTrace
:
852 case eStopReasonBreakpoint
:
853 case eStopReasonWatchpoint
:
854 case eStopReasonException
:
855 case eStopReasonExec
:
856 case eStopReasonFork
:
857 case eStopReasonVFork
:
858 case eStopReasonVForkDone
:
859 case eStopReasonThreadExiting
:
860 case eStopReasonInstrumentation
:
861 case eStopReasonProcessorTrace
:
863 other_thread
= thread
;
865 case eStopReasonPlanComplete
:
867 plan_thread
= thread
;
872 thread_list
.SetSelectedThreadByID(plan_thread
->GetID());
873 else if (other_thread
)
874 thread_list
.SetSelectedThreadByID(other_thread
->GetID());
876 if (curr_thread
&& curr_thread
->IsValid())
877 thread
= curr_thread
;
879 thread
= thread_list
.GetThreadAtIndex(0);
882 thread_list
.SetSelectedThreadByID(thread
->GetID());
886 // Drop the ThreadList mutex by here, since GetThreadStatus below might
887 // have to run code, e.g. for Data formatters, and if we hold the
888 // ThreadList mutex, then the process is going to have a hard time
889 // restarting the process.
891 Debugger
&debugger
= process_sp
->GetTarget().GetDebugger();
892 if (debugger
.GetTargetList().GetSelectedTarget().get() ==
893 &process_sp
->GetTarget()) {
894 ThreadSP thread_sp
= process_sp
->GetThreadList().GetSelectedThread();
896 if (!thread_sp
|| !thread_sp
->IsValid())
899 const bool only_threads_with_stop_reason
= true;
900 const uint32_t start_frame
=
901 thread_sp
->GetSelectedFrameIndex(select_most_relevant
);
902 const uint32_t num_frames
= 1;
903 const uint32_t num_frames_with_source
= 1;
904 const bool stop_format
= true;
906 process_sp
->GetStatus(*stream
);
907 process_sp
->GetThreadStatus(*stream
, only_threads_with_stop_reason
,
908 start_frame
, num_frames
,
909 num_frames_with_source
,
911 if (curr_thread_stop_info_sp
) {
912 lldb::addr_t crashing_address
;
913 ValueObjectSP valobj_sp
= StopInfo::GetCrashingDereference(
914 curr_thread_stop_info_sp
, &crashing_address
);
916 const ValueObject::GetExpressionPathFormat format
=
917 ValueObject::GetExpressionPathFormat::
918 eGetExpressionPathFormatHonorPointers
;
919 stream
->PutCString("Likely cause: ");
920 valobj_sp
->GetExpressionPath(*stream
, format
);
921 stream
->Printf(" accessed 0x%" PRIx64
"\n", crashing_address
);
925 uint32_t target_idx
= debugger
.GetTargetList().GetIndexOfTarget(
926 process_sp
->GetTarget().shared_from_this());
927 if (target_idx
!= UINT32_MAX
)
928 stream
->Printf("Target %d: (", target_idx
);
930 stream
->Printf("Target <unknown index>: (");
931 process_sp
->GetTarget().Dump(stream
, eDescriptionLevelBrief
);
932 stream
->Printf(") stopped.\n");
936 // Pop the process IO handler
937 pop_process_io_handler
= true;
942 if (handle_pop
&& pop_process_io_handler
)
943 process_sp
->PopProcessIOHandler();
948 bool Process::HijackProcessEvents(ListenerSP listener_sp
) {
950 return HijackBroadcaster(listener_sp
, eBroadcastBitStateChanged
|
951 eBroadcastBitInterrupt
);
956 void Process::RestoreProcessEvents() { RestoreBroadcaster(); }
958 StateType
Process::GetStateChangedEvents(EventSP
&event_sp
,
959 const Timeout
<std::micro
> &timeout
,
960 ListenerSP hijack_listener_sp
) {
961 Log
*log
= GetLog(LLDBLog::Process
);
962 LLDB_LOG(log
, "timeout = {0}, event_sp)...", timeout
);
964 ListenerSP listener_sp
= hijack_listener_sp
;
966 listener_sp
= GetPrimaryListener();
968 StateType state
= eStateInvalid
;
969 if (listener_sp
->GetEventForBroadcasterWithType(
970 this, eBroadcastBitStateChanged
| eBroadcastBitInterrupt
, event_sp
,
972 if (event_sp
&& event_sp
->GetType() == eBroadcastBitStateChanged
)
973 state
= Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
975 LLDB_LOG(log
, "got no event or was interrupted.");
978 LLDB_LOG(log
, "timeout = {0}, event_sp) => {1}", timeout
, state
);
982 Event
*Process::PeekAtStateChangedEvents() {
983 Log
*log
= GetLog(LLDBLog::Process
);
985 LLDB_LOGF(log
, "Process::%s...", __FUNCTION__
);
988 event_ptr
= GetPrimaryListener()->PeekAtNextEventForBroadcasterWithType(
989 this, eBroadcastBitStateChanged
);
992 LLDB_LOGF(log
, "Process::%s (event_ptr) => %s", __FUNCTION__
,
993 StateAsCString(ProcessEventData::GetStateFromEvent(event_ptr
)));
995 LLDB_LOGF(log
, "Process::%s no events found", __FUNCTION__
);
1002 Process::GetStateChangedEventsPrivate(EventSP
&event_sp
,
1003 const Timeout
<std::micro
> &timeout
) {
1004 Log
*log
= GetLog(LLDBLog::Process
);
1005 LLDB_LOG(log
, "timeout = {0}, event_sp)...", timeout
);
1007 StateType state
= eStateInvalid
;
1008 if (m_private_state_listener_sp
->GetEventForBroadcasterWithType(
1009 &m_private_state_broadcaster
,
1010 eBroadcastBitStateChanged
| eBroadcastBitInterrupt
, event_sp
,
1012 if (event_sp
&& event_sp
->GetType() == eBroadcastBitStateChanged
)
1013 state
= Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
1015 LLDB_LOG(log
, "timeout = {0}, event_sp) => {1}", timeout
,
1016 state
== eStateInvalid
? "TIMEOUT" : StateAsCString(state
));
1020 bool Process::GetEventsPrivate(EventSP
&event_sp
,
1021 const Timeout
<std::micro
> &timeout
,
1022 bool control_only
) {
1023 Log
*log
= GetLog(LLDBLog::Process
);
1024 LLDB_LOG(log
, "timeout = {0}, event_sp)...", timeout
);
1027 return m_private_state_listener_sp
->GetEventForBroadcaster(
1028 &m_private_state_control_broadcaster
, event_sp
, timeout
);
1030 return m_private_state_listener_sp
->GetEvent(event_sp
, timeout
);
1033 bool Process::IsRunning() const {
1034 return StateIsRunningState(m_public_state
.GetValue());
1037 int Process::GetExitStatus() {
1038 std::lock_guard
<std::mutex
> guard(m_exit_status_mutex
);
1040 if (m_public_state
.GetValue() == eStateExited
)
1041 return m_exit_status
;
1045 const char *Process::GetExitDescription() {
1046 std::lock_guard
<std::mutex
> guard(m_exit_status_mutex
);
1048 if (m_public_state
.GetValue() == eStateExited
&& !m_exit_string
.empty())
1049 return m_exit_string
.c_str();
1053 bool Process::SetExitStatus(int status
, llvm::StringRef exit_string
) {
1054 // Use a mutex to protect setting the exit status.
1055 std::lock_guard
<std::mutex
> guard(m_exit_status_mutex
);
1057 Log
*log(GetLog(LLDBLog::State
| LLDBLog::Process
));
1058 LLDB_LOG(log
, "(plugin = {0} status = {1} ({1:x8}), description=\"{2}\")",
1059 GetPluginName(), status
, exit_string
);
1061 // We were already in the exited state
1062 if (m_private_state
.GetValue() == eStateExited
) {
1065 "(plugin = {0}) ignoring exit status because state was already set "
1071 m_exit_status
= status
;
1072 if (!exit_string
.empty())
1073 m_exit_string
= exit_string
.str();
1075 m_exit_string
.clear();
1077 // Clear the last natural stop ID since it has a strong reference to this
1079 m_mod_id
.SetStopEventForLastNaturalStopID(EventSP());
1081 SetPrivateState(eStateExited
);
1083 // Allow subclasses to do some cleanup
1089 bool Process::IsAlive() {
1090 switch (m_private_state
.GetValue()) {
1091 case eStateConnected
:
1092 case eStateAttaching
:
1093 case eStateLaunching
:
1096 case eStateStepping
:
1098 case eStateSuspended
:
1105 // This static callback can be used to watch for local child processes on the
1106 // current host. The child process exits, the process will be found in the
1107 // global target list (we want to be completely sure that the
1108 // lldb_private::Process doesn't go away before we can deliver the signal.
1109 bool Process::SetProcessExitStatus(
1110 lldb::pid_t pid
, bool exited
,
1111 int signo
, // Zero for no signal
1112 int exit_status
// Exit value of process if signal is zero
1114 Log
*log
= GetLog(LLDBLog::Process
);
1116 "Process::SetProcessExitStatus (pid=%" PRIu64
1117 ", exited=%i, signal=%i, exit_status=%i)\n",
1118 pid
, exited
, signo
, exit_status
);
1121 TargetSP
target_sp(Debugger::FindTargetWithProcessID(pid
));
1123 ProcessSP
process_sp(target_sp
->GetProcessSP());
1125 llvm::StringRef signal_str
=
1126 process_sp
->GetUnixSignals()->GetSignalAsStringRef(signo
);
1127 process_sp
->SetExitStatus(exit_status
, signal_str
);
1135 bool Process::UpdateThreadList(ThreadList
&old_thread_list
,
1136 ThreadList
&new_thread_list
) {
1137 m_thread_plans
.ClearThreadCache();
1138 return DoUpdateThreadList(old_thread_list
, new_thread_list
);
1141 void Process::UpdateThreadListIfNeeded() {
1142 const uint32_t stop_id
= GetStopID();
1143 if (m_thread_list
.GetSize(false) == 0 ||
1144 stop_id
!= m_thread_list
.GetStopID()) {
1145 bool clear_unused_threads
= true;
1146 const StateType state
= GetPrivateState();
1147 if (StateIsStoppedState(state
, true)) {
1148 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list
.GetMutex());
1149 m_thread_list
.SetStopID(stop_id
);
1151 // m_thread_list does have its own mutex, but we need to hold onto the
1152 // mutex between the call to UpdateThreadList(...) and the
1153 // os->UpdateThreadList(...) so it doesn't change on us
1154 ThreadList
&old_thread_list
= m_thread_list
;
1155 ThreadList
real_thread_list(this);
1156 ThreadList
new_thread_list(this);
1157 // Always update the thread list with the protocol specific thread list,
1158 // but only update if "true" is returned
1159 if (UpdateThreadList(m_thread_list_real
, real_thread_list
)) {
1160 // Don't call into the OperatingSystem to update the thread list if we
1161 // are shutting down, since that may call back into the SBAPI's,
1162 // requiring the API lock which is already held by whoever is shutting
1163 // us down, causing a deadlock.
1164 OperatingSystem
*os
= GetOperatingSystem();
1165 if (os
&& !m_destroy_in_process
) {
1166 // Clear any old backing threads where memory threads might have been
1167 // backed by actual threads from the lldb_private::Process subclass
1168 size_t num_old_threads
= old_thread_list
.GetSize(false);
1169 for (size_t i
= 0; i
< num_old_threads
; ++i
)
1170 old_thread_list
.GetThreadAtIndex(i
, false)->ClearBackingThread();
1171 // See if the OS plugin reports all threads. If it does, then
1172 // it is safe to clear unseen thread's plans here. Otherwise we
1173 // should preserve them in case they show up again:
1174 clear_unused_threads
= GetOSPluginReportsAllThreads();
1176 // Turn off dynamic types to ensure we don't run any expressions.
1177 // Objective-C can run an expression to determine if a SBValue is a
1178 // dynamic type or not and we need to avoid this. OperatingSystem
1179 // plug-ins can't run expressions that require running code...
1181 Target
&target
= GetTarget();
1182 const lldb::DynamicValueType saved_prefer_dynamic
=
1183 target
.GetPreferDynamicValue();
1184 if (saved_prefer_dynamic
!= lldb::eNoDynamicValues
)
1185 target
.SetPreferDynamicValue(lldb::eNoDynamicValues
);
1187 // Now let the OperatingSystem plug-in update the thread list
1189 os
->UpdateThreadList(
1190 old_thread_list
, // Old list full of threads created by OS plug-in
1191 real_thread_list
, // The actual thread list full of threads
1192 // created by each lldb_private::Process
1194 new_thread_list
); // The new thread list that we will show to the
1195 // user that gets filled in
1197 if (saved_prefer_dynamic
!= lldb::eNoDynamicValues
)
1198 target
.SetPreferDynamicValue(saved_prefer_dynamic
);
1200 // No OS plug-in, the new thread list is the same as the real thread
1202 new_thread_list
= real_thread_list
;
1205 m_thread_list_real
.Update(real_thread_list
);
1206 m_thread_list
.Update(new_thread_list
);
1207 m_thread_list
.SetStopID(stop_id
);
1209 if (GetLastNaturalStopID() != m_extended_thread_stop_id
) {
1210 // Clear any extended threads that we may have accumulated previously
1211 m_extended_thread_list
.Clear();
1212 m_extended_thread_stop_id
= GetLastNaturalStopID();
1214 m_queue_list
.Clear();
1215 m_queue_list_stop_id
= GetLastNaturalStopID();
1218 // Now update the plan stack map.
1219 // If we do have an OS plugin, any absent real threads in the
1220 // m_thread_list have already been removed from the ThreadPlanStackMap.
1221 // So any remaining threads are OS Plugin threads, and those we want to
1222 // preserve in case they show up again.
1223 m_thread_plans
.Update(m_thread_list
, clear_unused_threads
);
1228 ThreadPlanStack
*Process::FindThreadPlans(lldb::tid_t tid
) {
1229 return m_thread_plans
.Find(tid
);
1232 bool Process::PruneThreadPlansForTID(lldb::tid_t tid
) {
1233 return m_thread_plans
.PrunePlansForTID(tid
);
1236 void Process::PruneThreadPlans() {
1237 m_thread_plans
.Update(GetThreadList(), true, false);
1240 bool Process::DumpThreadPlansForTID(Stream
&strm
, lldb::tid_t tid
,
1241 lldb::DescriptionLevel desc_level
,
1242 bool internal
, bool condense_trivial
,
1243 bool skip_unreported_plans
) {
1244 return m_thread_plans
.DumpPlansForTID(
1245 strm
, tid
, desc_level
, internal
, condense_trivial
, skip_unreported_plans
);
1247 void Process::DumpThreadPlans(Stream
&strm
, lldb::DescriptionLevel desc_level
,
1248 bool internal
, bool condense_trivial
,
1249 bool skip_unreported_plans
) {
1250 m_thread_plans
.DumpPlans(strm
, desc_level
, internal
, condense_trivial
,
1251 skip_unreported_plans
);
1254 void Process::UpdateQueueListIfNeeded() {
1255 if (m_system_runtime_up
) {
1256 if (m_queue_list
.GetSize() == 0 ||
1257 m_queue_list_stop_id
!= GetLastNaturalStopID()) {
1258 const StateType state
= GetPrivateState();
1259 if (StateIsStoppedState(state
, true)) {
1260 m_system_runtime_up
->PopulateQueueList(m_queue_list
);
1261 m_queue_list_stop_id
= GetLastNaturalStopID();
1267 ThreadSP
Process::CreateOSPluginThread(lldb::tid_t tid
, lldb::addr_t context
) {
1268 OperatingSystem
*os
= GetOperatingSystem();
1270 return os
->CreateThread(tid
, context
);
1274 uint32_t Process::GetNextThreadIndexID(uint64_t thread_id
) {
1275 return AssignIndexIDToThread(thread_id
);
1278 bool Process::HasAssignedIndexIDToThread(uint64_t thread_id
) {
1279 return (m_thread_id_to_index_id_map
.find(thread_id
) !=
1280 m_thread_id_to_index_id_map
.end());
1283 uint32_t Process::AssignIndexIDToThread(uint64_t thread_id
) {
1284 uint32_t result
= 0;
1285 std::map
<uint64_t, uint32_t>::iterator iterator
=
1286 m_thread_id_to_index_id_map
.find(thread_id
);
1287 if (iterator
== m_thread_id_to_index_id_map
.end()) {
1288 result
= ++m_thread_index_id
;
1289 m_thread_id_to_index_id_map
[thread_id
] = result
;
1291 result
= iterator
->second
;
1297 StateType
Process::GetState() {
1298 if (CurrentThreadIsPrivateStateThread())
1299 return m_private_state
.GetValue();
1301 return m_public_state
.GetValue();
1304 void Process::SetPublicState(StateType new_state
, bool restarted
) {
1305 const bool new_state_is_stopped
= StateIsStoppedState(new_state
, false);
1306 if (new_state_is_stopped
) {
1307 // This will only set the time if the public stop time has no value, so
1308 // it is ok to call this multiple times. With a public stop we can't look
1309 // at the stop ID because many private stops might have happened, so we
1310 // can't check for a stop ID of zero. This allows the "statistics" command
1311 // to dump the time it takes to reach somewhere in your code, like a
1312 // breakpoint you set.
1313 GetTarget().GetStatistics().SetFirstPublicStopTime();
1316 Log
*log(GetLog(LLDBLog::State
| LLDBLog::Process
));
1317 LLDB_LOGF(log
, "(plugin = %s, state = %s, restarted = %i)",
1318 GetPluginName().data(), StateAsCString(new_state
), restarted
);
1319 const StateType old_state
= m_public_state
.GetValue();
1320 m_public_state
.SetValue(new_state
);
1322 // On the transition from Run to Stopped, we unlock the writer end of the run
1323 // lock. The lock gets locked in Resume, which is the public API to tell the
1325 if (!StateChangedIsExternallyHijacked()) {
1326 if (new_state
== eStateDetached
) {
1328 "(plugin = %s, state = %s) -- unlocking run lock for detach",
1329 GetPluginName().data(), StateAsCString(new_state
));
1330 m_public_run_lock
.SetStopped();
1332 const bool old_state_is_stopped
= StateIsStoppedState(old_state
, false);
1333 if ((old_state_is_stopped
!= new_state_is_stopped
)) {
1334 if (new_state_is_stopped
&& !restarted
) {
1335 LLDB_LOGF(log
, "(plugin = %s, state = %s) -- unlocking run lock",
1336 GetPluginName().data(), StateAsCString(new_state
));
1337 m_public_run_lock
.SetStopped();
1344 Status
Process::Resume() {
1345 Log
*log(GetLog(LLDBLog::State
| LLDBLog::Process
));
1346 LLDB_LOGF(log
, "(plugin = %s) -- locking run lock", GetPluginName().data());
1347 if (!m_public_run_lock
.TrySetRunning()) {
1348 Status
error("Resume request failed - process still running.");
1349 LLDB_LOGF(log
, "(plugin = %s) -- TrySetRunning failed, not resuming.",
1350 GetPluginName().data());
1353 Status error
= PrivateResume();
1354 if (!error
.Success()) {
1355 // Undo running state change
1356 m_public_run_lock
.SetStopped();
1361 Status
Process::ResumeSynchronous(Stream
*stream
) {
1362 Log
*log(GetLog(LLDBLog::State
| LLDBLog::Process
));
1363 LLDB_LOGF(log
, "Process::ResumeSynchronous -- locking run lock");
1364 if (!m_public_run_lock
.TrySetRunning()) {
1365 Status
error("Resume request failed - process still running.");
1366 LLDB_LOGF(log
, "Process::Resume: -- TrySetRunning failed, not resuming.");
1370 ListenerSP
listener_sp(
1371 Listener::MakeListener(ResumeSynchronousHijackListenerName
.data()));
1372 HijackProcessEvents(listener_sp
);
1374 Status error
= PrivateResume();
1375 if (error
.Success()) {
1377 WaitForProcessToStop(std::nullopt
, nullptr, true, listener_sp
, stream
,
1378 true /* use_run_lock */, SelectMostRelevantFrame
);
1379 const bool must_be_alive
=
1380 false; // eStateExited is ok, so this must be false
1381 if (!StateIsStoppedState(state
, must_be_alive
))
1382 error
.SetErrorStringWithFormat(
1383 "process not in stopped state after synchronous resume: %s",
1384 StateAsCString(state
));
1386 // Undo running state change
1387 m_public_run_lock
.SetStopped();
1390 // Undo the hijacking of process events...
1391 RestoreProcessEvents();
1396 bool Process::StateChangedIsExternallyHijacked() {
1397 if (IsHijackedForEvent(eBroadcastBitStateChanged
)) {
1398 llvm::StringRef hijacking_name
= GetHijackingListenerName();
1399 if (!hijacking_name
.starts_with("lldb.internal"))
1405 bool Process::StateChangedIsHijackedForSynchronousResume() {
1406 if (IsHijackedForEvent(eBroadcastBitStateChanged
)) {
1407 llvm::StringRef hijacking_name
= GetHijackingListenerName();
1408 if (hijacking_name
== ResumeSynchronousHijackListenerName
)
1414 StateType
Process::GetPrivateState() { return m_private_state
.GetValue(); }
1416 void Process::SetPrivateState(StateType new_state
) {
1420 Log
*log(GetLog(LLDBLog::State
| LLDBLog::Process
| LLDBLog::Unwind
));
1421 bool state_changed
= false;
1423 LLDB_LOGF(log
, "(plugin = %s, state = %s)", GetPluginName().data(),
1424 StateAsCString(new_state
));
1426 std::lock_guard
<std::recursive_mutex
> thread_guard(m_thread_list
.GetMutex());
1427 std::lock_guard
<std::recursive_mutex
> guard(m_private_state
.GetMutex());
1429 const StateType old_state
= m_private_state
.GetValueNoLock();
1430 state_changed
= old_state
!= new_state
;
1432 const bool old_state_is_stopped
= StateIsStoppedState(old_state
, false);
1433 const bool new_state_is_stopped
= StateIsStoppedState(new_state
, false);
1434 if (old_state_is_stopped
!= new_state_is_stopped
) {
1435 if (new_state_is_stopped
)
1436 m_private_run_lock
.SetStopped();
1438 m_private_run_lock
.SetRunning();
1441 if (state_changed
) {
1442 m_private_state
.SetValueNoLock(new_state
);
1444 new Event(eBroadcastBitStateChanged
,
1445 new ProcessEventData(shared_from_this(), new_state
)));
1446 if (StateIsStoppedState(new_state
, false)) {
1447 // Note, this currently assumes that all threads in the list stop when
1448 // the process stops. In the future we will want to support a debugging
1449 // model where some threads continue to run while others are stopped.
1450 // When that happens we will either need a way for the thread list to
1451 // identify which threads are stopping or create a special thread list
1452 // containing only threads which actually stopped.
1454 // The process plugin is responsible for managing the actual behavior of
1455 // the threads and should have stopped any threads that are going to stop
1456 // before we get here.
1457 m_thread_list
.DidStop();
1459 if (m_mod_id
.BumpStopID() == 0)
1460 GetTarget().GetStatistics().SetFirstPrivateStopTime();
1462 if (!m_mod_id
.IsLastResumeForUserExpression())
1463 m_mod_id
.SetStopEventForLastNaturalStopID(event_sp
);
1464 m_memory_cache
.Clear();
1465 LLDB_LOGF(log
, "(plugin = %s, state = %s, stop_id = %u",
1466 GetPluginName().data(), StateAsCString(new_state
),
1467 m_mod_id
.GetStopID());
1470 m_private_state_broadcaster
.BroadcastEvent(event_sp
);
1472 LLDB_LOGF(log
, "(plugin = %s, state = %s) state didn't change. Ignoring...",
1473 GetPluginName().data(), StateAsCString(new_state
));
1477 void Process::SetRunningUserExpression(bool on
) {
1478 m_mod_id
.SetRunningUserExpression(on
);
1481 void Process::SetRunningUtilityFunction(bool on
) {
1482 m_mod_id
.SetRunningUtilityFunction(on
);
1485 addr_t
Process::GetImageInfoAddress() { return LLDB_INVALID_ADDRESS
; }
1487 const lldb::ABISP
&Process::GetABI() {
1489 m_abi_sp
= ABI::FindPlugin(shared_from_this(), GetTarget().GetArchitecture());
1493 std::vector
<LanguageRuntime
*> Process::GetLanguageRuntimes() {
1494 std::vector
<LanguageRuntime
*> language_runtimes
;
1497 return language_runtimes
;
1499 std::lock_guard
<std::recursive_mutex
> guard(m_language_runtimes_mutex
);
1500 // Before we pass off a copy of the language runtimes, we must make sure that
1501 // our collection is properly populated. It's possible that some of the
1502 // language runtimes were not loaded yet, either because nobody requested it
1503 // yet or the proper condition for loading wasn't yet met (e.g. libc++.so
1504 // hadn't been loaded).
1505 for (const lldb::LanguageType lang_type
: Language::GetSupportedLanguages()) {
1506 if (LanguageRuntime
*runtime
= GetLanguageRuntime(lang_type
))
1507 language_runtimes
.emplace_back(runtime
);
1510 return language_runtimes
;
1513 LanguageRuntime
*Process::GetLanguageRuntime(lldb::LanguageType language
) {
1517 LanguageRuntime
*runtime
= nullptr;
1519 std::lock_guard
<std::recursive_mutex
> guard(m_language_runtimes_mutex
);
1520 LanguageRuntimeCollection::iterator pos
;
1521 pos
= m_language_runtimes
.find(language
);
1522 if (pos
== m_language_runtimes
.end() || !pos
->second
) {
1523 lldb::LanguageRuntimeSP
runtime_sp(
1524 LanguageRuntime::FindPlugin(this, language
));
1526 m_language_runtimes
[language
] = runtime_sp
;
1527 runtime
= runtime_sp
.get();
1529 runtime
= pos
->second
.get();
1532 // It's possible that a language runtime can support multiple LanguageTypes,
1533 // for example, CPPLanguageRuntime will support eLanguageTypeC_plus_plus,
1534 // eLanguageTypeC_plus_plus_03, etc. Because of this, we should get the
1535 // primary language type and make sure that our runtime supports it.
1536 assert(runtime
->GetLanguageType() == Language::GetPrimaryLanguage(language
));
1541 bool Process::IsPossibleDynamicValue(ValueObject
&in_value
) {
1545 if (in_value
.IsDynamic())
1547 LanguageType known_type
= in_value
.GetObjectRuntimeLanguage();
1549 if (known_type
!= eLanguageTypeUnknown
&& known_type
!= eLanguageTypeC
) {
1550 LanguageRuntime
*runtime
= GetLanguageRuntime(known_type
);
1551 return runtime
? runtime
->CouldHaveDynamicValue(in_value
) : false;
1554 for (LanguageRuntime
*runtime
: GetLanguageRuntimes()) {
1555 if (runtime
->CouldHaveDynamicValue(in_value
))
1562 void Process::SetDynamicCheckers(DynamicCheckerFunctions
*dynamic_checkers
) {
1563 m_dynamic_checkers_up
.reset(dynamic_checkers
);
1566 BreakpointSiteList
&Process::GetBreakpointSiteList() {
1567 return m_breakpoint_site_list
;
1570 const BreakpointSiteList
&Process::GetBreakpointSiteList() const {
1571 return m_breakpoint_site_list
;
1574 void Process::DisableAllBreakpointSites() {
1575 m_breakpoint_site_list
.ForEach([this](BreakpointSite
*bp_site
) -> void {
1576 // bp_site->SetEnabled(true);
1577 DisableBreakpointSite(bp_site
);
1581 Status
Process::ClearBreakpointSiteByID(lldb::user_id_t break_id
) {
1582 Status
error(DisableBreakpointSiteByID(break_id
));
1584 if (error
.Success())
1585 m_breakpoint_site_list
.Remove(break_id
);
1590 Status
Process::DisableBreakpointSiteByID(lldb::user_id_t break_id
) {
1592 BreakpointSiteSP bp_site_sp
= m_breakpoint_site_list
.FindByID(break_id
);
1594 if (bp_site_sp
->IsEnabled())
1595 error
= DisableBreakpointSite(bp_site_sp
.get());
1597 error
.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64
,
1604 Status
Process::EnableBreakpointSiteByID(lldb::user_id_t break_id
) {
1606 BreakpointSiteSP bp_site_sp
= m_breakpoint_site_list
.FindByID(break_id
);
1608 if (!bp_site_sp
->IsEnabled())
1609 error
= EnableBreakpointSite(bp_site_sp
.get());
1611 error
.SetErrorStringWithFormat("invalid breakpoint site ID: %" PRIu64
,
1618 Process::CreateBreakpointSite(const BreakpointLocationSP
&owner
,
1619 bool use_hardware
) {
1620 addr_t load_addr
= LLDB_INVALID_ADDRESS
;
1622 bool show_error
= true;
1623 switch (GetState()) {
1625 case eStateUnloaded
:
1626 case eStateConnected
:
1627 case eStateAttaching
:
1628 case eStateLaunching
:
1629 case eStateDetached
:
1636 case eStateStepping
:
1638 case eStateSuspended
:
1639 show_error
= IsAlive();
1643 // Reset the IsIndirect flag here, in case the location changes from pointing
1644 // to a indirect symbol to a regular symbol.
1645 owner
->SetIsIndirect(false);
1647 if (owner
->ShouldResolveIndirectFunctions()) {
1648 Symbol
*symbol
= owner
->GetAddress().CalculateSymbolContextSymbol();
1649 if (symbol
&& symbol
->IsIndirect()) {
1651 Address symbol_address
= symbol
->GetAddress();
1652 load_addr
= ResolveIndirectFunction(&symbol_address
, error
);
1653 if (!error
.Success() && show_error
) {
1654 GetTarget().GetDebugger().GetErrorStream().Printf(
1655 "warning: failed to resolve indirect function at 0x%" PRIx64
1656 " for breakpoint %i.%i: %s\n",
1657 symbol
->GetLoadAddress(&GetTarget()),
1658 owner
->GetBreakpoint().GetID(), owner
->GetID(),
1659 error
.AsCString() ? error
.AsCString() : "unknown error");
1660 return LLDB_INVALID_BREAK_ID
;
1662 Address
resolved_address(load_addr
);
1663 load_addr
= resolved_address
.GetOpcodeLoadAddress(&GetTarget());
1664 owner
->SetIsIndirect(true);
1666 load_addr
= owner
->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1668 load_addr
= owner
->GetAddress().GetOpcodeLoadAddress(&GetTarget());
1670 if (load_addr
!= LLDB_INVALID_ADDRESS
) {
1671 BreakpointSiteSP bp_site_sp
;
1673 // Look up this breakpoint site. If it exists, then add this new owner,
1674 // otherwise create a new breakpoint site and add it.
1676 bp_site_sp
= m_breakpoint_site_list
.FindByAddress(load_addr
);
1679 bp_site_sp
->AddOwner(owner
);
1680 owner
->SetBreakpointSite(bp_site_sp
);
1681 return bp_site_sp
->GetID();
1683 bp_site_sp
.reset(new BreakpointSite(&m_breakpoint_site_list
, owner
,
1684 load_addr
, use_hardware
));
1686 Status error
= EnableBreakpointSite(bp_site_sp
.get());
1687 if (error
.Success()) {
1688 owner
->SetBreakpointSite(bp_site_sp
);
1689 return m_breakpoint_site_list
.Add(bp_site_sp
);
1691 if (show_error
|| use_hardware
) {
1692 // Report error for setting breakpoint...
1693 GetTarget().GetDebugger().GetErrorStream().Printf(
1694 "warning: failed to set breakpoint site at 0x%" PRIx64
1695 " for breakpoint %i.%i: %s\n",
1696 load_addr
, owner
->GetBreakpoint().GetID(), owner
->GetID(),
1697 error
.AsCString() ? error
.AsCString() : "unknown error");
1703 // We failed to enable the breakpoint
1704 return LLDB_INVALID_BREAK_ID
;
1707 void Process::RemoveOwnerFromBreakpointSite(lldb::user_id_t owner_id
,
1708 lldb::user_id_t owner_loc_id
,
1709 BreakpointSiteSP
&bp_site_sp
) {
1710 uint32_t num_owners
= bp_site_sp
->RemoveOwner(owner_id
, owner_loc_id
);
1711 if (num_owners
== 0) {
1712 // Don't try to disable the site if we don't have a live process anymore.
1714 DisableBreakpointSite(bp_site_sp
.get());
1715 m_breakpoint_site_list
.RemoveByAddress(bp_site_sp
->GetLoadAddress());
1719 size_t Process::RemoveBreakpointOpcodesFromBuffer(addr_t bp_addr
, size_t size
,
1720 uint8_t *buf
) const {
1721 size_t bytes_removed
= 0;
1722 BreakpointSiteList bp_sites_in_range
;
1724 if (m_breakpoint_site_list
.FindInRange(bp_addr
, bp_addr
+ size
,
1725 bp_sites_in_range
)) {
1726 bp_sites_in_range
.ForEach([bp_addr
, size
,
1727 buf
](BreakpointSite
*bp_site
) -> void {
1728 if (bp_site
->GetType() == BreakpointSite::eSoftware
) {
1729 addr_t intersect_addr
;
1730 size_t intersect_size
;
1731 size_t opcode_offset
;
1732 if (bp_site
->IntersectsRange(bp_addr
, size
, &intersect_addr
,
1733 &intersect_size
, &opcode_offset
)) {
1734 assert(bp_addr
<= intersect_addr
&& intersect_addr
< bp_addr
+ size
);
1735 assert(bp_addr
< intersect_addr
+ intersect_size
&&
1736 intersect_addr
+ intersect_size
<= bp_addr
+ size
);
1737 assert(opcode_offset
+ intersect_size
<= bp_site
->GetByteSize());
1738 size_t buf_offset
= intersect_addr
- bp_addr
;
1739 ::memcpy(buf
+ buf_offset
,
1740 bp_site
->GetSavedOpcodeBytes() + opcode_offset
,
1746 return bytes_removed
;
1749 size_t Process::GetSoftwareBreakpointTrapOpcode(BreakpointSite
*bp_site
) {
1750 PlatformSP
platform_sp(GetTarget().GetPlatform());
1752 return platform_sp
->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site
);
1756 Status
Process::EnableSoftwareBreakpoint(BreakpointSite
*bp_site
) {
1758 assert(bp_site
!= nullptr);
1759 Log
*log
= GetLog(LLDBLog::Breakpoints
);
1760 const addr_t bp_addr
= bp_site
->GetLoadAddress();
1762 log
, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
,
1763 bp_site
->GetID(), (uint64_t)bp_addr
);
1764 if (bp_site
->IsEnabled()) {
1767 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1768 " -- already enabled",
1769 bp_site
->GetID(), (uint64_t)bp_addr
);
1773 if (bp_addr
== LLDB_INVALID_ADDRESS
) {
1774 error
.SetErrorString("BreakpointSite contains an invalid load address.");
1777 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1778 // trap for the breakpoint site
1779 const size_t bp_opcode_size
= GetSoftwareBreakpointTrapOpcode(bp_site
);
1781 if (bp_opcode_size
== 0) {
1782 error
.SetErrorStringWithFormat("Process::GetSoftwareBreakpointTrapOpcode() "
1783 "returned zero, unable to get breakpoint "
1784 "trap for address 0x%" PRIx64
,
1787 const uint8_t *const bp_opcode_bytes
= bp_site
->GetTrapOpcodeBytes();
1789 if (bp_opcode_bytes
== nullptr) {
1790 error
.SetErrorString(
1791 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1795 // Save the original opcode by reading it
1796 if (DoReadMemory(bp_addr
, bp_site
->GetSavedOpcodeBytes(), bp_opcode_size
,
1797 error
) == bp_opcode_size
) {
1798 // Write a software breakpoint in place of the original opcode
1799 if (DoWriteMemory(bp_addr
, bp_opcode_bytes
, bp_opcode_size
, error
) ==
1801 uint8_t verify_bp_opcode_bytes
[64];
1802 if (DoReadMemory(bp_addr
, verify_bp_opcode_bytes
, bp_opcode_size
,
1803 error
) == bp_opcode_size
) {
1804 if (::memcmp(bp_opcode_bytes
, verify_bp_opcode_bytes
,
1805 bp_opcode_size
) == 0) {
1806 bp_site
->SetEnabled(true);
1807 bp_site
->SetType(BreakpointSite::eSoftware
);
1809 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1810 "addr = 0x%" PRIx64
" -- SUCCESS",
1811 bp_site
->GetID(), (uint64_t)bp_addr
);
1813 error
.SetErrorString(
1814 "failed to verify the breakpoint trap in memory.");
1816 error
.SetErrorString(
1817 "Unable to read memory to verify breakpoint trap.");
1819 error
.SetErrorString("Unable to write breakpoint trap to memory.");
1821 error
.SetErrorString("Unable to read memory at breakpoint address.");
1823 if (log
&& error
.Fail())
1826 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1828 bp_site
->GetID(), (uint64_t)bp_addr
, error
.AsCString());
1832 Status
Process::DisableSoftwareBreakpoint(BreakpointSite
*bp_site
) {
1834 assert(bp_site
!= nullptr);
1835 Log
*log
= GetLog(LLDBLog::Breakpoints
);
1836 addr_t bp_addr
= bp_site
->GetLoadAddress();
1837 lldb::user_id_t breakID
= bp_site
->GetID();
1839 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1840 ") addr = 0x%" PRIx64
,
1841 breakID
, (uint64_t)bp_addr
);
1843 if (bp_site
->IsHardware()) {
1844 error
.SetErrorString("Breakpoint site is a hardware breakpoint.");
1845 } else if (bp_site
->IsEnabled()) {
1846 const size_t break_op_size
= bp_site
->GetByteSize();
1847 const uint8_t *const break_op
= bp_site
->GetTrapOpcodeBytes();
1848 if (break_op_size
> 0) {
1849 // Clear a software breakpoint instruction
1850 uint8_t curr_break_op
[8];
1851 assert(break_op_size
<= sizeof(curr_break_op
));
1852 bool break_op_found
= false;
1854 // Read the breakpoint opcode
1855 if (DoReadMemory(bp_addr
, curr_break_op
, break_op_size
, error
) ==
1857 bool verify
= false;
1858 // Make sure the breakpoint opcode exists at this address
1859 if (::memcmp(curr_break_op
, break_op
, break_op_size
) == 0) {
1860 break_op_found
= true;
1861 // We found a valid breakpoint opcode at this address, now restore
1862 // the saved opcode.
1863 if (DoWriteMemory(bp_addr
, bp_site
->GetSavedOpcodeBytes(),
1864 break_op_size
, error
) == break_op_size
) {
1867 error
.SetErrorString(
1868 "Memory write failed when restoring original opcode.");
1870 error
.SetErrorString(
1871 "Original breakpoint trap is no longer in memory.");
1872 // Set verify to true and so we can check if the original opcode has
1873 // already been restored
1878 uint8_t verify_opcode
[8];
1879 assert(break_op_size
< sizeof(verify_opcode
));
1880 // Verify that our original opcode made it back to the inferior
1881 if (DoReadMemory(bp_addr
, verify_opcode
, break_op_size
, error
) ==
1883 // compare the memory we just read with the original opcode
1884 if (::memcmp(bp_site
->GetSavedOpcodeBytes(), verify_opcode
,
1885 break_op_size
) == 0) {
1887 bp_site
->SetEnabled(false);
1889 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1890 "addr = 0x%" PRIx64
" -- SUCCESS",
1891 bp_site
->GetID(), (uint64_t)bp_addr
);
1895 error
.SetErrorString("Failed to restore original opcode.");
1898 error
.SetErrorString("Failed to read memory to verify that "
1899 "breakpoint trap was restored.");
1902 error
.SetErrorString(
1903 "Unable to read memory that should contain the breakpoint trap.");
1908 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1909 " -- already disabled",
1910 bp_site
->GetID(), (uint64_t)bp_addr
);
1916 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1918 bp_site
->GetID(), (uint64_t)bp_addr
, error
.AsCString());
1922 // Uncomment to verify memory caching works after making changes to caching
1924 //#define VERIFY_MEMORY_READS
1926 size_t Process::ReadMemory(addr_t addr
, void *buf
, size_t size
, Status
&error
) {
1927 if (ABISP abi_sp
= GetABI())
1928 addr
= abi_sp
->FixAnyAddress(addr
);
1931 if (!GetDisableMemoryCache()) {
1932 #if defined(VERIFY_MEMORY_READS)
1933 // Memory caching is enabled, with debug verification
1936 // Uncomment the line below to make sure memory caching is working.
1937 // I ran this through the test suite and got no assertions, so I am
1938 // pretty confident this is working well. If any changes are made to
1939 // memory caching, uncomment the line below and test your changes!
1941 // Verify all memory reads by using the cache first, then redundantly
1942 // reading the same memory from the inferior and comparing to make sure
1943 // everything is exactly the same.
1944 std::string
verify_buf(size
, '\0');
1945 assert(verify_buf
.size() == size
);
1946 const size_t cache_bytes_read
=
1947 m_memory_cache
.Read(this, addr
, buf
, size
, error
);
1948 Status verify_error
;
1949 const size_t verify_bytes_read
=
1950 ReadMemoryFromInferior(addr
, const_cast<char *>(verify_buf
.data()),
1951 verify_buf
.size(), verify_error
);
1952 assert(cache_bytes_read
== verify_bytes_read
);
1953 assert(memcmp(buf
, verify_buf
.data(), verify_buf
.size()) == 0);
1954 assert(verify_error
.Success() == error
.Success());
1955 return cache_bytes_read
;
1958 #else // !defined(VERIFY_MEMORY_READS)
1959 // Memory caching is enabled, without debug verification
1961 return m_memory_cache
.Read(addr
, buf
, size
, error
);
1962 #endif // defined (VERIFY_MEMORY_READS)
1964 // Memory caching is disabled
1966 return ReadMemoryFromInferior(addr
, buf
, size
, error
);
1970 size_t Process::ReadCStringFromMemory(addr_t addr
, std::string
&out_str
,
1974 addr_t curr_addr
= addr
;
1976 size_t length
= ReadCStringFromMemory(curr_addr
, buf
, sizeof(buf
), error
);
1979 out_str
.append(buf
, length
);
1980 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1981 // to read some more characters
1982 if (length
== sizeof(buf
) - 1)
1983 curr_addr
+= length
;
1987 return out_str
.size();
1990 // Deprecated in favor of ReadStringFromMemory which has wchar support and
1991 // correct code to find null terminators.
1992 size_t Process::ReadCStringFromMemory(addr_t addr
, char *dst
,
1994 Status
&result_error
) {
1995 size_t total_cstr_len
= 0;
1996 if (dst
&& dst_max_len
) {
1997 result_error
.Clear();
1998 // NULL out everything just to be safe
1999 memset(dst
, 0, dst_max_len
);
2001 addr_t curr_addr
= addr
;
2002 const size_t cache_line_size
= m_memory_cache
.GetMemoryCacheLineSize();
2003 size_t bytes_left
= dst_max_len
- 1;
2004 char *curr_dst
= dst
;
2006 while (bytes_left
> 0) {
2007 addr_t cache_line_bytes_left
=
2008 cache_line_size
- (curr_addr
% cache_line_size
);
2009 addr_t bytes_to_read
=
2010 std::min
<addr_t
>(bytes_left
, cache_line_bytes_left
);
2011 size_t bytes_read
= ReadMemory(curr_addr
, curr_dst
, bytes_to_read
, error
);
2013 if (bytes_read
== 0) {
2014 result_error
= error
;
2015 dst
[total_cstr_len
] = '\0';
2018 const size_t len
= strlen(curr_dst
);
2020 total_cstr_len
+= len
;
2022 if (len
< bytes_to_read
)
2025 curr_dst
+= bytes_read
;
2026 curr_addr
+= bytes_read
;
2027 bytes_left
-= bytes_read
;
2031 result_error
.SetErrorString("invalid arguments");
2033 result_error
.Clear();
2035 return total_cstr_len
;
2038 size_t Process::ReadMemoryFromInferior(addr_t addr
, void *buf
, size_t size
,
2040 LLDB_SCOPED_TIMER();
2042 if (ABISP abi_sp
= GetABI())
2043 addr
= abi_sp
->FixAnyAddress(addr
);
2045 if (buf
== nullptr || size
== 0)
2048 size_t bytes_read
= 0;
2049 uint8_t *bytes
= (uint8_t *)buf
;
2051 while (bytes_read
< size
) {
2052 const size_t curr_size
= size
- bytes_read
;
2053 const size_t curr_bytes_read
=
2054 DoReadMemory(addr
+ bytes_read
, bytes
+ bytes_read
, curr_size
, error
);
2055 bytes_read
+= curr_bytes_read
;
2056 if (curr_bytes_read
== curr_size
|| curr_bytes_read
== 0)
2060 // Replace any software breakpoint opcodes that fall into this range back
2061 // into "buf" before we return
2063 RemoveBreakpointOpcodesFromBuffer(addr
, bytes_read
, (uint8_t *)buf
);
2067 uint64_t Process::ReadUnsignedIntegerFromMemory(lldb::addr_t vm_addr
,
2068 size_t integer_byte_size
,
2069 uint64_t fail_value
,
2072 if (ReadScalarIntegerFromMemory(vm_addr
, integer_byte_size
, false, scalar
,
2074 return scalar
.ULongLong(fail_value
);
2078 int64_t Process::ReadSignedIntegerFromMemory(lldb::addr_t vm_addr
,
2079 size_t integer_byte_size
,
2083 if (ReadScalarIntegerFromMemory(vm_addr
, integer_byte_size
, true, scalar
,
2085 return scalar
.SLongLong(fail_value
);
2089 addr_t
Process::ReadPointerFromMemory(lldb::addr_t vm_addr
, Status
&error
) {
2091 if (ReadScalarIntegerFromMemory(vm_addr
, GetAddressByteSize(), false, scalar
,
2093 return scalar
.ULongLong(LLDB_INVALID_ADDRESS
);
2094 return LLDB_INVALID_ADDRESS
;
2097 bool Process::WritePointerToMemory(lldb::addr_t vm_addr
, lldb::addr_t ptr_value
,
2100 const uint32_t addr_byte_size
= GetAddressByteSize();
2101 if (addr_byte_size
<= 4)
2102 scalar
= (uint32_t)ptr_value
;
2105 return WriteScalarToMemory(vm_addr
, scalar
, addr_byte_size
, error
) ==
2109 size_t Process::WriteMemoryPrivate(addr_t addr
, const void *buf
, size_t size
,
2111 size_t bytes_written
= 0;
2112 const uint8_t *bytes
= (const uint8_t *)buf
;
2114 while (bytes_written
< size
) {
2115 const size_t curr_size
= size
- bytes_written
;
2116 const size_t curr_bytes_written
= DoWriteMemory(
2117 addr
+ bytes_written
, bytes
+ bytes_written
, curr_size
, error
);
2118 bytes_written
+= curr_bytes_written
;
2119 if (curr_bytes_written
== curr_size
|| curr_bytes_written
== 0)
2122 return bytes_written
;
2125 size_t Process::WriteMemory(addr_t addr
, const void *buf
, size_t size
,
2127 if (ABISP abi_sp
= GetABI())
2128 addr
= abi_sp
->FixAnyAddress(addr
);
2130 #if defined(ENABLE_MEMORY_CACHING)
2131 m_memory_cache
.Flush(addr
, size
);
2134 if (buf
== nullptr || size
== 0)
2137 m_mod_id
.BumpMemoryID();
2139 // We need to write any data that would go where any current software traps
2140 // (enabled software breakpoints) any software traps (breakpoints) that we
2141 // may have placed in our tasks memory.
2143 BreakpointSiteList bp_sites_in_range
;
2144 if (!m_breakpoint_site_list
.FindInRange(addr
, addr
+ size
, bp_sites_in_range
))
2145 return WriteMemoryPrivate(addr
, buf
, size
, error
);
2147 // No breakpoint sites overlap
2148 if (bp_sites_in_range
.IsEmpty())
2149 return WriteMemoryPrivate(addr
, buf
, size
, error
);
2151 const uint8_t *ubuf
= (const uint8_t *)buf
;
2152 uint64_t bytes_written
= 0;
2154 bp_sites_in_range
.ForEach([this, addr
, size
, &bytes_written
, &ubuf
,
2155 &error
](BreakpointSite
*bp
) -> void {
2159 if (bp
->GetType() != BreakpointSite::eSoftware
)
2162 addr_t intersect_addr
;
2163 size_t intersect_size
;
2164 size_t opcode_offset
;
2165 const bool intersects
= bp
->IntersectsRange(
2166 addr
, size
, &intersect_addr
, &intersect_size
, &opcode_offset
);
2167 UNUSED_IF_ASSERT_DISABLED(intersects
);
2169 assert(addr
<= intersect_addr
&& intersect_addr
< addr
+ size
);
2170 assert(addr
< intersect_addr
+ intersect_size
&&
2171 intersect_addr
+ intersect_size
<= addr
+ size
);
2172 assert(opcode_offset
+ intersect_size
<= bp
->GetByteSize());
2174 // Check for bytes before this breakpoint
2175 const addr_t curr_addr
= addr
+ bytes_written
;
2176 if (intersect_addr
> curr_addr
) {
2177 // There are some bytes before this breakpoint that we need to just
2179 size_t curr_size
= intersect_addr
- curr_addr
;
2180 size_t curr_bytes_written
=
2181 WriteMemoryPrivate(curr_addr
, ubuf
+ bytes_written
, curr_size
, error
);
2182 bytes_written
+= curr_bytes_written
;
2183 if (curr_bytes_written
!= curr_size
) {
2184 // We weren't able to write all of the requested bytes, we are
2185 // done looping and will return the number of bytes that we have
2187 if (error
.Success())
2188 error
.SetErrorToGenericError();
2191 // Now write any bytes that would cover up any software breakpoints
2192 // directly into the breakpoint opcode buffer
2193 ::memcpy(bp
->GetSavedOpcodeBytes() + opcode_offset
, ubuf
+ bytes_written
,
2195 bytes_written
+= intersect_size
;
2198 // Write any remaining bytes after the last breakpoint if we have any left
2199 if (bytes_written
< size
)
2201 WriteMemoryPrivate(addr
+ bytes_written
, ubuf
+ bytes_written
,
2202 size
- bytes_written
, error
);
2204 return bytes_written
;
2207 size_t Process::WriteScalarToMemory(addr_t addr
, const Scalar
&scalar
,
2208 size_t byte_size
, Status
&error
) {
2209 if (byte_size
== UINT32_MAX
)
2210 byte_size
= scalar
.GetByteSize();
2211 if (byte_size
> 0) {
2213 const size_t mem_size
=
2214 scalar
.GetAsMemoryData(buf
, byte_size
, GetByteOrder(), error
);
2216 return WriteMemory(addr
, buf
, mem_size
, error
);
2218 error
.SetErrorString("failed to get scalar as memory data");
2220 error
.SetErrorString("invalid scalar value");
2225 size_t Process::ReadScalarIntegerFromMemory(addr_t addr
, uint32_t byte_size
,
2226 bool is_signed
, Scalar
&scalar
,
2229 if (byte_size
== 0) {
2230 error
.SetErrorString("byte size is zero");
2231 } else if (byte_size
& (byte_size
- 1)) {
2232 error
.SetErrorStringWithFormat("byte size %u is not a power of 2",
2234 } else if (byte_size
<= sizeof(uval
)) {
2235 const size_t bytes_read
= ReadMemory(addr
, &uval
, byte_size
, error
);
2236 if (bytes_read
== byte_size
) {
2237 DataExtractor
data(&uval
, sizeof(uval
), GetByteOrder(),
2238 GetAddressByteSize());
2239 lldb::offset_t offset
= 0;
2241 scalar
= data
.GetMaxU32(&offset
, byte_size
);
2243 scalar
= data
.GetMaxU64(&offset
, byte_size
);
2245 scalar
.SignExtend(byte_size
* 8);
2249 error
.SetErrorStringWithFormat(
2250 "byte size of %u is too large for integer scalar type", byte_size
);
2255 Status
Process::WriteObjectFile(std::vector
<ObjectFile::LoadableData
> entries
) {
2257 for (const auto &Entry
: entries
) {
2258 WriteMemory(Entry
.Dest
, Entry
.Contents
.data(), Entry
.Contents
.size(),
2260 if (!error
.Success())
2266 #define USE_ALLOCATE_MEMORY_CACHE 1
2267 addr_t
Process::AllocateMemory(size_t size
, uint32_t permissions
,
2269 if (GetPrivateState() != eStateStopped
) {
2270 error
.SetErrorToGenericError();
2271 return LLDB_INVALID_ADDRESS
;
2274 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2275 return m_allocated_memory_cache
.AllocateMemory(size
, permissions
, error
);
2277 addr_t allocated_addr
= DoAllocateMemory(size
, permissions
, error
);
2278 Log
*log
= GetLog(LLDBLog::Process
);
2280 "Process::AllocateMemory(size=%" PRIu64
2281 ", permissions=%s) => 0x%16.16" PRIx64
2282 " (m_stop_id = %u m_memory_id = %u)",
2283 (uint64_t)size
, GetPermissionsAsCString(permissions
),
2284 (uint64_t)allocated_addr
, m_mod_id
.GetStopID(),
2285 m_mod_id
.GetMemoryID());
2286 return allocated_addr
;
2290 addr_t
Process::CallocateMemory(size_t size
, uint32_t permissions
,
2292 addr_t return_addr
= AllocateMemory(size
, permissions
, error
);
2293 if (error
.Success()) {
2294 std::string
buffer(size
, 0);
2295 WriteMemory(return_addr
, buffer
.c_str(), size
, error
);
2300 bool Process::CanJIT() {
2301 if (m_can_jit
== eCanJITDontKnow
) {
2302 Log
*log
= GetLog(LLDBLog::Process
);
2305 uint64_t allocated_memory
= AllocateMemory(
2306 8, ePermissionsReadable
| ePermissionsWritable
| ePermissionsExecutable
,
2309 if (err
.Success()) {
2310 m_can_jit
= eCanJITYes
;
2312 "Process::%s pid %" PRIu64
2313 " allocation test passed, CanJIT () is true",
2314 __FUNCTION__
, GetID());
2316 m_can_jit
= eCanJITNo
;
2318 "Process::%s pid %" PRIu64
2319 " allocation test failed, CanJIT () is false: %s",
2320 __FUNCTION__
, GetID(), err
.AsCString());
2323 DeallocateMemory(allocated_memory
);
2326 return m_can_jit
== eCanJITYes
;
2329 void Process::SetCanJIT(bool can_jit
) {
2330 m_can_jit
= (can_jit
? eCanJITYes
: eCanJITNo
);
2333 void Process::SetCanRunCode(bool can_run_code
) {
2334 SetCanJIT(can_run_code
);
2335 m_can_interpret_function_calls
= can_run_code
;
2338 Status
Process::DeallocateMemory(addr_t ptr
) {
2340 #if defined(USE_ALLOCATE_MEMORY_CACHE)
2341 if (!m_allocated_memory_cache
.DeallocateMemory(ptr
)) {
2342 error
.SetErrorStringWithFormat(
2343 "deallocation of memory at 0x%" PRIx64
" failed.", (uint64_t)ptr
);
2346 error
= DoDeallocateMemory(ptr
);
2348 Log
*log
= GetLog(LLDBLog::Process
);
2350 "Process::DeallocateMemory(addr=0x%16.16" PRIx64
2351 ") => err = %s (m_stop_id = %u, m_memory_id = %u)",
2352 ptr
, error
.AsCString("SUCCESS"), m_mod_id
.GetStopID(),
2353 m_mod_id
.GetMemoryID());
2358 bool Process::GetWatchpointReportedAfter() {
2359 if (std::optional
<bool> subclass_override
= DoGetWatchpointReportedAfter())
2360 return *subclass_override
;
2362 bool reported_after
= true;
2363 const ArchSpec
&arch
= GetTarget().GetArchitecture();
2364 if (!arch
.IsValid())
2365 return reported_after
;
2366 llvm::Triple triple
= arch
.GetTriple();
2368 if (triple
.isMIPS() || triple
.isPPC64() || triple
.isRISCV() ||
2369 triple
.isAArch64() || triple
.isArmMClass() || triple
.isARM())
2370 reported_after
= false;
2372 return reported_after
;
2375 ModuleSP
Process::ReadModuleFromMemory(const FileSpec
&file_spec
,
2376 lldb::addr_t header_addr
,
2377 size_t size_to_read
) {
2378 Log
*log
= GetLog(LLDBLog::Host
);
2381 "Process::ReadModuleFromMemory reading %s binary from memory",
2382 file_spec
.GetPath().c_str());
2384 ModuleSP
module_sp(new Module(file_spec
, ArchSpec()));
2387 ObjectFile
*objfile
= module_sp
->GetMemoryObjectFile(
2388 shared_from_this(), header_addr
, error
, size_to_read
);
2395 bool Process::GetLoadAddressPermissions(lldb::addr_t load_addr
,
2396 uint32_t &permissions
) {
2397 MemoryRegionInfo range_info
;
2399 Status
error(GetMemoryRegionInfo(load_addr
, range_info
));
2400 if (!error
.Success())
2402 if (range_info
.GetReadable() == MemoryRegionInfo::eDontKnow
||
2403 range_info
.GetWritable() == MemoryRegionInfo::eDontKnow
||
2404 range_info
.GetExecutable() == MemoryRegionInfo::eDontKnow
) {
2408 if (range_info
.GetReadable() == MemoryRegionInfo::eYes
)
2409 permissions
|= lldb::ePermissionsReadable
;
2411 if (range_info
.GetWritable() == MemoryRegionInfo::eYes
)
2412 permissions
|= lldb::ePermissionsWritable
;
2414 if (range_info
.GetExecutable() == MemoryRegionInfo::eYes
)
2415 permissions
|= lldb::ePermissionsExecutable
;
2420 Status
Process::EnableWatchpoint(Watchpoint
*watchpoint
, bool notify
) {
2422 error
.SetErrorString("watchpoints are not supported");
2426 Status
Process::DisableWatchpoint(Watchpoint
*watchpoint
, bool notify
) {
2428 error
.SetErrorString("watchpoints are not supported");
2433 Process::WaitForProcessStopPrivate(EventSP
&event_sp
,
2434 const Timeout
<std::micro
> &timeout
) {
2439 state
= GetStateChangedEventsPrivate(event_sp
, timeout
);
2441 if (StateIsStoppedState(state
, false))
2444 // If state is invalid, then we timed out
2445 if (state
== eStateInvalid
)
2449 HandlePrivateEvent(event_sp
);
2454 void Process::LoadOperatingSystemPlugin(bool flush
) {
2455 std::lock_guard
<std::recursive_mutex
> guard(m_thread_mutex
);
2457 m_thread_list
.Clear();
2458 m_os_up
.reset(OperatingSystem::FindPlugin(this, nullptr));
2463 Status
Process::Launch(ProcessLaunchInfo
&launch_info
) {
2464 StateType state_after_launch
= eStateInvalid
;
2465 EventSP first_stop_event_sp
;
2467 LaunchPrivate(launch_info
, state_after_launch
, first_stop_event_sp
);
2471 if (state_after_launch
!= eStateStopped
&&
2472 state_after_launch
!= eStateCrashed
)
2475 // Note, the stop event was consumed above, but not handled. This
2476 // was done to give DidLaunch a chance to run. The target is either
2477 // stopped or crashed. Directly set the state. This is done to
2478 // prevent a stop message with a bunch of spurious output on thread
2479 // status, as well as not pop a ProcessIOHandler.
2480 SetPublicState(state_after_launch
, false);
2482 if (PrivateStateThreadIsValid())
2483 ResumePrivateStateThread();
2485 StartPrivateStateThread();
2487 // Target was stopped at entry as was intended. Need to notify the
2488 // listeners about it.
2489 if (launch_info
.GetFlags().Test(eLaunchFlagStopAtEntry
))
2490 HandlePrivateEvent(first_stop_event_sp
);
2495 Status
Process::LaunchPrivate(ProcessLaunchInfo
&launch_info
, StateType
&state
,
2496 EventSP
&event_sp
) {
2500 m_jit_loaders_up
.reset();
2501 m_system_runtime_up
.reset();
2505 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
2506 m_process_input_reader
.reset();
2509 Module
*exe_module
= GetTarget().GetExecutableModulePointer();
2511 // The "remote executable path" is hooked up to the local Executable
2512 // module. But we should be able to debug a remote process even if the
2513 // executable module only exists on the remote. However, there needs to
2514 // be a way to express this path, without actually having a module.
2515 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2516 // Figure that out here:
2518 FileSpec exe_spec_to_use
;
2520 if (!launch_info
.GetExecutableFile() && !launch_info
.IsScriptedProcess()) {
2521 error
.SetErrorString("executable module does not exist");
2524 exe_spec_to_use
= launch_info
.GetExecutableFile();
2526 exe_spec_to_use
= exe_module
->GetFileSpec();
2528 if (exe_module
&& FileSystem::Instance().Exists(exe_module
->GetFileSpec())) {
2529 // Install anything that might need to be installed prior to launching.
2530 // For host systems, this will do nothing, but if we are connected to a
2531 // remote platform it will install any needed binaries
2532 error
= GetTarget().Install(&launch_info
);
2537 // Listen and queue events that are broadcasted during the process launch.
2538 ListenerSP
listener_sp(Listener::MakeListener("LaunchEventHijack"));
2539 HijackProcessEvents(listener_sp
);
2540 auto on_exit
= llvm::make_scope_exit([this]() { RestoreProcessEvents(); });
2542 if (PrivateStateThreadIsValid())
2543 PausePrivateStateThread();
2545 error
= WillLaunch(exe_module
);
2547 std::string local_exec_file_path
= exe_spec_to_use
.GetPath();
2548 return Status("file doesn't exist: '%s'", local_exec_file_path
.c_str());
2551 const bool restarted
= false;
2552 SetPublicState(eStateLaunching
, restarted
);
2553 m_should_detach
= false;
2555 if (m_public_run_lock
.TrySetRunning()) {
2556 // Now launch using these arguments.
2557 error
= DoLaunch(exe_module
, launch_info
);
2559 // This shouldn't happen
2560 error
.SetErrorString("failed to acquire process run lock");
2564 if (GetID() != LLDB_INVALID_PROCESS_ID
) {
2565 SetID(LLDB_INVALID_PROCESS_ID
);
2566 const char *error_string
= error
.AsCString();
2567 if (error_string
== nullptr)
2568 error_string
= "launch failed";
2569 SetExitStatus(-1, error_string
);
2574 // Now wait for the process to launch and return control to us, and then
2576 state
= WaitForProcessStopPrivate(event_sp
, seconds(10));
2578 if (state
== eStateInvalid
|| !event_sp
) {
2579 // We were able to launch the process, but we failed to catch the
2581 error
.SetErrorString("failed to catch stop after launch");
2582 SetExitStatus(0, error
.AsCString());
2587 if (state
== eStateExited
) {
2588 // We exited while trying to launch somehow. Don't call DidLaunch
2589 // as that's not likely to work, and return an invalid pid.
2590 HandlePrivateEvent(event_sp
);
2594 if (state
== eStateStopped
|| state
== eStateCrashed
) {
2597 // Now that we know the process type, update its signal responses from the
2598 // ones stored in the Target:
2599 if (m_unix_signals_sp
) {
2600 StreamSP warning_strm
= GetTarget().GetDebugger().GetAsyncErrorStream();
2601 GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp
, warning_strm
);
2604 DynamicLoader
*dyld
= GetDynamicLoader();
2608 GetJITLoaders().DidLaunch();
2610 SystemRuntime
*system_runtime
= GetSystemRuntime();
2612 system_runtime
->DidLaunch();
2615 LoadOperatingSystemPlugin(false);
2617 // We successfully launched the process and stopped, now it the
2618 // right time to set up signal filters before resuming.
2619 UpdateAutomaticSignalFiltering();
2623 return Status("Unexpected process state after the launch: %s, expected %s, "
2625 StateAsCString(state
), StateAsCString(eStateInvalid
),
2626 StateAsCString(eStateExited
), StateAsCString(eStateStopped
),
2627 StateAsCString(eStateCrashed
));
2630 Status
Process::LoadCore() {
2631 Status error
= DoLoadCore();
2632 if (error
.Success()) {
2633 ListenerSP
listener_sp(
2634 Listener::MakeListener("lldb.process.load_core_listener"));
2635 HijackProcessEvents(listener_sp
);
2637 if (PrivateStateThreadIsValid())
2638 ResumePrivateStateThread();
2640 StartPrivateStateThread();
2642 DynamicLoader
*dyld
= GetDynamicLoader();
2646 GetJITLoaders().DidAttach();
2648 SystemRuntime
*system_runtime
= GetSystemRuntime();
2650 system_runtime
->DidAttach();
2653 LoadOperatingSystemPlugin(false);
2655 // We successfully loaded a core file, now pretend we stopped so we can
2656 // show all of the threads in the core file and explore the crashed state.
2657 SetPrivateState(eStateStopped
);
2659 // Wait for a stopped event since we just posted one above...
2660 lldb::EventSP event_sp
;
2662 WaitForProcessToStop(std::nullopt
, &event_sp
, true, listener_sp
,
2663 nullptr, true, SelectMostRelevantFrame
);
2665 if (!StateIsStoppedState(state
, false)) {
2666 Log
*log
= GetLog(LLDBLog::Process
);
2667 LLDB_LOGF(log
, "Process::Halt() failed to stop, state is: %s",
2668 StateAsCString(state
));
2669 error
.SetErrorString(
2670 "Did not get stopped event after loading the core file.");
2672 RestoreProcessEvents();
2677 DynamicLoader
*Process::GetDynamicLoader() {
2679 m_dyld_up
.reset(DynamicLoader::FindPlugin(this, ""));
2680 return m_dyld_up
.get();
2683 void Process::SetDynamicLoader(DynamicLoaderUP dyld_up
) {
2684 m_dyld_up
= std::move(dyld_up
);
2687 DataExtractor
Process::GetAuxvData() { return DataExtractor(); }
2689 llvm::Expected
<bool> Process::SaveCore(llvm::StringRef outfile
) {
2693 JITLoaderList
&Process::GetJITLoaders() {
2694 if (!m_jit_loaders_up
) {
2695 m_jit_loaders_up
= std::make_unique
<JITLoaderList
>();
2696 JITLoader::LoadPlugins(this, *m_jit_loaders_up
);
2698 return *m_jit_loaders_up
;
2701 SystemRuntime
*Process::GetSystemRuntime() {
2702 if (!m_system_runtime_up
)
2703 m_system_runtime_up
.reset(SystemRuntime::FindPlugin(this));
2704 return m_system_runtime_up
.get();
2707 Process::AttachCompletionHandler::AttachCompletionHandler(Process
*process
,
2708 uint32_t exec_count
)
2709 : NextEventAction(process
), m_exec_count(exec_count
) {
2710 Log
*log
= GetLog(LLDBLog::Process
);
2713 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32
,
2714 __FUNCTION__
, static_cast<void *>(process
), exec_count
);
2717 Process::NextEventAction::EventActionResult
2718 Process::AttachCompletionHandler::PerformAction(lldb::EventSP
&event_sp
) {
2719 Log
*log
= GetLog(LLDBLog::Process
);
2721 StateType state
= ProcessEventData::GetStateFromEvent(event_sp
.get());
2723 "Process::AttachCompletionHandler::%s called with state %s (%d)",
2724 __FUNCTION__
, StateAsCString(state
), static_cast<int>(state
));
2727 case eStateAttaching
:
2728 return eEventActionSuccess
;
2731 case eStateConnected
:
2732 return eEventActionRetry
;
2736 // During attach, prior to sending the eStateStopped event,
2737 // lldb_private::Process subclasses must set the new process ID.
2738 assert(m_process
->GetID() != LLDB_INVALID_PROCESS_ID
);
2739 // We don't want these events to be reported, so go set the
2740 // ShouldReportStop here:
2741 m_process
->GetThreadList().SetShouldReportStop(eVoteNo
);
2743 if (m_exec_count
> 0) {
2747 "Process::AttachCompletionHandler::%s state %s: reduced "
2748 "remaining exec count to %" PRIu32
", requesting resume",
2749 __FUNCTION__
, StateAsCString(state
), m_exec_count
);
2752 return eEventActionRetry
;
2755 "Process::AttachCompletionHandler::%s state %s: no more "
2756 "execs expected to start, continuing with attach",
2757 __FUNCTION__
, StateAsCString(state
));
2759 m_process
->CompleteAttach();
2760 return eEventActionSuccess
;
2770 m_exit_string
.assign("No valid Process");
2771 return eEventActionExit
;
2774 Process::NextEventAction::EventActionResult
2775 Process::AttachCompletionHandler::HandleBeingInterrupted() {
2776 return eEventActionSuccess
;
2779 const char *Process::AttachCompletionHandler::GetExitString() {
2780 return m_exit_string
.c_str();
2783 ListenerSP
ProcessAttachInfo::GetListenerForProcess(Debugger
&debugger
) {
2785 return m_listener_sp
;
2787 return debugger
.GetListener();
2790 Status
Process::WillLaunch(Module
*module
) {
2791 return DoWillLaunch(module
);
2794 Status
Process::WillAttachToProcessWithID(lldb::pid_t pid
) {
2795 return DoWillAttachToProcessWithID(pid
);
2798 Status
Process::WillAttachToProcessWithName(const char *process_name
,
2799 bool wait_for_launch
) {
2800 return DoWillAttachToProcessWithName(process_name
, wait_for_launch
);
2803 Status
Process::Attach(ProcessAttachInfo
&attach_info
) {
2806 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
2807 m_process_input_reader
.reset();
2810 m_jit_loaders_up
.reset();
2811 m_system_runtime_up
.reset();
2814 lldb::pid_t attach_pid
= attach_info
.GetProcessID();
2816 if (attach_pid
== LLDB_INVALID_PROCESS_ID
) {
2817 char process_name
[PATH_MAX
];
2819 if (attach_info
.GetExecutableFile().GetPath(process_name
,
2820 sizeof(process_name
))) {
2821 const bool wait_for_launch
= attach_info
.GetWaitForLaunch();
2823 if (wait_for_launch
) {
2824 error
= WillAttachToProcessWithName(process_name
, wait_for_launch
);
2825 if (error
.Success()) {
2826 if (m_public_run_lock
.TrySetRunning()) {
2827 m_should_detach
= true;
2828 const bool restarted
= false;
2829 SetPublicState(eStateAttaching
, restarted
);
2830 // Now attach using these arguments.
2831 error
= DoAttachToProcessWithName(process_name
, attach_info
);
2833 // This shouldn't happen
2834 error
.SetErrorString("failed to acquire process run lock");
2838 if (GetID() != LLDB_INVALID_PROCESS_ID
) {
2839 SetID(LLDB_INVALID_PROCESS_ID
);
2840 if (error
.AsCString() == nullptr)
2841 error
.SetErrorString("attach failed");
2843 SetExitStatus(-1, error
.AsCString());
2846 SetNextEventAction(new Process::AttachCompletionHandler(
2847 this, attach_info
.GetResumeCount()));
2848 StartPrivateStateThread();
2853 ProcessInstanceInfoList process_infos
;
2854 PlatformSP
platform_sp(GetTarget().GetPlatform());
2857 ProcessInstanceInfoMatch match_info
;
2858 match_info
.GetProcessInfo() = attach_info
;
2859 match_info
.SetNameMatchType(NameMatch::Equals
);
2860 platform_sp
->FindProcesses(match_info
, process_infos
);
2861 const uint32_t num_matches
= process_infos
.size();
2862 if (num_matches
== 1) {
2863 attach_pid
= process_infos
[0].GetProcessID();
2864 // Fall through and attach using the above process ID
2866 match_info
.GetProcessInfo().GetExecutableFile().GetPath(
2867 process_name
, sizeof(process_name
));
2868 if (num_matches
> 1) {
2870 ProcessInstanceInfo::DumpTableHeader(s
, true, false);
2871 for (size_t i
= 0; i
< num_matches
; i
++) {
2872 process_infos
[i
].DumpAsTableRow(
2873 s
, platform_sp
->GetUserIDResolver(), true, false);
2875 error
.SetErrorStringWithFormat(
2876 "more than one process named %s:\n%s", process_name
,
2879 error
.SetErrorStringWithFormat(
2880 "could not find a process named %s", process_name
);
2883 error
.SetErrorString(
2884 "invalid platform, can't find processes by name");
2889 error
.SetErrorString("invalid process name");
2893 if (attach_pid
!= LLDB_INVALID_PROCESS_ID
) {
2894 error
= WillAttachToProcessWithID(attach_pid
);
2895 if (error
.Success()) {
2897 if (m_public_run_lock
.TrySetRunning()) {
2898 // Now attach using these arguments.
2899 m_should_detach
= true;
2900 const bool restarted
= false;
2901 SetPublicState(eStateAttaching
, restarted
);
2902 error
= DoAttachToProcessWithID(attach_pid
, attach_info
);
2904 // This shouldn't happen
2905 error
.SetErrorString("failed to acquire process run lock");
2908 if (error
.Success()) {
2909 SetNextEventAction(new Process::AttachCompletionHandler(
2910 this, attach_info
.GetResumeCount()));
2911 StartPrivateStateThread();
2913 if (GetID() != LLDB_INVALID_PROCESS_ID
)
2914 SetID(LLDB_INVALID_PROCESS_ID
);
2916 const char *error_string
= error
.AsCString();
2917 if (error_string
== nullptr)
2918 error_string
= "attach failed";
2920 SetExitStatus(-1, error_string
);
2927 void Process::CompleteAttach() {
2928 Log
*log(GetLog(LLDBLog::Process
| LLDBLog::Target
));
2929 LLDB_LOGF(log
, "Process::%s()", __FUNCTION__
);
2931 // Let the process subclass figure out at much as it can about the process
2932 // before we go looking for a dynamic loader plug-in.
2933 ArchSpec process_arch
;
2934 DidAttach(process_arch
);
2936 if (process_arch
.IsValid()) {
2937 GetTarget().SetArchitecture(process_arch
);
2939 const char *triple_str
= process_arch
.GetTriple().getTriple().c_str();
2941 "Process::%s replacing process architecture with DidAttach() "
2943 __FUNCTION__
, triple_str
? triple_str
: "<null>");
2947 // We just attached. If we have a platform, ask it for the process
2948 // architecture, and if it isn't the same as the one we've already set,
2949 // switch architectures.
2950 PlatformSP
platform_sp(GetTarget().GetPlatform());
2951 assert(platform_sp
);
2952 ArchSpec process_host_arch
= GetSystemArchitecture();
2954 const ArchSpec
&target_arch
= GetTarget().GetArchitecture();
2955 if (target_arch
.IsValid() && !platform_sp
->IsCompatibleArchitecture(
2956 target_arch
, process_host_arch
,
2957 ArchSpec::CompatibleMatch
, nullptr)) {
2958 ArchSpec platform_arch
;
2959 platform_sp
= GetTarget().GetDebugger().GetPlatformList().GetOrCreate(
2960 target_arch
, process_host_arch
, &platform_arch
);
2962 GetTarget().SetPlatform(platform_sp
);
2963 GetTarget().SetArchitecture(platform_arch
);
2965 "switching platform to {0} and architecture to {1} based on "
2967 platform_sp
->GetName(), platform_arch
.GetTriple().getTriple());
2969 } else if (!process_arch
.IsValid()) {
2970 ProcessInstanceInfo process_info
;
2971 GetProcessInfo(process_info
);
2972 const ArchSpec
&process_arch
= process_info
.GetArchitecture();
2973 const ArchSpec
&target_arch
= GetTarget().GetArchitecture();
2974 if (process_arch
.IsValid() &&
2975 target_arch
.IsCompatibleMatch(process_arch
) &&
2976 !target_arch
.IsExactMatch(process_arch
)) {
2977 GetTarget().SetArchitecture(process_arch
);
2979 "Process::%s switching architecture to %s based on info "
2980 "the platform retrieved for pid %" PRIu64
,
2981 __FUNCTION__
, process_arch
.GetTriple().getTriple().c_str(),
2986 // Now that we know the process type, update its signal responses from the
2987 // ones stored in the Target:
2988 if (m_unix_signals_sp
) {
2989 StreamSP warning_strm
= GetTarget().GetDebugger().GetAsyncErrorStream();
2990 GetTarget().UpdateSignalsFromDummy(m_unix_signals_sp
, warning_strm
);
2993 // We have completed the attach, now it is time to find the dynamic loader
2995 DynamicLoader
*dyld
= GetDynamicLoader();
2999 ModuleSP exe_module_sp
= GetTarget().GetExecutableModule();
3001 "after DynamicLoader::DidAttach(), target "
3002 "executable is {0} (using {1} plugin)",
3003 exe_module_sp
? exe_module_sp
->GetFileSpec() : FileSpec(),
3004 dyld
->GetPluginName());
3008 GetJITLoaders().DidAttach();
3010 SystemRuntime
*system_runtime
= GetSystemRuntime();
3011 if (system_runtime
) {
3012 system_runtime
->DidAttach();
3014 ModuleSP exe_module_sp
= GetTarget().GetExecutableModule();
3016 "after SystemRuntime::DidAttach(), target "
3017 "executable is {0} (using {1} plugin)",
3018 exe_module_sp
? exe_module_sp
->GetFileSpec() : FileSpec(),
3019 system_runtime
->GetPluginName());
3024 LoadOperatingSystemPlugin(false);
3026 // Somebody might have gotten threads before now, but we need to force the
3027 // update after we've loaded the OperatingSystem plugin or it won't get a
3028 // chance to process the threads.
3029 m_thread_list
.Clear();
3030 UpdateThreadListIfNeeded();
3033 // Figure out which one is the executable, and set that in our target:
3034 ModuleSP new_executable_module_sp
;
3035 for (ModuleSP module_sp
: GetTarget().GetImages().Modules()) {
3036 if (module_sp
&& module_sp
->IsExecutable()) {
3037 if (GetTarget().GetExecutableModulePointer() != module_sp
.get())
3038 new_executable_module_sp
= module_sp
;
3042 if (new_executable_module_sp
) {
3043 GetTarget().SetExecutableModule(new_executable_module_sp
,
3046 ModuleSP exe_module_sp
= GetTarget().GetExecutableModule();
3049 "Process::%s after looping through modules, target executable is %s",
3051 exe_module_sp
? exe_module_sp
->GetFileSpec().GetPath().c_str()
3057 Status
Process::ConnectRemote(llvm::StringRef remote_url
) {
3060 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
3061 m_process_input_reader
.reset();
3064 // Find the process and its architecture. Make sure it matches the
3065 // architecture of the current Target, and if not adjust it.
3067 Status
error(DoConnectRemote(remote_url
));
3068 if (error
.Success()) {
3069 if (GetID() != LLDB_INVALID_PROCESS_ID
) {
3071 StateType state
= WaitForProcessStopPrivate(event_sp
, std::nullopt
);
3073 if (state
== eStateStopped
|| state
== eStateCrashed
) {
3074 // If we attached and actually have a process on the other end, then
3075 // this ended up being the equivalent of an attach.
3078 // This delays passing the stopped event to listeners till
3079 // CompleteAttach gets a chance to complete...
3080 HandlePrivateEvent(event_sp
);
3084 if (PrivateStateThreadIsValid())
3085 ResumePrivateStateThread();
3087 StartPrivateStateThread();
3092 Status
Process::PrivateResume() {
3093 Log
*log(GetLog(LLDBLog::Process
| LLDBLog::Step
));
3095 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3096 "private state: %s",
3097 m_mod_id
.GetStopID(), StateAsCString(m_public_state
.GetValue()),
3098 StateAsCString(m_private_state
.GetValue()));
3100 // If signals handing status changed we might want to update our signal
3101 // filters before resuming.
3102 UpdateAutomaticSignalFiltering();
3104 Status
error(WillResume());
3105 // Tell the process it is about to resume before the thread list
3106 if (error
.Success()) {
3107 // Now let the thread list know we are about to resume so it can let all of
3108 // our threads know that they are about to be resumed. Threads will each be
3109 // called with Thread::WillResume(StateType) where StateType contains the
3110 // state that they are supposed to have when the process is resumed
3111 // (suspended/running/stepping). Threads should also check their resume
3112 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3113 // start back up with a signal.
3114 if (m_thread_list
.WillResume()) {
3115 // Last thing, do the PreResumeActions.
3116 if (!RunPreResumeActions()) {
3117 error
.SetErrorString(
3118 "Process::PrivateResume PreResumeActions failed, not resuming.");
3120 m_mod_id
.BumpResumeID();
3122 if (error
.Success()) {
3124 m_thread_list
.DidResume();
3125 LLDB_LOGF(log
, "Process thinks the process has resumed.");
3127 LLDB_LOGF(log
, "Process::PrivateResume() DoResume failed.");
3132 // Somebody wanted to run without running (e.g. we were faking a step
3133 // from one frame of a set of inlined frames that share the same PC to
3134 // another.) So generate a continue & a stopped event, and let the world
3137 "Process::PrivateResume() asked to simulate a start & stop.");
3139 SetPrivateState(eStateRunning
);
3140 SetPrivateState(eStateStopped
);
3143 LLDB_LOGF(log
, "Process::PrivateResume() got an error \"%s\".",
3144 error
.AsCString("<unknown error>"));
3148 Status
Process::Halt(bool clear_thread_plans
, bool use_run_lock
) {
3149 if (!StateIsRunningState(m_public_state
.GetValue()))
3150 return Status("Process is not running.");
3152 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3153 // case it was already set and some thread plan logic calls halt on its own.
3154 m_clear_thread_plans_on_stop
|= clear_thread_plans
;
3156 ListenerSP
halt_listener_sp(
3157 Listener::MakeListener("lldb.process.halt_listener"));
3158 HijackProcessEvents(halt_listener_sp
);
3162 SendAsyncInterrupt();
3164 if (m_public_state
.GetValue() == eStateAttaching
) {
3165 // Don't hijack and eat the eStateExited as the code that was doing the
3166 // attach will be waiting for this event...
3167 RestoreProcessEvents();
3168 SetExitStatus(SIGKILL
, "Cancelled async attach.");
3173 // Wait for the process halt timeout seconds for the process to stop.
3174 // If we are going to use the run lock, that means we're stopping out to the
3175 // user, so we should also select the most relevant frame.
3176 SelectMostRelevant select_most_relevant
=
3177 use_run_lock
? SelectMostRelevantFrame
: DoNoSelectMostRelevantFrame
;
3178 StateType state
= WaitForProcessToStop(GetInterruptTimeout(), &event_sp
, true,
3179 halt_listener_sp
, nullptr,
3180 use_run_lock
, select_most_relevant
);
3181 RestoreProcessEvents();
3183 if (state
== eStateInvalid
|| !event_sp
) {
3184 // We timed out and didn't get a stop event...
3185 return Status("Halt timed out. State = %s", StateAsCString(GetState()));
3188 BroadcastEvent(event_sp
);
3193 Status
Process::StopForDestroyOrDetach(lldb::EventSP
&exit_event_sp
) {
3196 // Check both the public & private states here. If we're hung evaluating an
3197 // expression, for instance, then the public state will be stopped, but we
3198 // still need to interrupt.
3199 if (m_public_state
.GetValue() == eStateRunning
||
3200 m_private_state
.GetValue() == eStateRunning
) {
3201 Log
*log
= GetLog(LLDBLog::Process
);
3202 LLDB_LOGF(log
, "Process::%s() About to stop.", __FUNCTION__
);
3204 ListenerSP
listener_sp(
3205 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3206 HijackProcessEvents(listener_sp
);
3208 SendAsyncInterrupt();
3210 // Consume the interrupt event.
3211 StateType state
= WaitForProcessToStop(GetInterruptTimeout(),
3212 &exit_event_sp
, true, listener_sp
);
3214 RestoreProcessEvents();
3216 // If the process exited while we were waiting for it to stop, put the
3217 // exited event into the shared pointer passed in and return. Our caller
3218 // doesn't need to do anything else, since they don't have a process
3221 if (state
== eStateExited
|| m_private_state
.GetValue() == eStateExited
) {
3222 LLDB_LOGF(log
, "Process::%s() Process exited while waiting to stop.",
3226 exit_event_sp
.reset(); // It is ok to consume any non-exit stop events
3228 if (state
!= eStateStopped
) {
3229 LLDB_LOGF(log
, "Process::%s() failed to stop, state is: %s", __FUNCTION__
,
3230 StateAsCString(state
));
3231 // If we really couldn't stop the process then we should just error out
3232 // here, but if the lower levels just bobbled sending the event and we
3233 // really are stopped, then continue on.
3234 StateType private_state
= m_private_state
.GetValue();
3235 if (private_state
!= eStateStopped
) {
3237 "Attempt to stop the target in order to detach timed out. "
3239 StateAsCString(GetState()));
3246 Status
Process::Detach(bool keep_stopped
) {
3247 EventSP exit_event_sp
;
3249 m_destroy_in_process
= true;
3251 error
= WillDetach();
3253 if (error
.Success()) {
3254 if (DetachRequiresHalt()) {
3255 error
= StopForDestroyOrDetach(exit_event_sp
);
3256 if (!error
.Success()) {
3257 m_destroy_in_process
= false;
3259 } else if (exit_event_sp
) {
3260 // We shouldn't need to do anything else here. There's no process left
3261 // to detach from...
3262 StopPrivateStateThread();
3263 m_destroy_in_process
= false;
3268 m_thread_list
.DiscardThreadPlans();
3269 DisableAllBreakpointSites();
3271 error
= DoDetach(keep_stopped
);
3272 if (error
.Success()) {
3274 StopPrivateStateThread();
3279 m_destroy_in_process
= false;
3281 // If we exited when we were waiting for a process to stop, then forward the
3282 // event here so we don't lose the event
3283 if (exit_event_sp
) {
3284 // Directly broadcast our exited event because we shut down our private
3285 // state thread above
3286 BroadcastEvent(exit_event_sp
);
3289 // If we have been interrupted (to kill us) in the middle of running, we may
3290 // not end up propagating the last events through the event system, in which
3291 // case we might strand the write lock. Unlock it here so when we do to tear
3292 // down the process we don't get an error destroying the lock.
3294 m_public_run_lock
.SetStopped();
3298 Status
Process::Destroy(bool force_kill
) {
3299 // If we've already called Process::Finalize then there's nothing useful to
3300 // be done here. Finalize has actually called Destroy already.
3303 return DestroyImpl(force_kill
);
3306 Status
Process::DestroyImpl(bool force_kill
) {
3307 // Tell ourselves we are in the process of destroying the process, so that we
3308 // don't do any unnecessary work that might hinder the destruction. Remember
3309 // to set this back to false when we are done. That way if the attempt
3310 // failed and the process stays around for some reason it won't be in a
3314 m_should_detach
= false;
3316 if (GetShouldDetach()) {
3317 // FIXME: This will have to be a process setting:
3318 bool keep_stopped
= false;
3319 Detach(keep_stopped
);
3322 m_destroy_in_process
= true;
3324 Status
error(WillDestroy());
3325 if (error
.Success()) {
3326 EventSP exit_event_sp
;
3327 if (DestroyRequiresHalt()) {
3328 error
= StopForDestroyOrDetach(exit_event_sp
);
3331 if (m_public_state
.GetValue() == eStateStopped
) {
3332 // Ditch all thread plans, and remove all our breakpoints: in case we
3333 // have to restart the target to kill it, we don't want it hitting a
3334 // breakpoint... Only do this if we've stopped, however, since if we
3335 // didn't manage to halt it above, then we're not going to have much luck
3337 m_thread_list
.DiscardThreadPlans();
3338 DisableAllBreakpointSites();
3341 error
= DoDestroy();
3342 if (error
.Success()) {
3344 StopPrivateStateThread();
3346 m_stdio_communication
.StopReadThread();
3347 m_stdio_communication
.Disconnect();
3348 m_stdin_forward
= false;
3351 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
3352 if (m_process_input_reader
) {
3353 m_process_input_reader
->SetIsDone(true);
3354 m_process_input_reader
->Cancel();
3355 m_process_input_reader
.reset();
3359 // If we exited when we were waiting for a process to stop, then forward
3360 // the event here so we don't lose the event
3361 if (exit_event_sp
) {
3362 // Directly broadcast our exited event because we shut down our private
3363 // state thread above
3364 BroadcastEvent(exit_event_sp
);
3367 // If we have been interrupted (to kill us) in the middle of running, we
3368 // may not end up propagating the last events through the event system, in
3369 // which case we might strand the write lock. Unlock it here so when we do
3370 // to tear down the process we don't get an error destroying the lock.
3371 m_public_run_lock
.SetStopped();
3374 m_destroy_in_process
= false;
3379 Status
Process::Signal(int signal
) {
3380 Status
error(WillSignal());
3381 if (error
.Success()) {
3382 error
= DoSignal(signal
);
3383 if (error
.Success())
3389 void Process::SetUnixSignals(UnixSignalsSP
&&signals_sp
) {
3390 assert(signals_sp
&& "null signals_sp");
3391 m_unix_signals_sp
= std::move(signals_sp
);
3394 const lldb::UnixSignalsSP
&Process::GetUnixSignals() {
3395 assert(m_unix_signals_sp
&& "null m_unix_signals_sp");
3396 return m_unix_signals_sp
;
3399 lldb::ByteOrder
Process::GetByteOrder() const {
3400 return GetTarget().GetArchitecture().GetByteOrder();
3403 uint32_t Process::GetAddressByteSize() const {
3404 return GetTarget().GetArchitecture().GetAddressByteSize();
3407 bool Process::ShouldBroadcastEvent(Event
*event_ptr
) {
3408 const StateType state
=
3409 Process::ProcessEventData::GetStateFromEvent(event_ptr
);
3410 bool return_value
= true;
3411 Log
*log(GetLog(LLDBLog::Events
| LLDBLog::Process
));
3414 case eStateDetached
:
3416 case eStateUnloaded
:
3417 m_stdio_communication
.SynchronizeWithReadThread();
3418 m_stdio_communication
.StopReadThread();
3419 m_stdio_communication
.Disconnect();
3420 m_stdin_forward
= false;
3423 case eStateConnected
:
3424 case eStateAttaching
:
3425 case eStateLaunching
:
3426 // These events indicate changes in the state of the debugging session,
3427 // always report them.
3428 return_value
= true;
3431 // We stopped for no apparent reason, don't report it.
3432 return_value
= false;
3435 case eStateStepping
:
3436 // If we've started the target running, we handle the cases where we are
3437 // already running and where there is a transition from stopped to running
3438 // differently. running -> running: Automatically suppress extra running
3439 // events stopped -> running: Report except when there is one or more no
3441 // and no yes votes.
3442 SynchronouslyNotifyStateChanged(state
);
3443 if (m_force_next_event_delivery
)
3444 return_value
= true;
3446 switch (m_last_broadcast_state
) {
3448 case eStateStepping
:
3449 // We always suppress multiple runnings with no PUBLIC stop in between.
3450 return_value
= false;
3453 // TODO: make this work correctly. For now always report
3454 // run if we aren't running so we don't miss any running events. If I
3455 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3456 // and hit the breakpoints on multiple threads, then somehow during the
3457 // stepping over of all breakpoints no run gets reported.
3459 // This is a transition from stop to run.
3460 switch (m_thread_list
.ShouldReportRun(event_ptr
)) {
3462 case eVoteNoOpinion
:
3463 return_value
= true;
3466 return_value
= false;
3475 case eStateSuspended
:
3476 // We've stopped. First see if we're going to restart the target. If we
3477 // are going to stop, then we always broadcast the event. If we aren't
3478 // going to stop, let the thread plans decide if we're going to report this
3479 // event. If no thread has an opinion, we don't report it.
3481 m_stdio_communication
.SynchronizeWithReadThread();
3482 RefreshStateAfterStop();
3483 if (ProcessEventData::GetInterruptedFromEvent(event_ptr
)) {
3485 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3486 "interrupt, state: %s",
3487 static_cast<void *>(event_ptr
), StateAsCString(state
));
3488 // Even though we know we are going to stop, we should let the threads
3489 // have a look at the stop, so they can properly set their state.
3490 m_thread_list
.ShouldStop(event_ptr
);
3491 return_value
= true;
3493 bool was_restarted
= ProcessEventData::GetRestartedFromEvent(event_ptr
);
3494 bool should_resume
= false;
3496 // It makes no sense to ask "ShouldStop" if we've already been
3497 // restarted... Asking the thread list is also not likely to go well,
3498 // since we are running again. So in that case just report the event.
3501 should_resume
= !m_thread_list
.ShouldStop(event_ptr
);
3503 if (was_restarted
|| should_resume
|| m_resume_requested
) {
3504 Vote report_stop_vote
= m_thread_list
.ShouldReportStop(event_ptr
);
3506 "Process::ShouldBroadcastEvent: should_resume: %i state: "
3507 "%s was_restarted: %i report_stop_vote: %d.",
3508 should_resume
, StateAsCString(state
), was_restarted
,
3511 switch (report_stop_vote
) {
3513 return_value
= true;
3515 case eVoteNoOpinion
:
3517 return_value
= false;
3521 if (!was_restarted
) {
3523 "Process::ShouldBroadcastEvent (%p) Restarting process "
3525 static_cast<void *>(event_ptr
), StateAsCString(state
));
3526 ProcessEventData::SetRestartedInEvent(event_ptr
, true);
3530 return_value
= true;
3531 SynchronouslyNotifyStateChanged(state
);
3537 // Forcing the next event delivery is a one shot deal. So reset it here.
3538 m_force_next_event_delivery
= false;
3540 // We do some coalescing of events (for instance two consecutive running
3541 // events get coalesced.) But we only coalesce against events we actually
3542 // broadcast. So we use m_last_broadcast_state to track that. NB - you
3543 // can't use "m_public_state.GetValue()" for that purpose, as was originally
3544 // done, because the PublicState reflects the last event pulled off the
3545 // queue, and there may be several events stacked up on the queue unserviced.
3546 // So the PublicState may not reflect the last broadcasted event yet.
3547 // m_last_broadcast_state gets updated here.
3550 m_last_broadcast_state
= state
;
3553 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
3554 "broadcast state: %s - %s",
3555 static_cast<void *>(event_ptr
), StateAsCString(state
),
3556 StateAsCString(m_last_broadcast_state
),
3557 return_value
? "YES" : "NO");
3558 return return_value
;
3561 bool Process::StartPrivateStateThread(bool is_secondary_thread
) {
3562 Log
*log
= GetLog(LLDBLog::Events
);
3564 bool already_running
= PrivateStateThreadIsValid();
3565 LLDB_LOGF(log
, "Process::%s()%s ", __FUNCTION__
,
3566 already_running
? " already running"
3567 : " starting private state thread");
3569 if (!is_secondary_thread
&& already_running
)
3572 // Create a thread that watches our internal state and controls which events
3573 // make it to clients (into the DCProcess event queue).
3574 char thread_name
[1024];
3575 uint32_t max_len
= llvm::get_max_thread_name_length();
3576 if (max_len
> 0 && max_len
<= 30) {
3577 // On platforms with abbreviated thread name lengths, choose thread names
3578 // that fit within the limit.
3579 if (already_running
)
3580 snprintf(thread_name
, sizeof(thread_name
), "intern-state-OV");
3582 snprintf(thread_name
, sizeof(thread_name
), "intern-state");
3584 if (already_running
)
3585 snprintf(thread_name
, sizeof(thread_name
),
3586 "<lldb.process.internal-state-override(pid=%" PRIu64
")>",
3589 snprintf(thread_name
, sizeof(thread_name
),
3590 "<lldb.process.internal-state(pid=%" PRIu64
")>", GetID());
3593 llvm::Expected
<HostThread
> private_state_thread
=
3594 ThreadLauncher::LaunchThread(
3596 [this, is_secondary_thread
] {
3597 return RunPrivateStateThread(is_secondary_thread
);
3600 if (!private_state_thread
) {
3601 LLDB_LOG_ERROR(GetLog(LLDBLog::Host
), private_state_thread
.takeError(),
3602 "failed to launch host thread: {0}");
3606 assert(private_state_thread
->IsJoinable());
3607 m_private_state_thread
= *private_state_thread
;
3608 ResumePrivateStateThread();
3612 void Process::PausePrivateStateThread() {
3613 ControlPrivateStateThread(eBroadcastInternalStateControlPause
);
3616 void Process::ResumePrivateStateThread() {
3617 ControlPrivateStateThread(eBroadcastInternalStateControlResume
);
3620 void Process::StopPrivateStateThread() {
3621 if (m_private_state_thread
.IsJoinable())
3622 ControlPrivateStateThread(eBroadcastInternalStateControlStop
);
3624 Log
*log
= GetLog(LLDBLog::Process
);
3627 "Went to stop the private state thread, but it was already invalid.");
3631 void Process::ControlPrivateStateThread(uint32_t signal
) {
3632 Log
*log
= GetLog(LLDBLog::Process
);
3634 assert(signal
== eBroadcastInternalStateControlStop
||
3635 signal
== eBroadcastInternalStateControlPause
||
3636 signal
== eBroadcastInternalStateControlResume
);
3638 LLDB_LOGF(log
, "Process::%s (signal = %d)", __FUNCTION__
, signal
);
3640 // Signal the private state thread
3641 if (m_private_state_thread
.IsJoinable()) {
3642 // Broadcast the event.
3643 // It is important to do this outside of the if below, because it's
3644 // possible that the thread state is invalid but that the thread is waiting
3645 // on a control event instead of simply being on its way out (this should
3646 // not happen, but it apparently can).
3647 LLDB_LOGF(log
, "Sending control event of type: %d.", signal
);
3648 std::shared_ptr
<EventDataReceipt
> event_receipt_sp(new EventDataReceipt());
3649 m_private_state_control_broadcaster
.BroadcastEvent(signal
,
3652 // Wait for the event receipt or for the private state thread to exit
3653 bool receipt_received
= false;
3654 if (PrivateStateThreadIsValid()) {
3655 while (!receipt_received
) {
3656 // Check for a receipt for n seconds and then check if the private
3657 // state thread is still around.
3659 event_receipt_sp
->WaitForEventReceived(GetUtilityExpressionTimeout());
3660 if (!receipt_received
) {
3661 // Check if the private state thread is still around. If it isn't
3662 // then we are done waiting
3663 if (!PrivateStateThreadIsValid())
3664 break; // Private state thread exited or is exiting, we are done
3669 if (signal
== eBroadcastInternalStateControlStop
) {
3670 thread_result_t result
= {};
3671 m_private_state_thread
.Join(&result
);
3672 m_private_state_thread
.Reset();
3677 "Private state thread already dead, no need to signal it to stop.");
3681 void Process::SendAsyncInterrupt() {
3682 if (PrivateStateThreadIsValid())
3683 m_private_state_broadcaster
.BroadcastEvent(Process::eBroadcastBitInterrupt
,
3686 BroadcastEvent(Process::eBroadcastBitInterrupt
, nullptr);
3689 void Process::HandlePrivateEvent(EventSP
&event_sp
) {
3690 Log
*log
= GetLog(LLDBLog::Process
);
3691 m_resume_requested
= false;
3693 const StateType new_state
=
3694 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
3696 // First check to see if anybody wants a shot at this event:
3697 if (m_next_event_action_up
) {
3698 NextEventAction::EventActionResult action_result
=
3699 m_next_event_action_up
->PerformAction(event_sp
);
3700 LLDB_LOGF(log
, "Ran next event action, result was %d.", action_result
);
3702 switch (action_result
) {
3703 case NextEventAction::eEventActionSuccess
:
3704 SetNextEventAction(nullptr);
3707 case NextEventAction::eEventActionRetry
:
3710 case NextEventAction::eEventActionExit
:
3711 // Handle Exiting Here. If we already got an exited event, we should
3712 // just propagate it. Otherwise, swallow this event, and set our state
3713 // to exit so the next event will kill us.
3714 if (new_state
!= eStateExited
) {
3715 // FIXME: should cons up an exited event, and discard this one.
3716 SetExitStatus(0, m_next_event_action_up
->GetExitString());
3717 SetNextEventAction(nullptr);
3720 SetNextEventAction(nullptr);
3725 // See if we should broadcast this state to external clients?
3726 const bool should_broadcast
= ShouldBroadcastEvent(event_sp
.get());
3728 if (should_broadcast
) {
3729 const bool is_hijacked
= IsHijackedForEvent(eBroadcastBitStateChanged
);
3732 "Process::%s (pid = %" PRIu64
3733 ") broadcasting new state %s (old state %s) to %s",
3734 __FUNCTION__
, GetID(), StateAsCString(new_state
),
3735 StateAsCString(GetState()),
3736 is_hijacked
? "hijacked" : "public");
3738 Process::ProcessEventData::SetUpdateStateOnRemoval(event_sp
.get());
3739 if (StateIsRunningState(new_state
)) {
3740 // Only push the input handler if we aren't fowarding events, as this
3741 // means the curses GUI is in use... Or don't push it if we are launching
3742 // since it will come up stopped.
3743 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
3744 new_state
!= eStateLaunching
&& new_state
!= eStateAttaching
) {
3745 PushProcessIOHandler();
3746 m_iohandler_sync
.SetValue(m_iohandler_sync
.GetValue() + 1,
3748 LLDB_LOGF(log
, "Process::%s updated m_iohandler_sync to %d",
3749 __FUNCTION__
, m_iohandler_sync
.GetValue());
3751 } else if (StateIsStoppedState(new_state
, false)) {
3752 if (!Process::ProcessEventData::GetRestartedFromEvent(event_sp
.get())) {
3753 // If the lldb_private::Debugger is handling the events, we don't want
3754 // to pop the process IOHandler here, we want to do it when we receive
3755 // the stopped event so we can carefully control when the process
3756 // IOHandler is popped because when we stop we want to display some
3757 // text stating how and why we stopped, then maybe some
3758 // process/thread/frame info, and then we want the "(lldb) " prompt to
3759 // show up. If we pop the process IOHandler here, then we will cause
3760 // the command interpreter to become the top IOHandler after the
3761 // process pops off and it will update its prompt right away... See the
3762 // Debugger.cpp file where it calls the function as
3763 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
3764 // Otherwise we end up getting overlapping "(lldb) " prompts and
3767 // If we aren't handling the events in the debugger (which is indicated
3768 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
3769 // we are hijacked, then we always pop the process IO handler manually.
3770 // Hijacking happens when the internal process state thread is running
3771 // thread plans, or when commands want to run in synchronous mode and
3772 // they call "process->WaitForProcessToStop()". An example of something
3773 // that will hijack the events is a simple expression:
3775 // (lldb) expr (int)puts("hello")
3777 // This will cause the internal process state thread to resume and halt
3778 // the process (and _it_ will hijack the eBroadcastBitStateChanged
3779 // events) and we do need the IO handler to be pushed and popped
3782 if (is_hijacked
|| !GetTarget().GetDebugger().IsHandlingEvents())
3783 PopProcessIOHandler();
3787 BroadcastEvent(event_sp
);
3792 "Process::%s (pid = %" PRIu64
3793 ") suppressing state %s (old state %s): should_broadcast == false",
3794 __FUNCTION__
, GetID(), StateAsCString(new_state
),
3795 StateAsCString(GetState()));
3800 Status
Process::HaltPrivate() {
3802 Status
error(WillHalt());
3806 // Ask the process subclass to actually halt our process
3808 error
= DoHalt(caused_stop
);
3814 thread_result_t
Process::RunPrivateStateThread(bool is_secondary_thread
) {
3815 bool control_only
= true;
3817 Log
*log
= GetLog(LLDBLog::Process
);
3818 LLDB_LOGF(log
, "Process::%s (arg = %p, pid = %" PRIu64
") thread starting...",
3819 __FUNCTION__
, static_cast<void *>(this), GetID());
3821 bool exit_now
= false;
3822 bool interrupt_requested
= false;
3825 GetEventsPrivate(event_sp
, std::nullopt
, control_only
);
3826 if (event_sp
->BroadcasterIs(&m_private_state_control_broadcaster
)) {
3828 "Process::%s (arg = %p, pid = %" PRIu64
3829 ") got a control event: %d",
3830 __FUNCTION__
, static_cast<void *>(this), GetID(),
3831 event_sp
->GetType());
3833 switch (event_sp
->GetType()) {
3834 case eBroadcastInternalStateControlStop
:
3836 break; // doing any internal state management below
3838 case eBroadcastInternalStateControlPause
:
3839 control_only
= true;
3842 case eBroadcastInternalStateControlResume
:
3843 control_only
= false;
3848 } else if (event_sp
->GetType() == eBroadcastBitInterrupt
) {
3849 if (m_public_state
.GetValue() == eStateAttaching
) {
3851 "Process::%s (arg = %p, pid = %" PRIu64
3852 ") woke up with an interrupt while attaching - "
3853 "forwarding interrupt.",
3854 __FUNCTION__
, static_cast<void *>(this), GetID());
3855 BroadcastEvent(eBroadcastBitInterrupt
, nullptr);
3856 } else if (StateIsRunningState(m_last_broadcast_state
)) {
3858 "Process::%s (arg = %p, pid = %" PRIu64
3859 ") woke up with an interrupt - Halting.",
3860 __FUNCTION__
, static_cast<void *>(this), GetID());
3861 Status error
= HaltPrivate();
3862 if (error
.Fail() && log
)
3864 "Process::%s (arg = %p, pid = %" PRIu64
3865 ") failed to halt the process: %s",
3866 __FUNCTION__
, static_cast<void *>(this), GetID(),
3868 // Halt should generate a stopped event. Make a note of the fact that
3869 // we were doing the interrupt, so we can set the interrupted flag
3870 // after we receive the event. We deliberately set this to true even if
3871 // HaltPrivate failed, so that we can interrupt on the next natural
3873 interrupt_requested
= true;
3875 // This can happen when someone (e.g. Process::Halt) sees that we are
3876 // running and sends an interrupt request, but the process actually
3877 // stops before we receive it. In that case, we can just ignore the
3878 // request. We use m_last_broadcast_state, because the Stopped event
3879 // may not have been popped of the event queue yet, which is when the
3880 // public state gets updated.
3882 "Process::%s ignoring interrupt as we have already stopped.",
3888 const StateType internal_state
=
3889 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
3891 if (internal_state
!= eStateInvalid
) {
3892 if (m_clear_thread_plans_on_stop
&&
3893 StateIsStoppedState(internal_state
, true)) {
3894 m_clear_thread_plans_on_stop
= false;
3895 m_thread_list
.DiscardThreadPlans();
3898 if (interrupt_requested
) {
3899 if (StateIsStoppedState(internal_state
, true)) {
3900 // We requested the interrupt, so mark this as such in the stop event
3901 // so clients can tell an interrupted process from a natural stop
3902 ProcessEventData::SetInterruptedInEvent(event_sp
.get(), true);
3903 interrupt_requested
= false;
3906 "Process::%s interrupt_requested, but a non-stopped "
3907 "state '%s' received.",
3908 __FUNCTION__
, StateAsCString(internal_state
));
3912 HandlePrivateEvent(event_sp
);
3915 if (internal_state
== eStateInvalid
|| internal_state
== eStateExited
||
3916 internal_state
== eStateDetached
) {
3918 "Process::%s (arg = %p, pid = %" PRIu64
3919 ") about to exit with internal state %s...",
3920 __FUNCTION__
, static_cast<void *>(this), GetID(),
3921 StateAsCString(internal_state
));
3927 // Verify log is still enabled before attempting to write to it...
3928 LLDB_LOGF(log
, "Process::%s (arg = %p, pid = %" PRIu64
") thread exiting...",
3929 __FUNCTION__
, static_cast<void *>(this), GetID());
3931 // If we are a secondary thread, then the primary thread we are working for
3932 // will have already acquired the public_run_lock, and isn't done with what
3933 // it was doing yet, so don't try to change it on the way out.
3934 if (!is_secondary_thread
)
3935 m_public_run_lock
.SetStopped();
3939 // Process Event Data
3941 Process::ProcessEventData::ProcessEventData() : EventData(), m_process_wp() {}
3943 Process::ProcessEventData::ProcessEventData(const ProcessSP
&process_sp
,
3945 : EventData(), m_process_wp(), m_state(state
) {
3947 m_process_wp
= process_sp
;
3950 Process::ProcessEventData::~ProcessEventData() = default;
3952 llvm::StringRef
Process::ProcessEventData::GetFlavorString() {
3953 return "Process::ProcessEventData";
3956 llvm::StringRef
Process::ProcessEventData::GetFlavor() const {
3957 return ProcessEventData::GetFlavorString();
3960 bool Process::ProcessEventData::ShouldStop(Event
*event_ptr
,
3961 bool &found_valid_stopinfo
) {
3962 found_valid_stopinfo
= false;
3964 ProcessSP
process_sp(m_process_wp
.lock());
3968 ThreadList
&curr_thread_list
= process_sp
->GetThreadList();
3969 uint32_t num_threads
= curr_thread_list
.GetSize();
3972 // The actions might change one of the thread's stop_info's opinions about
3973 // whether we should stop the process, so we need to query that as we go.
3975 // One other complication here, is that we try to catch any case where the
3976 // target has run (except for expressions) and immediately exit, but if we
3977 // get that wrong (which is possible) then the thread list might have
3978 // changed, and that would cause our iteration here to crash. We could
3979 // make a copy of the thread list, but we'd really like to also know if it
3980 // has changed at all, so we make up a vector of the thread ID's and check
3981 // what we get back against this list & bag out if anything differs.
3982 ThreadList
not_suspended_thread_list(process_sp
.get());
3983 std::vector
<uint32_t> thread_index_array(num_threads
);
3984 uint32_t not_suspended_idx
= 0;
3985 for (idx
= 0; idx
< num_threads
; ++idx
) {
3986 lldb::ThreadSP thread_sp
= curr_thread_list
.GetThreadAtIndex(idx
);
3989 Filter out all suspended threads, they could not be the reason
3990 of stop and no need to perform any actions on them.
3992 if (thread_sp
->GetResumeState() != eStateSuspended
) {
3993 not_suspended_thread_list
.AddThread(thread_sp
);
3994 thread_index_array
[not_suspended_idx
] = thread_sp
->GetIndexID();
3995 not_suspended_idx
++;
3999 // Use this to track whether we should continue from here. We will only
4000 // continue the target running if no thread says we should stop. Of course
4001 // if some thread's PerformAction actually sets the target running, then it
4002 // doesn't matter what the other threads say...
4004 bool still_should_stop
= false;
4006 // Sometimes - for instance if we have a bug in the stub we are talking to,
4007 // we stop but no thread has a valid stop reason. In that case we should
4008 // just stop, because we have no way of telling what the right thing to do
4009 // is, and it's better to let the user decide than continue behind their
4012 for (idx
= 0; idx
< not_suspended_thread_list
.GetSize(); ++idx
) {
4013 curr_thread_list
= process_sp
->GetThreadList();
4014 if (curr_thread_list
.GetSize() != num_threads
) {
4015 Log
*log(GetLog(LLDBLog::Step
| LLDBLog::Process
));
4018 "Number of threads changed from %u to %u while processing event.",
4019 num_threads
, curr_thread_list
.GetSize());
4023 lldb::ThreadSP thread_sp
= not_suspended_thread_list
.GetThreadAtIndex(idx
);
4025 if (thread_sp
->GetIndexID() != thread_index_array
[idx
]) {
4026 Log
*log(GetLog(LLDBLog::Step
| LLDBLog::Process
));
4028 "The thread at position %u changed from %u to %u while "
4029 "processing event.",
4030 idx
, thread_index_array
[idx
], thread_sp
->GetIndexID());
4034 StopInfoSP stop_info_sp
= thread_sp
->GetStopInfo();
4035 if (stop_info_sp
&& stop_info_sp
->IsValid()) {
4036 found_valid_stopinfo
= true;
4037 bool this_thread_wants_to_stop
;
4038 if (stop_info_sp
->GetOverrideShouldStop()) {
4039 this_thread_wants_to_stop
=
4040 stop_info_sp
->GetOverriddenShouldStopValue();
4042 stop_info_sp
->PerformAction(event_ptr
);
4043 // The stop action might restart the target. If it does, then we
4044 // want to mark that in the event so that whoever is receiving it
4045 // will know to wait for the running event and reflect that state
4046 // appropriately. We also need to stop processing actions, since they
4047 // aren't expecting the target to be running.
4049 // FIXME: we might have run.
4050 if (stop_info_sp
->HasTargetRunSinceMe()) {
4055 this_thread_wants_to_stop
= stop_info_sp
->ShouldStop(event_ptr
);
4058 if (!still_should_stop
)
4059 still_should_stop
= this_thread_wants_to_stop
;
4063 return still_should_stop
;
4066 void Process::ProcessEventData::DoOnRemoval(Event
*event_ptr
) {
4067 ProcessSP
process_sp(m_process_wp
.lock());
4072 // This function gets called twice for each event, once when the event gets
4073 // pulled off of the private process event queue, and then any number of
4074 // times, first when it gets pulled off of the public event queue, then other
4075 // times when we're pretending that this is where we stopped at the end of
4076 // expression evaluation. m_update_state is used to distinguish these three
4077 // cases; it is 0 when we're just pulling it off for private handling, and >
4078 // 1 for expression evaluation, and we don't want to do the breakpoint
4079 // command handling then.
4080 if (m_update_state
!= 1)
4083 process_sp
->SetPublicState(
4084 m_state
, Process::ProcessEventData::GetRestartedFromEvent(event_ptr
));
4086 if (m_state
== eStateStopped
&& !m_restarted
) {
4087 // Let process subclasses know we are about to do a public stop and do
4088 // anything they might need to in order to speed up register and memory
4090 process_sp
->WillPublicStop();
4093 // If this is a halt event, even if the halt stopped with some reason other
4094 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4095 // the halt request came through) don't do the StopInfo actions, as they may
4096 // end up restarting the process.
4100 // If we're not stopped or have restarted, then skip the StopInfo actions:
4101 if (m_state
!= eStateStopped
|| m_restarted
) {
4105 bool does_anybody_have_an_opinion
= false;
4106 bool still_should_stop
= ShouldStop(event_ptr
, does_anybody_have_an_opinion
);
4108 if (GetRestarted()) {
4112 if (!still_should_stop
&& does_anybody_have_an_opinion
) {
4113 // We've been asked to continue, so do that here.
4115 // Use the private resume method here, since we aren't changing the run
4117 process_sp
->PrivateResume();
4119 bool hijacked
= process_sp
->IsHijackedForEvent(eBroadcastBitStateChanged
) &&
4120 !process_sp
->StateChangedIsHijackedForSynchronousResume();
4123 // If we didn't restart, run the Stop Hooks here.
4124 // Don't do that if state changed events aren't hooked up to the
4125 // public (or SyncResume) broadcasters. StopHooks are just for
4126 // real public stops. They might also restart the target,
4127 // so watch for that.
4128 if (process_sp
->GetTarget().RunStopHooks())
4134 void Process::ProcessEventData::Dump(Stream
*s
) const {
4135 ProcessSP
process_sp(m_process_wp
.lock());
4138 s
->Printf(" process = %p (pid = %" PRIu64
"), ",
4139 static_cast<void *>(process_sp
.get()), process_sp
->GetID());
4141 s
->PutCString(" process = NULL, ");
4143 s
->Printf("state = %s", StateAsCString(GetState()));
4146 const Process::ProcessEventData
*
4147 Process::ProcessEventData::GetEventDataFromEvent(const Event
*event_ptr
) {
4149 const EventData
*event_data
= event_ptr
->GetData();
4151 event_data
->GetFlavor() == ProcessEventData::GetFlavorString())
4152 return static_cast<const ProcessEventData
*>(event_ptr
->GetData());
4158 Process::ProcessEventData::GetProcessFromEvent(const Event
*event_ptr
) {
4159 ProcessSP process_sp
;
4160 const ProcessEventData
*data
= GetEventDataFromEvent(event_ptr
);
4162 process_sp
= data
->GetProcessSP();
4166 StateType
Process::ProcessEventData::GetStateFromEvent(const Event
*event_ptr
) {
4167 const ProcessEventData
*data
= GetEventDataFromEvent(event_ptr
);
4168 if (data
== nullptr)
4169 return eStateInvalid
;
4171 return data
->GetState();
4174 bool Process::ProcessEventData::GetRestartedFromEvent(const Event
*event_ptr
) {
4175 const ProcessEventData
*data
= GetEventDataFromEvent(event_ptr
);
4176 if (data
== nullptr)
4179 return data
->GetRestarted();
4182 void Process::ProcessEventData::SetRestartedInEvent(Event
*event_ptr
,
4184 ProcessEventData
*data
=
4185 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4186 if (data
!= nullptr)
4187 data
->SetRestarted(new_value
);
4191 Process::ProcessEventData::GetNumRestartedReasons(const Event
*event_ptr
) {
4192 ProcessEventData
*data
=
4193 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4194 if (data
!= nullptr)
4195 return data
->GetNumRestartedReasons();
4201 Process::ProcessEventData::GetRestartedReasonAtIndex(const Event
*event_ptr
,
4203 ProcessEventData
*data
=
4204 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4205 if (data
!= nullptr)
4206 return data
->GetRestartedReasonAtIndex(idx
);
4211 void Process::ProcessEventData::AddRestartedReason(Event
*event_ptr
,
4212 const char *reason
) {
4213 ProcessEventData
*data
=
4214 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4215 if (data
!= nullptr)
4216 data
->AddRestartedReason(reason
);
4219 bool Process::ProcessEventData::GetInterruptedFromEvent(
4220 const Event
*event_ptr
) {
4221 const ProcessEventData
*data
= GetEventDataFromEvent(event_ptr
);
4222 if (data
== nullptr)
4225 return data
->GetInterrupted();
4228 void Process::ProcessEventData::SetInterruptedInEvent(Event
*event_ptr
,
4230 ProcessEventData
*data
=
4231 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4232 if (data
!= nullptr)
4233 data
->SetInterrupted(new_value
);
4236 bool Process::ProcessEventData::SetUpdateStateOnRemoval(Event
*event_ptr
) {
4237 ProcessEventData
*data
=
4238 const_cast<ProcessEventData
*>(GetEventDataFromEvent(event_ptr
));
4240 data
->SetUpdateStateOnRemoval();
4246 lldb::TargetSP
Process::CalculateTarget() { return m_target_wp
.lock(); }
4248 void Process::CalculateExecutionContext(ExecutionContext
&exe_ctx
) {
4249 exe_ctx
.SetTargetPtr(&GetTarget());
4250 exe_ctx
.SetProcessPtr(this);
4251 exe_ctx
.SetThreadPtr(nullptr);
4252 exe_ctx
.SetFramePtr(nullptr);
4256 // Process::ListProcessesMatchingName (const char *name, StringList &matches,
4257 // std::vector<lldb::pid_t> &pids)
4263 // Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4265 // return Host::GetArchSpecForExistingProcess (pid);
4269 // Process::GetArchSpecForExistingProcess (const char *process_name)
4271 // return Host::GetArchSpecForExistingProcess (process_name);
4274 void Process::AppendSTDOUT(const char *s
, size_t len
) {
4275 std::lock_guard
<std::recursive_mutex
> guard(m_stdio_communication_mutex
);
4276 m_stdout_data
.append(s
, len
);
4277 BroadcastEventIfUnique(eBroadcastBitSTDOUT
,
4278 new ProcessEventData(shared_from_this(), GetState()));
4281 void Process::AppendSTDERR(const char *s
, size_t len
) {
4282 std::lock_guard
<std::recursive_mutex
> guard(m_stdio_communication_mutex
);
4283 m_stderr_data
.append(s
, len
);
4284 BroadcastEventIfUnique(eBroadcastBitSTDERR
,
4285 new ProcessEventData(shared_from_this(), GetState()));
4288 void Process::BroadcastAsyncProfileData(const std::string
&one_profile_data
) {
4289 std::lock_guard
<std::recursive_mutex
> guard(m_profile_data_comm_mutex
);
4290 m_profile_data
.push_back(one_profile_data
);
4291 BroadcastEventIfUnique(eBroadcastBitProfileData
,
4292 new ProcessEventData(shared_from_this(), GetState()));
4295 void Process::BroadcastStructuredData(const StructuredData::ObjectSP
&object_sp
,
4296 const StructuredDataPluginSP
&plugin_sp
) {
4298 eBroadcastBitStructuredData
,
4299 new EventDataStructuredData(shared_from_this(), object_sp
, plugin_sp
));
4302 StructuredDataPluginSP
4303 Process::GetStructuredDataPlugin(llvm::StringRef type_name
) const {
4304 auto find_it
= m_structured_data_plugin_map
.find(type_name
);
4305 if (find_it
!= m_structured_data_plugin_map
.end())
4306 return find_it
->second
;
4308 return StructuredDataPluginSP();
4311 size_t Process::GetAsyncProfileData(char *buf
, size_t buf_size
, Status
&error
) {
4312 std::lock_guard
<std::recursive_mutex
> guard(m_profile_data_comm_mutex
);
4313 if (m_profile_data
.empty())
4316 std::string
&one_profile_data
= m_profile_data
.front();
4317 size_t bytes_available
= one_profile_data
.size();
4318 if (bytes_available
> 0) {
4319 Log
*log
= GetLog(LLDBLog::Process
);
4320 LLDB_LOGF(log
, "Process::GetProfileData (buf = %p, size = %" PRIu64
")",
4321 static_cast<void *>(buf
), static_cast<uint64_t>(buf_size
));
4322 if (bytes_available
> buf_size
) {
4323 memcpy(buf
, one_profile_data
.c_str(), buf_size
);
4324 one_profile_data
.erase(0, buf_size
);
4325 bytes_available
= buf_size
;
4327 memcpy(buf
, one_profile_data
.c_str(), bytes_available
);
4328 m_profile_data
.erase(m_profile_data
.begin());
4331 return bytes_available
;
4336 size_t Process::GetSTDOUT(char *buf
, size_t buf_size
, Status
&error
) {
4337 std::lock_guard
<std::recursive_mutex
> guard(m_stdio_communication_mutex
);
4338 size_t bytes_available
= m_stdout_data
.size();
4339 if (bytes_available
> 0) {
4340 Log
*log
= GetLog(LLDBLog::Process
);
4341 LLDB_LOGF(log
, "Process::GetSTDOUT (buf = %p, size = %" PRIu64
")",
4342 static_cast<void *>(buf
), static_cast<uint64_t>(buf_size
));
4343 if (bytes_available
> buf_size
) {
4344 memcpy(buf
, m_stdout_data
.c_str(), buf_size
);
4345 m_stdout_data
.erase(0, buf_size
);
4346 bytes_available
= buf_size
;
4348 memcpy(buf
, m_stdout_data
.c_str(), bytes_available
);
4349 m_stdout_data
.clear();
4352 return bytes_available
;
4355 size_t Process::GetSTDERR(char *buf
, size_t buf_size
, Status
&error
) {
4356 std::lock_guard
<std::recursive_mutex
> gaurd(m_stdio_communication_mutex
);
4357 size_t bytes_available
= m_stderr_data
.size();
4358 if (bytes_available
> 0) {
4359 Log
*log
= GetLog(LLDBLog::Process
);
4360 LLDB_LOGF(log
, "Process::GetSTDERR (buf = %p, size = %" PRIu64
")",
4361 static_cast<void *>(buf
), static_cast<uint64_t>(buf_size
));
4362 if (bytes_available
> buf_size
) {
4363 memcpy(buf
, m_stderr_data
.c_str(), buf_size
);
4364 m_stderr_data
.erase(0, buf_size
);
4365 bytes_available
= buf_size
;
4367 memcpy(buf
, m_stderr_data
.c_str(), bytes_available
);
4368 m_stderr_data
.clear();
4371 return bytes_available
;
4374 void Process::STDIOReadThreadBytesReceived(void *baton
, const void *src
,
4376 Process
*process
= (Process
*)baton
;
4377 process
->AppendSTDOUT(static_cast<const char *>(src
), src_len
);
4380 class IOHandlerProcessSTDIO
: public IOHandler
{
4382 IOHandlerProcessSTDIO(Process
*process
, int write_fd
)
4383 : IOHandler(process
->GetTarget().GetDebugger(),
4384 IOHandler::Type::ProcessIO
),
4386 m_read_file(GetInputFD(), File::eOpenOptionReadOnly
, false),
4387 m_write_file(write_fd
, File::eOpenOptionWriteOnly
, false) {
4388 m_pipe
.CreateNew(false);
4391 ~IOHandlerProcessSTDIO() override
= default;
4393 void SetIsRunning(bool running
) {
4394 std::lock_guard
<std::mutex
> guard(m_mutex
);
4395 SetIsDone(!running
);
4396 m_is_running
= running
;
4399 // Each IOHandler gets to run until it is done. It should read data from the
4400 // "in" and place output into "out" and "err and return when done.
4401 void Run() override
{
4402 if (!m_read_file
.IsValid() || !m_write_file
.IsValid() ||
4403 !m_pipe
.CanRead() || !m_pipe
.CanWrite()) {
4409 const int read_fd
= m_read_file
.GetDescriptor();
4410 Terminal
terminal(read_fd
);
4411 TerminalState
terminal_state(terminal
, false);
4412 // FIXME: error handling?
4413 llvm::consumeError(terminal
.SetCanonical(false));
4414 llvm::consumeError(terminal
.SetEcho(false));
4415 // FD_ZERO, FD_SET are not supported on windows
4417 const int pipe_read_fd
= m_pipe
.GetReadFileDescriptor();
4421 std::lock_guard
<std::mutex
> guard(m_mutex
);
4426 SelectHelper select_helper
;
4427 select_helper
.FDSetRead(read_fd
);
4428 select_helper
.FDSetRead(pipe_read_fd
);
4429 Status error
= select_helper
.Select();
4436 if (select_helper
.FDIsSetRead(read_fd
)) {
4438 if (m_read_file
.Read(&ch
, n
).Success() && n
== 1) {
4439 if (m_write_file
.Write(&ch
, n
).Fail() || n
!= 1)
4445 if (select_helper
.FDIsSetRead(pipe_read_fd
)) {
4447 // Consume the interrupt byte
4448 Status error
= m_pipe
.Read(&ch
, 1, bytes_read
);
4449 if (error
.Success()) {
4453 if (StateIsRunningState(m_process
->GetState()))
4454 m_process
->SendAsyncInterrupt();
4458 SetIsRunning(false);
4462 void Cancel() override
{
4463 std::lock_guard
<std::mutex
> guard(m_mutex
);
4465 // Only write to our pipe to cancel if we are in
4466 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
4467 // is being run from the command interpreter:
4469 // (lldb) step_process_thousands_of_times
4471 // In this case the command interpreter will be in the middle of handling
4472 // the command and if the process pushes and pops the IOHandler thousands
4473 // of times, we can end up writing to m_pipe without ever consuming the
4474 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
4475 // deadlocking when the pipe gets fed up and blocks until data is consumed.
4477 char ch
= 'q'; // Send 'q' for quit
4478 size_t bytes_written
= 0;
4479 m_pipe
.Write(&ch
, 1, bytes_written
);
4483 bool Interrupt() override
{
4484 // Do only things that are safe to do in an interrupt context (like in a
4485 // SIGINT handler), like write 1 byte to a file descriptor. This will
4486 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
4487 // that was written to the pipe and then call
4488 // m_process->SendAsyncInterrupt() from a much safer location in code.
4490 char ch
= 'i'; // Send 'i' for interrupt
4491 size_t bytes_written
= 0;
4492 Status result
= m_pipe
.Write(&ch
, 1, bytes_written
);
4493 return result
.Success();
4495 // This IOHandler might be pushed on the stack, but not being run
4496 // currently so do the right thing if we aren't actively watching for
4497 // STDIN by sending the interrupt to the process. Otherwise the write to
4498 // the pipe above would do nothing. This can happen when the command
4499 // interpreter is running and gets a "expression ...". It will be on the
4500 // IOHandler thread and sending the input is complete to the delegate
4501 // which will cause the expression to run, which will push the process IO
4502 // handler, but not run it.
4504 if (StateIsRunningState(m_process
->GetState())) {
4505 m_process
->SendAsyncInterrupt();
4512 void GotEOF() override
{}
4516 NativeFile m_read_file
; // Read from this file (usually actual STDIN for LLDB
4517 NativeFile m_write_file
; // Write to this file (usually the primary pty for
4518 // getting io to debuggee)
4521 bool m_is_running
= false;
4524 void Process::SetSTDIOFileDescriptor(int fd
) {
4525 // First set up the Read Thread for reading/handling process I/O
4526 m_stdio_communication
.SetConnection(
4527 std::make_unique
<ConnectionFileDescriptor
>(fd
, true));
4528 if (m_stdio_communication
.IsConnected()) {
4529 m_stdio_communication
.SetReadThreadBytesReceivedCallback(
4530 STDIOReadThreadBytesReceived
, this);
4531 m_stdio_communication
.StartReadThread();
4533 // Now read thread is set up, set up input reader.
4535 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
4536 if (!m_process_input_reader
)
4537 m_process_input_reader
=
4538 std::make_shared
<IOHandlerProcessSTDIO
>(this, fd
);
4543 bool Process::ProcessIOHandlerIsActive() {
4544 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
4545 IOHandlerSP
io_handler_sp(m_process_input_reader
);
4547 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp
);
4551 bool Process::PushProcessIOHandler() {
4552 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
4553 IOHandlerSP
io_handler_sp(m_process_input_reader
);
4554 if (io_handler_sp
) {
4555 Log
*log
= GetLog(LLDBLog::Process
);
4556 LLDB_LOGF(log
, "Process::%s pushing IO handler", __FUNCTION__
);
4558 io_handler_sp
->SetIsDone(false);
4559 // If we evaluate an utility function, then we don't cancel the current
4560 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
4561 // existing IOHandler that potentially provides the user interface (e.g.
4562 // the IOHandler for Editline).
4563 bool cancel_top_handler
= !m_mod_id
.IsRunningUtilityFunction();
4564 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp
,
4565 cancel_top_handler
);
4571 bool Process::PopProcessIOHandler() {
4572 std::lock_guard
<std::mutex
> guard(m_process_input_reader_mutex
);
4573 IOHandlerSP
io_handler_sp(m_process_input_reader
);
4575 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp
);
4579 // The process needs to know about installed plug-ins
4580 void Process::SettingsInitialize() { Thread::SettingsInitialize(); }
4582 void Process::SettingsTerminate() { Thread::SettingsTerminate(); }
4585 // RestorePlanState is used to record the "is private", "is controlling" and
4587 // to discard" fields of the plan we are running, and reset it on Clean or on
4588 // destruction. It will only reset the state once, so you can call Clean and
4589 // then monkey with the state and it won't get reset on you again.
4591 class RestorePlanState
{
4593 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp
)
4594 : m_thread_plan_sp(thread_plan_sp
) {
4595 if (m_thread_plan_sp
) {
4596 m_private
= m_thread_plan_sp
->GetPrivate();
4597 m_is_controlling
= m_thread_plan_sp
->IsControllingPlan();
4598 m_okay_to_discard
= m_thread_plan_sp
->OkayToDiscard();
4602 ~RestorePlanState() { Clean(); }
4605 if (!m_already_reset
&& m_thread_plan_sp
) {
4606 m_already_reset
= true;
4607 m_thread_plan_sp
->SetPrivate(m_private
);
4608 m_thread_plan_sp
->SetIsControllingPlan(m_is_controlling
);
4609 m_thread_plan_sp
->SetOkayToDiscard(m_okay_to_discard
);
4614 lldb::ThreadPlanSP m_thread_plan_sp
;
4615 bool m_already_reset
= false;
4616 bool m_private
= false;
4617 bool m_is_controlling
= false;
4618 bool m_okay_to_discard
= false;
4620 } // anonymous namespace
4623 GetOneThreadExpressionTimeout(const EvaluateExpressionOptions
&options
) {
4624 const milliseconds
default_one_thread_timeout(250);
4626 // If the overall wait is forever, then we don't need to worry about it.
4627 if (!options
.GetTimeout()) {
4628 return options
.GetOneThreadTimeout() ? *options
.GetOneThreadTimeout()
4629 : default_one_thread_timeout
;
4632 // If the one thread timeout is set, use it.
4633 if (options
.GetOneThreadTimeout())
4634 return *options
.GetOneThreadTimeout();
4636 // Otherwise use half the total timeout, bounded by the
4637 // default_one_thread_timeout.
4638 return std::min
<microseconds
>(default_one_thread_timeout
,
4639 *options
.GetTimeout() / 2);
4642 static Timeout
<std::micro
>
4643 GetExpressionTimeout(const EvaluateExpressionOptions
&options
,
4644 bool before_first_timeout
) {
4645 // If we are going to run all threads the whole time, or if we are only going
4646 // to run one thread, we can just return the overall timeout.
4647 if (!options
.GetStopOthers() || !options
.GetTryAllThreads())
4648 return options
.GetTimeout();
4650 if (before_first_timeout
)
4651 return GetOneThreadExpressionTimeout(options
);
4653 if (!options
.GetTimeout())
4654 return std::nullopt
;
4656 return *options
.GetTimeout() - GetOneThreadExpressionTimeout(options
);
4659 static std::optional
<ExpressionResults
>
4660 HandleStoppedEvent(lldb::tid_t thread_id
, const ThreadPlanSP
&thread_plan_sp
,
4661 RestorePlanState
&restorer
, const EventSP
&event_sp
,
4662 EventSP
&event_to_broadcast_sp
,
4663 const EvaluateExpressionOptions
&options
,
4664 bool handle_interrupts
) {
4665 Log
*log
= GetLog(LLDBLog::Step
| LLDBLog::Process
);
4667 ThreadSP thread_sp
= thread_plan_sp
->GetTarget()
4670 .FindThreadByID(thread_id
);
4673 "The thread on which we were running the "
4674 "expression: tid = {0}, exited while "
4675 "the expression was running.",
4677 return eExpressionThreadVanished
;
4680 ThreadPlanSP plan
= thread_sp
->GetCompletedPlan();
4681 if (plan
== thread_plan_sp
&& plan
->PlanSucceeded()) {
4682 LLDB_LOG(log
, "execution completed successfully");
4684 // Restore the plan state so it will get reported as intended when we are
4687 return eExpressionCompleted
;
4690 StopInfoSP stop_info_sp
= thread_sp
->GetStopInfo();
4691 if (stop_info_sp
&& stop_info_sp
->GetStopReason() == eStopReasonBreakpoint
&&
4692 stop_info_sp
->ShouldNotify(event_sp
.get())) {
4693 LLDB_LOG(log
, "stopped for breakpoint: {0}.", stop_info_sp
->GetDescription());
4694 if (!options
.DoesIgnoreBreakpoints()) {
4695 // Restore the plan state and then force Private to false. We are going
4696 // to stop because of this plan so we need it to become a public plan or
4697 // it won't report correctly when we continue to its termination later
4700 thread_plan_sp
->SetPrivate(false);
4701 event_to_broadcast_sp
= event_sp
;
4703 return eExpressionHitBreakpoint
;
4706 if (!handle_interrupts
&&
4707 Process::ProcessEventData::GetInterruptedFromEvent(event_sp
.get()))
4708 return std::nullopt
;
4710 LLDB_LOG(log
, "thread plan did not successfully complete");
4711 if (!options
.DoesUnwindOnError())
4712 event_to_broadcast_sp
= event_sp
;
4713 return eExpressionInterrupted
;
4717 Process::RunThreadPlan(ExecutionContext
&exe_ctx
,
4718 lldb::ThreadPlanSP
&thread_plan_sp
,
4719 const EvaluateExpressionOptions
&options
,
4720 DiagnosticManager
&diagnostic_manager
) {
4721 ExpressionResults return_value
= eExpressionSetupError
;
4723 std::lock_guard
<std::mutex
> run_thread_plan_locker(m_run_thread_plan_lock
);
4725 if (!thread_plan_sp
) {
4726 diagnostic_manager
.PutString(
4727 eDiagnosticSeverityError
,
4728 "RunThreadPlan called with empty thread plan.");
4729 return eExpressionSetupError
;
4732 if (!thread_plan_sp
->ValidatePlan(nullptr)) {
4733 diagnostic_manager
.PutString(
4734 eDiagnosticSeverityError
,
4735 "RunThreadPlan called with an invalid thread plan.");
4736 return eExpressionSetupError
;
4739 if (exe_ctx
.GetProcessPtr() != this) {
4740 diagnostic_manager
.PutString(eDiagnosticSeverityError
,
4741 "RunThreadPlan called on wrong process.");
4742 return eExpressionSetupError
;
4745 Thread
*thread
= exe_ctx
.GetThreadPtr();
4746 if (thread
== nullptr) {
4747 diagnostic_manager
.PutString(eDiagnosticSeverityError
,
4748 "RunThreadPlan called with invalid thread.");
4749 return eExpressionSetupError
;
4752 // Record the thread's id so we can tell when a thread we were using
4753 // to run the expression exits during the expression evaluation.
4754 lldb::tid_t expr_thread_id
= thread
->GetID();
4756 // We need to change some of the thread plan attributes for the thread plan
4757 // runner. This will restore them when we are done:
4759 RestorePlanState
thread_plan_restorer(thread_plan_sp
);
4761 // We rely on the thread plan we are running returning "PlanCompleted" if
4762 // when it successfully completes. For that to be true the plan can't be
4763 // private - since private plans suppress themselves in the GetCompletedPlan
4766 thread_plan_sp
->SetPrivate(false);
4768 // The plans run with RunThreadPlan also need to be terminal controlling plans
4769 // or when they are done we will end up asking the plan above us whether we
4770 // should stop, which may give the wrong answer.
4772 thread_plan_sp
->SetIsControllingPlan(true);
4773 thread_plan_sp
->SetOkayToDiscard(false);
4775 // If we are running some utility expression for LLDB, we now have to mark
4776 // this in the ProcesModID of this process. This RAII takes care of marking
4777 // and reverting the mark it once we are done running the expression.
4778 UtilityFunctionScope
util_scope(options
.IsForUtilityExpr() ? this : nullptr);
4780 if (m_private_state
.GetValue() != eStateStopped
) {
4781 diagnostic_manager
.PutString(
4782 eDiagnosticSeverityError
,
4783 "RunThreadPlan called while the private state was not stopped.");
4784 return eExpressionSetupError
;
4787 // Save the thread & frame from the exe_ctx for restoration after we run
4788 const uint32_t thread_idx_id
= thread
->GetIndexID();
4789 StackFrameSP selected_frame_sp
=
4790 thread
->GetSelectedFrame(DoNoSelectMostRelevantFrame
);
4791 if (!selected_frame_sp
) {
4792 thread
->SetSelectedFrame(nullptr);
4793 selected_frame_sp
= thread
->GetSelectedFrame(DoNoSelectMostRelevantFrame
);
4794 if (!selected_frame_sp
) {
4795 diagnostic_manager
.Printf(
4796 eDiagnosticSeverityError
,
4797 "RunThreadPlan called without a selected frame on thread %d",
4799 return eExpressionSetupError
;
4803 // Make sure the timeout values make sense. The one thread timeout needs to
4804 // be smaller than the overall timeout.
4805 if (options
.GetOneThreadTimeout() && options
.GetTimeout() &&
4806 *options
.GetTimeout() < *options
.GetOneThreadTimeout()) {
4807 diagnostic_manager
.PutString(eDiagnosticSeverityError
,
4808 "RunThreadPlan called with one thread "
4809 "timeout greater than total timeout");
4810 return eExpressionSetupError
;
4813 StackID ctx_frame_id
= selected_frame_sp
->GetStackID();
4815 // N.B. Running the target may unset the currently selected thread and frame.
4816 // We don't want to do that either, so we should arrange to reset them as
4819 lldb::ThreadSP selected_thread_sp
= GetThreadList().GetSelectedThread();
4821 uint32_t selected_tid
;
4822 StackID selected_stack_id
;
4823 if (selected_thread_sp
) {
4824 selected_tid
= selected_thread_sp
->GetIndexID();
4826 selected_thread_sp
->GetSelectedFrame(DoNoSelectMostRelevantFrame
)
4829 selected_tid
= LLDB_INVALID_THREAD_ID
;
4832 HostThread backup_private_state_thread
;
4833 lldb::StateType old_state
= eStateInvalid
;
4834 lldb::ThreadPlanSP stopper_base_plan_sp
;
4836 Log
*log(GetLog(LLDBLog::Step
| LLDBLog::Process
));
4837 if (m_private_state_thread
.EqualsThread(Host::GetCurrentThread())) {
4838 // Yikes, we are running on the private state thread! So we can't wait for
4839 // public events on this thread, since we are the thread that is generating
4840 // public events. The simplest thing to do is to spin up a temporary thread
4841 // to handle private state thread events while we are fielding public
4843 LLDB_LOGF(log
, "Running thread plan on private state thread, spinning up "
4844 "another state thread to handle the events.");
4846 backup_private_state_thread
= m_private_state_thread
;
4848 // One other bit of business: we want to run just this thread plan and
4849 // anything it pushes, and then stop, returning control here. But in the
4850 // normal course of things, the plan above us on the stack would be given a
4851 // shot at the stop event before deciding to stop, and we don't want that.
4852 // So we insert a "stopper" base plan on the stack before the plan we want
4853 // to run. Since base plans always stop and return control to the user,
4854 // that will do just what we want.
4855 stopper_base_plan_sp
.reset(new ThreadPlanBase(*thread
));
4856 thread
->QueueThreadPlan(stopper_base_plan_sp
, false);
4857 // Have to make sure our public state is stopped, since otherwise the
4858 // reporting logic below doesn't work correctly.
4859 old_state
= m_public_state
.GetValue();
4860 m_public_state
.SetValueNoLock(eStateStopped
);
4862 // Now spin up the private state thread:
4863 StartPrivateStateThread(true);
4866 thread
->QueueThreadPlan(
4867 thread_plan_sp
, false); // This used to pass "true" does that make sense?
4869 if (options
.GetDebug()) {
4870 // In this case, we aren't actually going to run, we just want to stop
4871 // right away. Flush this thread so we will refetch the stacks and show the
4872 // correct backtrace.
4873 // FIXME: To make this prettier we should invent some stop reason for this,
4875 // is only cosmetic, and this functionality is only of use to lldb
4876 // developers who can live with not pretty...
4878 return eExpressionStoppedForDebug
;
4881 ListenerSP
listener_sp(
4882 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
4884 lldb::EventSP event_to_broadcast_sp
;
4887 // This process event hijacker Hijacks the Public events and its destructor
4888 // makes sure that the process events get restored on exit to the function.
4890 // If the event needs to propagate beyond the hijacker (e.g., the process
4891 // exits during execution), then the event is put into
4892 // event_to_broadcast_sp for rebroadcasting.
4894 ProcessEventHijacker
run_thread_plan_hijacker(*this, listener_sp
);
4898 thread_plan_sp
->GetDescription(&s
, lldb::eDescriptionLevelVerbose
);
4900 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
4901 " to run thread plan \"%s\".",
4902 thread_idx_id
, expr_thread_id
, s
.GetData());
4906 lldb::EventSP event_sp
;
4907 lldb::StateType stop_state
= lldb::eStateInvalid
;
4909 bool before_first_timeout
= true; // This is set to false the first time
4910 // that we have to halt the target.
4911 bool do_resume
= true;
4912 bool handle_running_event
= true;
4914 // This is just for accounting:
4915 uint32_t num_resumes
= 0;
4917 // If we are going to run all threads the whole time, or if we are only
4918 // going to run one thread, then we don't need the first timeout. So we
4919 // pretend we are after the first timeout already.
4920 if (!options
.GetStopOthers() || !options
.GetTryAllThreads())
4921 before_first_timeout
= false;
4923 LLDB_LOGF(log
, "Stop others: %u, try all: %u, before_first: %u.\n",
4924 options
.GetStopOthers(), options
.GetTryAllThreads(),
4925 before_first_timeout
);
4927 // This isn't going to work if there are unfetched events on the queue. Are
4928 // there cases where we might want to run the remaining events here, and
4929 // then try to call the function? That's probably being too tricky for our
4932 Event
*other_events
= listener_sp
->PeekAtNextEvent();
4933 if (other_events
!= nullptr) {
4934 diagnostic_manager
.PutString(
4935 eDiagnosticSeverityError
,
4936 "RunThreadPlan called with pending events on the queue.");
4937 return eExpressionSetupError
;
4940 // We also need to make sure that the next event is delivered. We might be
4941 // calling a function as part of a thread plan, in which case the last
4942 // delivered event could be the running event, and we don't want event
4943 // coalescing to cause us to lose OUR running event...
4944 ForceNextEventDelivery();
4946 // This while loop must exit out the bottom, there's cleanup that we need to do
4947 // when we are done. So don't call return anywhere within it.
4949 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
4950 // It's pretty much impossible to write test cases for things like: One
4951 // thread timeout expires, I go to halt, but the process already stopped on
4952 // the function call stop breakpoint. Turning on this define will make us
4953 // not fetch the first event till after the halt. So if you run a quick
4954 // function, it will have completed, and the completion event will be
4955 // waiting, when you interrupt for halt. The expression evaluation should
4957 bool miss_first_event
= true;
4960 // We usually want to resume the process if we get to the top of the
4961 // loop. The only exception is if we get two running events with no
4962 // intervening stop, which can happen, we will just wait for then next
4965 "Top of while loop: do_resume: %i handle_running_event: %i "
4966 "before_first_timeout: %i.",
4967 do_resume
, handle_running_event
, before_first_timeout
);
4969 if (do_resume
|| handle_running_event
) {
4970 // Do the initial resume and wait for the running event before going
4975 Status resume_error
= PrivateResume();
4976 if (!resume_error
.Success()) {
4977 diagnostic_manager
.Printf(
4978 eDiagnosticSeverityError
,
4979 "couldn't resume inferior the %d time: \"%s\".", num_resumes
,
4980 resume_error
.AsCString());
4981 return_value
= eExpressionSetupError
;
4987 listener_sp
->GetEvent(event_sp
, GetUtilityExpressionTimeout());
4990 "Process::RunThreadPlan(): didn't get any event after "
4991 "resume %" PRIu32
", exiting.",
4994 diagnostic_manager
.Printf(eDiagnosticSeverityError
,
4995 "didn't get any event after resume %" PRIu32
4998 return_value
= eExpressionSetupError
;
5003 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
5005 if (stop_state
!= eStateRunning
) {
5006 bool restarted
= false;
5008 if (stop_state
== eStateStopped
) {
5009 restarted
= Process::ProcessEventData::GetRestartedFromEvent(
5013 "Process::RunThreadPlan(): didn't get running event after "
5014 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5015 "handle_running_event: %i).",
5016 num_resumes
, StateAsCString(stop_state
), restarted
, do_resume
,
5017 handle_running_event
);
5021 // This is probably an overabundance of caution, I don't think I
5022 // should ever get a stopped & restarted event here. But if I do,
5023 // the best thing is to Halt and then get out of here.
5024 const bool clear_thread_plans
= false;
5025 const bool use_run_lock
= false;
5026 Halt(clear_thread_plans
, use_run_lock
);
5029 diagnostic_manager
.Printf(
5030 eDiagnosticSeverityError
,
5031 "didn't get running event after initial resume, got %s instead.",
5032 StateAsCString(stop_state
));
5033 return_value
= eExpressionSetupError
;
5038 log
->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5039 // We need to call the function synchronously, so spin waiting for it
5040 // to return. If we get interrupted while executing, we're going to
5041 // lose our context, and won't be able to gather the result at this
5042 // point. We set the timeout AFTER the resume, since the resume takes
5043 // some time and we don't want to charge that to the timeout.
5046 log
->PutCString("Process::RunThreadPlan(): waiting for next event.");
5050 handle_running_event
= true;
5052 // Now wait for the process to stop again:
5055 Timeout
<std::micro
> timeout
=
5056 GetExpressionTimeout(options
, before_first_timeout
);
5059 auto now
= system_clock::now();
5061 "Process::RunThreadPlan(): about to wait - now is %s - "
5063 llvm::to_string(now
).c_str(),
5064 llvm::to_string(now
+ *timeout
).c_str());
5066 LLDB_LOGF(log
, "Process::RunThreadPlan(): about to wait forever.");
5070 #ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5071 // See comment above...
5072 if (miss_first_event
) {
5073 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5074 miss_first_event
= false;
5078 got_event
= listener_sp
->GetEvent(event_sp
, timeout
);
5082 bool keep_going
= false;
5083 if (event_sp
->GetType() == eBroadcastBitInterrupt
) {
5084 const bool clear_thread_plans
= false;
5085 const bool use_run_lock
= false;
5086 Halt(clear_thread_plans
, use_run_lock
);
5087 return_value
= eExpressionInterrupted
;
5088 diagnostic_manager
.PutString(eDiagnosticSeverityRemark
,
5089 "execution halted by user interrupt.");
5090 LLDB_LOGF(log
, "Process::RunThreadPlan(): Got interrupted by "
5091 "eBroadcastBitInterrupted, exiting.");
5095 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
5097 "Process::RunThreadPlan(): in while loop, got event: %s.",
5098 StateAsCString(stop_state
));
5100 switch (stop_state
) {
5101 case lldb::eStateStopped
: {
5102 if (Process::ProcessEventData::GetRestartedFromEvent(
5104 // If we were restarted, we just need to go back up to fetch
5106 LLDB_LOGF(log
, "Process::RunThreadPlan(): Got a stop and "
5107 "restart, so we'll continue waiting.");
5110 handle_running_event
= true;
5112 const bool handle_interrupts
= true;
5113 return_value
= *HandleStoppedEvent(
5114 expr_thread_id
, thread_plan_sp
, thread_plan_restorer
,
5115 event_sp
, event_to_broadcast_sp
, options
,
5117 if (return_value
== eExpressionThreadVanished
)
5122 case lldb::eStateRunning
:
5123 // This shouldn't really happen, but sometimes we do get two
5124 // running events without an intervening stop, and in that case
5125 // we should just go back to waiting for the stop.
5128 handle_running_event
= false;
5133 "Process::RunThreadPlan(): execution stopped with "
5134 "unexpected state: %s.",
5135 StateAsCString(stop_state
));
5137 if (stop_state
== eStateExited
)
5138 event_to_broadcast_sp
= event_sp
;
5140 diagnostic_manager
.PutString(
5141 eDiagnosticSeverityError
,
5142 "execution stopped with unexpected state.");
5143 return_value
= eExpressionInterrupted
;
5154 log
->PutCString("Process::RunThreadPlan(): got_event was true, but "
5155 "the event pointer was null. How odd...");
5156 return_value
= eExpressionInterrupted
;
5160 // If we didn't get an event that means we've timed out... We will
5161 // interrupt the process here. Depending on what we were asked to do
5162 // we will either exit, or try with all threads running for the same
5166 if (options
.GetTryAllThreads()) {
5167 if (before_first_timeout
) {
5169 "Running function with one thread timeout timed out.");
5171 LLDB_LOG(log
, "Restarting function with all threads enabled and "
5172 "timeout: {0} timed out, abandoning execution.",
5175 LLDB_LOG(log
, "Running function with timeout: {0} timed out, "
5176 "abandoning execution.",
5180 // It is possible that between the time we issued the Halt, and we get
5181 // around to calling Halt the target could have stopped. That's fine,
5182 // Halt will figure that out and send the appropriate Stopped event.
5183 // BUT it is also possible that we stopped & restarted (e.g. hit a
5184 // signal with "stop" set to false.) In
5185 // that case, we'll get the stopped & restarted event, and we should go
5186 // back to waiting for the Halt's stopped event. That's what this
5189 bool back_to_top
= true;
5190 uint32_t try_halt_again
= 0;
5191 bool do_halt
= true;
5192 const uint32_t num_retries
= 5;
5193 while (try_halt_again
< num_retries
) {
5196 LLDB_LOGF(log
, "Process::RunThreadPlan(): Running Halt.");
5197 const bool clear_thread_plans
= false;
5198 const bool use_run_lock
= false;
5199 Halt(clear_thread_plans
, use_run_lock
);
5201 if (halt_error
.Success()) {
5203 log
->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5206 listener_sp
->GetEvent(event_sp
, GetUtilityExpressionTimeout());
5210 Process::ProcessEventData::GetStateFromEvent(event_sp
.get());
5213 "Process::RunThreadPlan(): Stopped with event: %s",
5214 StateAsCString(stop_state
));
5215 if (stop_state
== lldb::eStateStopped
&&
5216 Process::ProcessEventData::GetInterruptedFromEvent(
5218 log
->PutCString(" Event was the Halt interruption event.");
5221 if (stop_state
== lldb::eStateStopped
) {
5222 if (Process::ProcessEventData::GetRestartedFromEvent(
5225 log
->PutCString("Process::RunThreadPlan(): Went to halt "
5226 "but got a restarted event, there must be "
5227 "an un-restarted stopped event so try "
5229 "Exiting wait loop.");
5235 // Between the time we initiated the Halt and the time we
5236 // delivered it, the process could have already finished its
5237 // job. Check that here:
5238 const bool handle_interrupts
= false;
5239 if (auto result
= HandleStoppedEvent(
5240 expr_thread_id
, thread_plan_sp
, thread_plan_restorer
,
5241 event_sp
, event_to_broadcast_sp
, options
,
5242 handle_interrupts
)) {
5243 return_value
= *result
;
5244 back_to_top
= false;
5248 if (!options
.GetTryAllThreads()) {
5250 log
->PutCString("Process::RunThreadPlan(): try_all_threads "
5251 "was false, we stopped so now we're "
5253 return_value
= eExpressionInterrupted
;
5254 back_to_top
= false;
5258 if (before_first_timeout
) {
5259 // Set all the other threads to run, and return to the top of
5260 // the loop, which will continue;
5261 before_first_timeout
= false;
5262 thread_plan_sp
->SetStopOthers(false);
5265 "Process::RunThreadPlan(): about to resume.");
5270 // Running all threads failed, so return Interrupted.
5272 log
->PutCString("Process::RunThreadPlan(): running all "
5273 "threads timed out.");
5274 return_value
= eExpressionInterrupted
;
5275 back_to_top
= false;
5281 log
->PutCString("Process::RunThreadPlan(): halt said it "
5282 "succeeded, but I got no event. "
5283 "I'm getting out of here passing Interrupted.");
5284 return_value
= eExpressionInterrupted
;
5285 back_to_top
= false;
5294 if (!back_to_top
|| try_halt_again
> num_retries
)
5301 // If we had to start up a temporary private state thread to run this
5302 // thread plan, shut it down now.
5303 if (backup_private_state_thread
.IsJoinable()) {
5304 StopPrivateStateThread();
5306 m_private_state_thread
= backup_private_state_thread
;
5307 if (stopper_base_plan_sp
) {
5308 thread
->DiscardThreadPlansUpToPlan(stopper_base_plan_sp
);
5310 if (old_state
!= eStateInvalid
)
5311 m_public_state
.SetValueNoLock(old_state
);
5314 // If our thread went away on us, we need to get out of here without
5315 // doing any more work. We don't have to clean up the thread plan, that
5316 // will have happened when the Thread was destroyed.
5317 if (return_value
== eExpressionThreadVanished
) {
5318 return return_value
;
5321 if (return_value
!= eExpressionCompleted
&& log
) {
5322 // Print a backtrace into the log so we can figure out where we are:
5324 s
.PutCString("Thread state after unsuccessful completion: \n");
5325 thread
->GetStackFrameStatus(s
, 0, UINT32_MAX
, true, UINT32_MAX
);
5326 log
->PutString(s
.GetString());
5328 // Restore the thread state if we are going to discard the plan execution.
5329 // There are three cases where this could happen: 1) The execution
5330 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5331 // was true 3) We got some other error, and discard_on_error was true
5332 bool should_unwind
= (return_value
== eExpressionInterrupted
&&
5333 options
.DoesUnwindOnError()) ||
5334 (return_value
== eExpressionHitBreakpoint
&&
5335 options
.DoesIgnoreBreakpoints());
5337 if (return_value
== eExpressionCompleted
|| should_unwind
) {
5338 thread_plan_sp
->RestoreThreadState();
5341 // Now do some processing on the results of the run:
5342 if (return_value
== eExpressionInterrupted
||
5343 return_value
== eExpressionHitBreakpoint
) {
5349 log
->PutCString("Process::RunThreadPlan(): Stop event that "
5350 "interrupted us is NULL.");
5355 const char *event_explanation
= nullptr;
5359 event_explanation
= "<no event>";
5361 } else if (event_sp
->GetType() == eBroadcastBitInterrupt
) {
5362 event_explanation
= "<user interrupt>";
5365 const Process::ProcessEventData
*event_data
=
5366 Process::ProcessEventData::GetEventDataFromEvent(
5370 event_explanation
= "<no event data>";
5374 Process
*process
= event_data
->GetProcessSP().get();
5377 event_explanation
= "<no process>";
5381 ThreadList
&thread_list
= process
->GetThreadList();
5383 uint32_t num_threads
= thread_list
.GetSize();
5384 uint32_t thread_index
;
5386 ts
.Printf("<%u threads> ", num_threads
);
5388 for (thread_index
= 0; thread_index
< num_threads
; ++thread_index
) {
5389 Thread
*thread
= thread_list
.GetThreadAtIndex(thread_index
).get();
5396 ts
.Printf("<0x%4.4" PRIx64
" ", thread
->GetID());
5397 RegisterContext
*register_context
=
5398 thread
->GetRegisterContext().get();
5400 if (register_context
)
5401 ts
.Printf("[ip 0x%" PRIx64
"] ", register_context
->GetPC());
5403 ts
.Printf("[ip unknown] ");
5405 // Show the private stop info here, the public stop info will be
5406 // from the last natural stop.
5407 lldb::StopInfoSP stop_info_sp
= thread
->GetPrivateStopInfo();
5409 const char *stop_desc
= stop_info_sp
->GetDescription();
5411 ts
.PutCString(stop_desc
);
5416 event_explanation
= ts
.GetData();
5420 if (event_explanation
)
5422 "Process::RunThreadPlan(): execution interrupted: %s %s",
5423 s
.GetData(), event_explanation
);
5425 LLDB_LOGF(log
, "Process::RunThreadPlan(): execution interrupted: %s",
5429 if (should_unwind
) {
5431 "Process::RunThreadPlan: ExecutionInterrupted - "
5432 "discarding thread plans up to %p.",
5433 static_cast<void *>(thread_plan_sp
.get()));
5434 thread
->DiscardThreadPlansUpToPlan(thread_plan_sp
);
5437 "Process::RunThreadPlan: ExecutionInterrupted - for "
5438 "plan: %p not discarding.",
5439 static_cast<void *>(thread_plan_sp
.get()));
5441 } else if (return_value
== eExpressionSetupError
) {
5443 log
->PutCString("Process::RunThreadPlan(): execution set up error.");
5445 if (options
.DoesUnwindOnError()) {
5446 thread
->DiscardThreadPlansUpToPlan(thread_plan_sp
);
5449 if (thread
->IsThreadPlanDone(thread_plan_sp
.get())) {
5451 log
->PutCString("Process::RunThreadPlan(): thread plan is done");
5452 return_value
= eExpressionCompleted
;
5453 } else if (thread
->WasThreadPlanDiscarded(thread_plan_sp
.get())) {
5456 "Process::RunThreadPlan(): thread plan was discarded");
5457 return_value
= eExpressionDiscarded
;
5461 "Process::RunThreadPlan(): thread plan stopped in mid course");
5462 if (options
.DoesUnwindOnError() && thread_plan_sp
) {
5464 log
->PutCString("Process::RunThreadPlan(): discarding thread plan "
5465 "'cause unwind_on_error is set.");
5466 thread
->DiscardThreadPlansUpToPlan(thread_plan_sp
);
5471 // Thread we ran the function in may have gone away because we ran the
5472 // target Check that it's still there, and if it is put it back in the
5473 // context. Also restore the frame in the context if it is still present.
5474 thread
= GetThreadList().FindThreadByIndexID(thread_idx_id
, true).get();
5476 exe_ctx
.SetFrameSP(thread
->GetFrameWithStackID(ctx_frame_id
));
5479 // Also restore the current process'es selected frame & thread, since this
5480 // function calling may be done behind the user's back.
5482 if (selected_tid
!= LLDB_INVALID_THREAD_ID
) {
5483 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid
) &&
5484 selected_stack_id
.IsValid()) {
5485 // We were able to restore the selected thread, now restore the frame:
5486 std::lock_guard
<std::recursive_mutex
> guard(GetThreadList().GetMutex());
5487 StackFrameSP old_frame_sp
=
5488 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
5491 GetThreadList().GetSelectedThread()->SetSelectedFrame(
5492 old_frame_sp
.get());
5497 // If the process exited during the run of the thread plan, notify everyone.
5499 if (event_to_broadcast_sp
) {
5501 log
->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
5502 BroadcastEvent(event_to_broadcast_sp
);
5505 return return_value
;
5508 const char *Process::ExecutionResultAsCString(ExpressionResults result
) {
5509 const char *result_name
= "<unknown>";
5512 case eExpressionCompleted
:
5513 result_name
= "eExpressionCompleted";
5515 case eExpressionDiscarded
:
5516 result_name
= "eExpressionDiscarded";
5518 case eExpressionInterrupted
:
5519 result_name
= "eExpressionInterrupted";
5521 case eExpressionHitBreakpoint
:
5522 result_name
= "eExpressionHitBreakpoint";
5524 case eExpressionSetupError
:
5525 result_name
= "eExpressionSetupError";
5527 case eExpressionParseError
:
5528 result_name
= "eExpressionParseError";
5530 case eExpressionResultUnavailable
:
5531 result_name
= "eExpressionResultUnavailable";
5533 case eExpressionTimedOut
:
5534 result_name
= "eExpressionTimedOut";
5536 case eExpressionStoppedForDebug
:
5537 result_name
= "eExpressionStoppedForDebug";
5539 case eExpressionThreadVanished
:
5540 result_name
= "eExpressionThreadVanished";
5545 void Process::GetStatus(Stream
&strm
) {
5546 const StateType state
= GetState();
5547 if (StateIsStoppedState(state
, false)) {
5548 if (state
== eStateExited
) {
5549 int exit_status
= GetExitStatus();
5550 const char *exit_description
= GetExitDescription();
5551 strm
.Printf("Process %" PRIu64
" exited with status = %i (0x%8.8x) %s\n",
5552 GetID(), exit_status
, exit_status
,
5553 exit_description
? exit_description
: "");
5555 if (state
== eStateConnected
)
5556 strm
.Printf("Connected to remote target.\n");
5558 strm
.Printf("Process %" PRIu64
" %s\n", GetID(), StateAsCString(state
));
5561 strm
.Printf("Process %" PRIu64
" is running.\n", GetID());
5565 size_t Process::GetThreadStatus(Stream
&strm
,
5566 bool only_threads_with_stop_reason
,
5567 uint32_t start_frame
, uint32_t num_frames
,
5568 uint32_t num_frames_with_source
,
5570 size_t num_thread_infos_dumped
= 0;
5572 // You can't hold the thread list lock while calling Thread::GetStatus. That
5573 // very well might run code (e.g. if we need it to get return values or
5574 // arguments.) For that to work the process has to be able to acquire it.
5575 // So instead copy the thread ID's, and look them up one by one:
5577 uint32_t num_threads
;
5578 std::vector
<lldb::tid_t
> thread_id_array
;
5579 // Scope for thread list locker;
5581 std::lock_guard
<std::recursive_mutex
> guard(GetThreadList().GetMutex());
5582 ThreadList
&curr_thread_list
= GetThreadList();
5583 num_threads
= curr_thread_list
.GetSize();
5585 thread_id_array
.resize(num_threads
);
5586 for (idx
= 0; idx
< num_threads
; ++idx
)
5587 thread_id_array
[idx
] = curr_thread_list
.GetThreadAtIndex(idx
)->GetID();
5590 for (uint32_t i
= 0; i
< num_threads
; i
++) {
5591 ThreadSP
thread_sp(GetThreadList().FindThreadByID(thread_id_array
[i
]));
5593 if (only_threads_with_stop_reason
) {
5594 StopInfoSP stop_info_sp
= thread_sp
->GetStopInfo();
5595 if (!stop_info_sp
|| !stop_info_sp
->IsValid())
5598 thread_sp
->GetStatus(strm
, start_frame
, num_frames
,
5599 num_frames_with_source
,
5601 ++num_thread_infos_dumped
;
5603 Log
*log
= GetLog(LLDBLog::Process
);
5604 LLDB_LOGF(log
, "Process::GetThreadStatus - thread 0x" PRIu64
5605 " vanished while running Thread::GetStatus.");
5608 return num_thread_infos_dumped
;
5611 void Process::AddInvalidMemoryRegion(const LoadRange
®ion
) {
5612 m_memory_cache
.AddInvalidRange(region
.GetRangeBase(), region
.GetByteSize());
5615 bool Process::RemoveInvalidMemoryRange(const LoadRange
®ion
) {
5616 return m_memory_cache
.RemoveInvalidRange(region
.GetRangeBase(),
5617 region
.GetByteSize());
5620 void Process::AddPreResumeAction(PreResumeActionCallback callback
,
5622 m_pre_resume_actions
.push_back(PreResumeCallbackAndBaton(callback
, baton
));
5625 bool Process::RunPreResumeActions() {
5627 while (!m_pre_resume_actions
.empty()) {
5628 struct PreResumeCallbackAndBaton action
= m_pre_resume_actions
.back();
5629 m_pre_resume_actions
.pop_back();
5630 bool this_result
= action
.callback(action
.baton
);
5632 result
= this_result
;
5637 void Process::ClearPreResumeActions() { m_pre_resume_actions
.clear(); }
5639 void Process::ClearPreResumeAction(PreResumeActionCallback callback
, void *baton
)
5641 PreResumeCallbackAndBaton
element(callback
, baton
);
5642 auto found_iter
= std::find(m_pre_resume_actions
.begin(), m_pre_resume_actions
.end(), element
);
5643 if (found_iter
!= m_pre_resume_actions
.end())
5645 m_pre_resume_actions
.erase(found_iter
);
5649 ProcessRunLock
&Process::GetRunLock() {
5650 if (m_private_state_thread
.EqualsThread(Host::GetCurrentThread()))
5651 return m_private_run_lock
;
5653 return m_public_run_lock
;
5656 bool Process::CurrentThreadIsPrivateStateThread()
5658 return m_private_state_thread
.EqualsThread(Host::GetCurrentThread());
5662 void Process::Flush() {
5663 m_thread_list
.Flush();
5664 m_extended_thread_list
.Flush();
5665 m_extended_thread_stop_id
= 0;
5666 m_queue_list
.Clear();
5667 m_queue_list_stop_id
= 0;
5670 lldb::addr_t
Process::GetCodeAddressMask() {
5671 if (uint32_t num_bits_setting
= GetVirtualAddressableBits())
5672 return ~((1ULL << num_bits_setting
) - 1);
5674 return m_code_address_mask
;
5677 lldb::addr_t
Process::GetDataAddressMask() {
5678 if (uint32_t num_bits_setting
= GetVirtualAddressableBits())
5679 return ~((1ULL << num_bits_setting
) - 1);
5681 return m_data_address_mask
;
5684 lldb::addr_t
Process::GetHighmemCodeAddressMask() {
5685 if (uint32_t num_bits_setting
= GetHighmemVirtualAddressableBits())
5686 return ~((1ULL << num_bits_setting
) - 1);
5687 return GetCodeAddressMask();
5690 lldb::addr_t
Process::GetHighmemDataAddressMask() {
5691 if (uint32_t num_bits_setting
= GetHighmemVirtualAddressableBits())
5692 return ~((1ULL << num_bits_setting
) - 1);
5693 return GetDataAddressMask();
5696 void Process::SetCodeAddressMask(lldb::addr_t code_address_mask
) {
5697 LLDB_LOG(GetLog(LLDBLog::Process
),
5698 "Setting Process code address mask to {0:x}", code_address_mask
);
5699 m_code_address_mask
= code_address_mask
;
5702 void Process::SetDataAddressMask(lldb::addr_t data_address_mask
) {
5703 LLDB_LOG(GetLog(LLDBLog::Process
),
5704 "Setting Process data address mask to {0:x}", data_address_mask
);
5705 m_data_address_mask
= data_address_mask
;
5708 void Process::SetHighmemCodeAddressMask(lldb::addr_t code_address_mask
) {
5709 LLDB_LOG(GetLog(LLDBLog::Process
),
5710 "Setting Process highmem code address mask to {0:x}",
5712 m_highmem_code_address_mask
= code_address_mask
;
5715 void Process::SetHighmemDataAddressMask(lldb::addr_t data_address_mask
) {
5716 LLDB_LOG(GetLog(LLDBLog::Process
),
5717 "Setting Process highmem data address mask to {0:x}",
5719 m_highmem_data_address_mask
= data_address_mask
;
5722 addr_t
Process::FixCodeAddress(addr_t addr
) {
5723 if (ABISP abi_sp
= GetABI())
5724 addr
= abi_sp
->FixCodeAddress(addr
);
5728 addr_t
Process::FixDataAddress(addr_t addr
) {
5729 if (ABISP abi_sp
= GetABI())
5730 addr
= abi_sp
->FixDataAddress(addr
);
5734 addr_t
Process::FixAnyAddress(addr_t addr
) {
5735 if (ABISP abi_sp
= GetABI())
5736 addr
= abi_sp
->FixAnyAddress(addr
);
5740 void Process::DidExec() {
5741 Log
*log
= GetLog(LLDBLog::Process
);
5742 LLDB_LOGF(log
, "Process::%s()", __FUNCTION__
);
5744 Target
&target
= GetTarget();
5745 target
.CleanupProcess();
5746 target
.ClearModules(false);
5747 m_dynamic_checkers_up
.reset();
5749 m_system_runtime_up
.reset();
5752 m_jit_loaders_up
.reset();
5753 m_image_tokens
.clear();
5754 // After an exec, the inferior is a new process and these memory regions are
5755 // no longer allocated.
5756 m_allocated_memory_cache
.Clear(/*deallocte_memory=*/false);
5758 std::lock_guard
<std::recursive_mutex
> guard(m_language_runtimes_mutex
);
5759 m_language_runtimes
.clear();
5761 m_instrumentation_runtimes
.clear();
5762 m_thread_list
.DiscardThreadPlans();
5763 m_memory_cache
.Clear(true);
5766 // Flush the process (threads and all stack frames) after running
5767 // CompleteAttach() in case the dynamic loader loaded things in new
5771 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
5772 // let the target know so it can do any cleanup it needs to.
5776 addr_t
Process::ResolveIndirectFunction(const Address
*address
, Status
&error
) {
5777 if (address
== nullptr) {
5778 error
.SetErrorString("Invalid address argument");
5779 return LLDB_INVALID_ADDRESS
;
5782 addr_t function_addr
= LLDB_INVALID_ADDRESS
;
5784 addr_t addr
= address
->GetLoadAddress(&GetTarget());
5785 std::map
<addr_t
, addr_t
>::const_iterator iter
=
5786 m_resolved_indirect_addresses
.find(addr
);
5787 if (iter
!= m_resolved_indirect_addresses
.end()) {
5788 function_addr
= (*iter
).second
;
5790 if (!CallVoidArgVoidPtrReturn(address
, function_addr
)) {
5791 Symbol
*symbol
= address
->CalculateSymbolContextSymbol();
5792 error
.SetErrorStringWithFormat(
5793 "Unable to call resolver for indirect function %s",
5794 symbol
? symbol
->GetName().AsCString() : "<UNKNOWN>");
5795 function_addr
= LLDB_INVALID_ADDRESS
;
5797 if (ABISP abi_sp
= GetABI())
5798 function_addr
= abi_sp
->FixCodeAddress(function_addr
);
5799 m_resolved_indirect_addresses
.insert(
5800 std::pair
<addr_t
, addr_t
>(addr
, function_addr
));
5803 return function_addr
;
5806 void Process::ModulesDidLoad(ModuleList
&module_list
) {
5807 // Inform the system runtime of the modified modules.
5808 SystemRuntime
*sys_runtime
= GetSystemRuntime();
5810 sys_runtime
->ModulesDidLoad(module_list
);
5812 GetJITLoaders().ModulesDidLoad(module_list
);
5814 // Give the instrumentation runtimes a chance to be created before informing
5815 // them of the modified modules.
5816 InstrumentationRuntime::ModulesDidLoad(module_list
, this,
5817 m_instrumentation_runtimes
);
5818 for (auto &runtime
: m_instrumentation_runtimes
)
5819 runtime
.second
->ModulesDidLoad(module_list
);
5821 // Give the language runtimes a chance to be created before informing them of
5822 // the modified modules.
5823 for (const lldb::LanguageType lang_type
: Language::GetSupportedLanguages()) {
5824 if (LanguageRuntime
*runtime
= GetLanguageRuntime(lang_type
))
5825 runtime
->ModulesDidLoad(module_list
);
5828 // If we don't have an operating system plug-in, try to load one since
5829 // loading shared libraries might cause a new one to try and load
5831 LoadOperatingSystemPlugin(false);
5833 // Inform the structured-data plugins of the modified modules.
5834 for (auto &pair
: m_structured_data_plugin_map
) {
5836 pair
.second
->ModulesDidLoad(*this, module_list
);
5840 void Process::PrintWarningOptimization(const SymbolContext
&sc
) {
5841 if (!GetWarningsOptimization())
5843 if (!sc
.module_sp
|| !sc
.function
|| !sc
.function
->GetIsOptimized())
5845 sc
.module_sp
->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
5848 void Process::PrintWarningUnsupportedLanguage(const SymbolContext
&sc
) {
5849 if (!GetWarningsUnsupportedLanguage())
5853 LanguageType language
= sc
.GetLanguage();
5854 if (language
== eLanguageTypeUnknown
)
5856 LanguageSet plugins
=
5857 PluginManager::GetAllTypeSystemSupportedLanguagesForTypes();
5858 if (plugins
[language
])
5860 sc
.module_sp
->ReportWarningUnsupportedLanguage(
5861 language
, GetTarget().GetDebugger().GetID());
5864 bool Process::GetProcessInfo(ProcessInstanceInfo
&info
) {
5867 PlatformSP platform_sp
= GetTarget().GetPlatform();
5871 return platform_sp
->GetProcessInfo(GetID(), info
);
5874 ThreadCollectionSP
Process::GetHistoryThreads(lldb::addr_t addr
) {
5875 ThreadCollectionSP threads
;
5877 const MemoryHistorySP
&memory_history
=
5878 MemoryHistory::FindPlugin(shared_from_this());
5880 if (!memory_history
) {
5884 threads
= std::make_shared
<ThreadCollection
>(
5885 memory_history
->GetHistoryThreads(addr
));
5890 InstrumentationRuntimeSP
5891 Process::GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type
) {
5892 InstrumentationRuntimeCollection::iterator pos
;
5893 pos
= m_instrumentation_runtimes
.find(type
);
5894 if (pos
== m_instrumentation_runtimes
.end()) {
5895 return InstrumentationRuntimeSP();
5897 return (*pos
).second
;
5900 bool Process::GetModuleSpec(const FileSpec
&module_file_spec
,
5901 const ArchSpec
&arch
, ModuleSpec
&module_spec
) {
5902 module_spec
.Clear();
5906 size_t Process::AddImageToken(lldb::addr_t image_ptr
) {
5907 m_image_tokens
.push_back(image_ptr
);
5908 return m_image_tokens
.size() - 1;
5911 lldb::addr_t
Process::GetImagePtrFromToken(size_t token
) const {
5912 if (token
< m_image_tokens
.size())
5913 return m_image_tokens
[token
];
5914 return LLDB_INVALID_IMAGE_TOKEN
;
5917 void Process::ResetImageToken(size_t token
) {
5918 if (token
< m_image_tokens
.size())
5919 m_image_tokens
[token
] = LLDB_INVALID_IMAGE_TOKEN
;
5923 Process::AdvanceAddressToNextBranchInstruction(Address default_stop_addr
,
5924 AddressRange range_bounds
) {
5925 Target
&target
= GetTarget();
5926 DisassemblerSP disassembler_sp
;
5927 InstructionList
*insn_list
= nullptr;
5929 Address retval
= default_stop_addr
;
5931 if (!target
.GetUseFastStepping())
5933 if (!default_stop_addr
.IsValid())
5936 const char *plugin_name
= nullptr;
5937 const char *flavor
= nullptr;
5938 disassembler_sp
= Disassembler::DisassembleRange(
5939 target
.GetArchitecture(), plugin_name
, flavor
, GetTarget(), range_bounds
);
5940 if (disassembler_sp
)
5941 insn_list
= &disassembler_sp
->GetInstructionList();
5943 if (insn_list
== nullptr) {
5947 size_t insn_offset
=
5948 insn_list
->GetIndexOfInstructionAtAddress(default_stop_addr
);
5949 if (insn_offset
== UINT32_MAX
) {
5953 uint32_t branch_index
= insn_list
->GetIndexOfNextBranchInstruction(
5954 insn_offset
, false /* ignore_calls*/, nullptr);
5955 if (branch_index
== UINT32_MAX
) {
5959 if (branch_index
> insn_offset
) {
5960 Address next_branch_insn_address
=
5961 insn_list
->GetInstructionAtIndex(branch_index
)->GetAddress();
5962 if (next_branch_insn_address
.IsValid() &&
5963 range_bounds
.ContainsFileAddress(next_branch_insn_address
)) {
5964 retval
= next_branch_insn_address
;
5971 Status
Process::GetMemoryRegionInfo(lldb::addr_t load_addr
,
5972 MemoryRegionInfo
&range_info
) {
5973 if (const lldb::ABISP
&abi
= GetABI())
5974 load_addr
= abi
->FixAnyAddress(load_addr
);
5975 return DoGetMemoryRegionInfo(load_addr
, range_info
);
5978 Status
Process::GetMemoryRegions(lldb_private::MemoryRegionInfos
®ion_list
) {
5981 lldb::addr_t range_end
= 0;
5982 const lldb::ABISP
&abi
= GetABI();
5984 region_list
.clear();
5986 lldb_private::MemoryRegionInfo region_info
;
5987 error
= GetMemoryRegionInfo(range_end
, region_info
);
5988 // GetMemoryRegionInfo should only return an error if it is unimplemented.
5990 region_list
.clear();
5994 // We only check the end address, not start and end, because we assume that
5995 // the start will not have non-address bits until the first unmappable
5996 // region. We will have exited the loop by that point because the previous
5997 // region, the last mappable region, will have non-address bits in its end
5999 range_end
= region_info
.GetRange().GetRangeEnd();
6000 if (region_info
.GetMapped() == MemoryRegionInfo::eYes
) {
6001 region_list
.push_back(std::move(region_info
));
6004 // For a process with no non-address bits, all address bits
6005 // set means the end of memory.
6006 range_end
!= LLDB_INVALID_ADDRESS
&&
6007 // If we have non-address bits and some are set then the end
6008 // is at or beyond the end of mappable memory.
6009 !(abi
&& (abi
->FixAnyAddress(range_end
) != range_end
)));
6015 Process::ConfigureStructuredData(llvm::StringRef type_name
,
6016 const StructuredData::ObjectSP
&config_sp
) {
6017 // If you get this, the Process-derived class needs to implement a method to
6018 // enable an already-reported asynchronous structured data feature. See
6019 // ProcessGDBRemote for an example implementation over gdb-remote.
6020 return Status("unimplemented");
6023 void Process::MapSupportedStructuredDataPlugins(
6024 const StructuredData::Array
&supported_type_names
) {
6025 Log
*log
= GetLog(LLDBLog::Process
);
6027 // Bail out early if there are no type names to map.
6028 if (supported_type_names
.GetSize() == 0) {
6029 LLDB_LOG(log
, "no structured data types supported");
6033 // These StringRefs are backed by the input parameter.
6034 std::set
<llvm::StringRef
> type_names
;
6037 "the process supports the following async structured data types:");
6039 supported_type_names
.ForEach(
6040 [&type_names
, &log
](StructuredData::Object
*object
) {
6041 // There shouldn't be null objects in the array.
6045 // All type names should be strings.
6046 const llvm::StringRef type_name
= object
->GetStringValue();
6047 if (type_name
.empty())
6050 type_names
.insert(type_name
);
6051 LLDB_LOG(log
, "- {0}", type_name
);
6055 // For each StructuredDataPlugin, if the plugin handles any of the types in
6056 // the supported_type_names, map that type name to that plugin. Stop when
6057 // we've consumed all the type names.
6058 // FIXME: should we return an error if there are type names nobody
6060 for (uint32_t plugin_index
= 0; !type_names
.empty(); plugin_index
++) {
6061 auto create_instance
=
6062 PluginManager::GetStructuredDataPluginCreateCallbackAtIndex(
6064 if (!create_instance
)
6067 // Create the plugin.
6068 StructuredDataPluginSP plugin_sp
= (*create_instance
)(*this);
6070 // This plugin doesn't think it can work with the process. Move on to the
6075 // For any of the remaining type names, map any that this plugin supports.
6076 std::vector
<llvm::StringRef
> names_to_remove
;
6077 for (llvm::StringRef type_name
: type_names
) {
6078 if (plugin_sp
->SupportsStructuredDataType(type_name
)) {
6079 m_structured_data_plugin_map
.insert(
6080 std::make_pair(type_name
, plugin_sp
));
6081 names_to_remove
.push_back(type_name
);
6082 LLDB_LOG(log
, "using plugin {0} for type name {1}",
6083 plugin_sp
->GetPluginName(), type_name
);
6087 // Remove the type names that were consumed by this plugin.
6088 for (llvm::StringRef type_name
: names_to_remove
)
6089 type_names
.erase(type_name
);
6093 bool Process::RouteAsyncStructuredData(
6094 const StructuredData::ObjectSP object_sp
) {
6095 // Nothing to do if there's no data.
6099 // The contract is this must be a dictionary, so we can look up the routing
6100 // key via the top-level 'type' string value within the dictionary.
6101 StructuredData::Dictionary
*dictionary
= object_sp
->GetAsDictionary();
6105 // Grab the async structured type name (i.e. the feature/plugin name).
6106 llvm::StringRef type_name
;
6107 if (!dictionary
->GetValueForKeyAsString("type", type_name
))
6110 // Check if there's a plugin registered for this type name.
6111 auto find_it
= m_structured_data_plugin_map
.find(type_name
);
6112 if (find_it
== m_structured_data_plugin_map
.end()) {
6113 // We don't have a mapping for this structured data type.
6117 // Route the structured data to the plugin.
6118 find_it
->second
->HandleArrivalOfStructuredData(*this, type_name
, object_sp
);
6122 Status
Process::UpdateAutomaticSignalFiltering() {
6123 // Default implementation does nothign.
6124 // No automatic signal filtering to speak of.
6128 UtilityFunction
*Process::GetLoadImageUtilityFunction(
6130 llvm::function_ref
<std::unique_ptr
<UtilityFunction
>()> factory
) {
6131 if (platform
!= GetTarget().GetPlatform().get())
6133 llvm::call_once(m_dlopen_utility_func_flag_once
,
6134 [&] { m_dlopen_utility_func_up
= factory(); });
6135 return m_dlopen_utility_func_up
.get();
6138 llvm::Expected
<TraceSupportedResponse
> Process::TraceSupported() {
6139 if (!IsLiveDebugSession())
6140 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6141 "Can't trace a non-live process.");
6142 return llvm::make_error
<UnimplementedError
>();
6145 bool Process::CallVoidArgVoidPtrReturn(const Address
*address
,
6146 addr_t
&returned_func
,
6147 bool trap_exceptions
) {
6148 Thread
*thread
= GetThreadList().GetExpressionExecutionThread().get();
6149 if (thread
== nullptr || address
== nullptr)
6152 EvaluateExpressionOptions options
;
6153 options
.SetStopOthers(true);
6154 options
.SetUnwindOnError(true);
6155 options
.SetIgnoreBreakpoints(true);
6156 options
.SetTryAllThreads(true);
6157 options
.SetDebug(false);
6158 options
.SetTimeout(GetUtilityExpressionTimeout());
6159 options
.SetTrapExceptions(trap_exceptions
);
6161 auto type_system_or_err
=
6162 GetTarget().GetScratchTypeSystemForLanguage(eLanguageTypeC
);
6163 if (!type_system_or_err
) {
6164 llvm::consumeError(type_system_or_err
.takeError());
6167 auto ts
= *type_system_or_err
;
6170 CompilerType void_ptr_type
=
6171 ts
->GetBasicTypeFromAST(eBasicTypeVoid
).GetPointerType();
6172 lldb::ThreadPlanSP
call_plan_sp(new ThreadPlanCallFunction(
6173 *thread
, *address
, void_ptr_type
, llvm::ArrayRef
<addr_t
>(), options
));
6175 DiagnosticManager diagnostics
;
6177 StackFrame
*frame
= thread
->GetStackFrameAtIndex(0).get();
6179 ExecutionContext exe_ctx
;
6180 frame
->CalculateExecutionContext(exe_ctx
);
6181 ExpressionResults result
=
6182 RunThreadPlan(exe_ctx
, call_plan_sp
, options
, diagnostics
);
6183 if (result
== eExpressionCompleted
) {
6185 call_plan_sp
->GetReturnValueObject()->GetValueAsUnsigned(
6186 LLDB_INVALID_ADDRESS
);
6188 if (GetAddressByteSize() == 4) {
6189 if (returned_func
== UINT32_MAX
)
6191 } else if (GetAddressByteSize() == 8) {
6192 if (returned_func
== UINT64_MAX
)
6203 llvm::Expected
<const MemoryTagManager
*> Process::GetMemoryTagManager() {
6204 Architecture
*arch
= GetTarget().GetArchitecturePlugin();
6205 const MemoryTagManager
*tag_manager
=
6206 arch
? arch
->GetMemoryTagManager() : nullptr;
6207 if (!arch
|| !tag_manager
) {
6208 return llvm::createStringError(
6209 llvm::inconvertibleErrorCode(),
6210 "This architecture does not support memory tagging");
6213 if (!SupportsMemoryTagging()) {
6214 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6215 "Process does not support memory tagging");
6221 llvm::Expected
<std::vector
<lldb::addr_t
>>
6222 Process::ReadMemoryTags(lldb::addr_t addr
, size_t len
) {
6223 llvm::Expected
<const MemoryTagManager
*> tag_manager_or_err
=
6224 GetMemoryTagManager();
6225 if (!tag_manager_or_err
)
6226 return tag_manager_or_err
.takeError();
6228 const MemoryTagManager
*tag_manager
= *tag_manager_or_err
;
6229 llvm::Expected
<std::vector
<uint8_t>> tag_data
=
6230 DoReadMemoryTags(addr
, len
, tag_manager
->GetAllocationTagType());
6232 return tag_data
.takeError();
6234 return tag_manager
->UnpackTagsData(*tag_data
,
6235 len
/ tag_manager
->GetGranuleSize());
6238 Status
Process::WriteMemoryTags(lldb::addr_t addr
, size_t len
,
6239 const std::vector
<lldb::addr_t
> &tags
) {
6240 llvm::Expected
<const MemoryTagManager
*> tag_manager_or_err
=
6241 GetMemoryTagManager();
6242 if (!tag_manager_or_err
)
6243 return Status(tag_manager_or_err
.takeError());
6245 const MemoryTagManager
*tag_manager
= *tag_manager_or_err
;
6246 llvm::Expected
<std::vector
<uint8_t>> packed_tags
=
6247 tag_manager
->PackTags(tags
);
6249 return Status(packed_tags
.takeError());
6252 return DoWriteMemoryTags(addr
, len
, tag_manager
->GetAllocationTagType(),