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