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->Printf("Target <unknown index>: (");
929 process_sp->GetTarget().Dump(stream, eDescriptionLevelBrief);
930 stream->Printf(") 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(addr_t addr, void *buf, size_t size, Status &error) {
2039 if (ABISP abi_sp = GetABI())
2040 addr = abi_sp->FixAnyAddress(addr);
2041
2042 error.Clear();
2043 if (!GetDisableMemoryCache()) {
2044#if defined(VERIFY_MEMORY_READS)
2045 // Memory caching is enabled, with debug verification
2046
2047 if (buf && size) {
2048 // Uncomment the line below to make sure memory caching is working.
2049 // I ran this through the test suite and got no assertions, so I am
2050 // pretty confident this is working well. If any changes are made to
2051 // memory caching, uncomment the line below and test your changes!
2052
2053 // Verify all memory reads by using the cache first, then redundantly
2054 // reading the same memory from the inferior and comparing to make sure
2055 // everything is exactly the same.
2056 std::string verify_buf(size, '\0');
2057 assert(verify_buf.size() == size);
2058 const size_t cache_bytes_read =
2059 m_memory_cache.Read(this, addr, buf, size, error);
2060 Status verify_error;
2061 const size_t verify_bytes_read =
2062 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2063 verify_buf.size(), verify_error);
2064 assert(cache_bytes_read == verify_bytes_read);
2065 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2066 assert(verify_error.Success() == error.Success());
2067 return cache_bytes_read;
2068 }
2069 return 0;
2070#else // !defined(VERIFY_MEMORY_READS)
2071 // Memory caching is enabled, without debug verification
2072
2073 return m_memory_cache.Read(addr, buf, size, error);
2074#endif // defined (VERIFY_MEMORY_READS)
2075 } else {
2076 // Memory caching is disabled
2077
2078 return ReadMemoryFromInferior(addr, buf, size, error);
2079 }
2080}
2081
2082llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2084 llvm::MutableArrayRef<uint8_t> buffer) {
2085 llvm::SmallVector<Range<lldb::addr_t, size_t>> fixed_ranges;
2086 fixed_ranges.reserve(ranges.size());
2087 for (const Range<lldb::addr_t, size_t> &range : ranges)
2088 fixed_ranges.emplace_back(FixAnyAddress(range.GetRangeBase()),
2089 range.GetByteSize());
2090 if (!GetDisableMemoryCache())
2091 return m_memory_cache.ReadRanges(fixed_ranges, buffer);
2092 return DoReadMemoryRanges(fixed_ranges, buffer);
2093}
2094
2095llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2097 llvm::MutableArrayRef<uint8_t> buffer) {
2098 auto total_ranges_len = llvm::sum_of(
2099 llvm::map_range(ranges, [](auto range) { return range.size; }));
2100 // If the buffer is not large enough, this is a programmer error.
2101 // In production builds, gracefully fail by returning a length of 0 for all
2102 // ranges.
2103 assert(buffer.size() >= total_ranges_len && "provided buffer is too short");
2104 if (buffer.size() < total_ranges_len) {
2105 llvm::MutableArrayRef<uint8_t> empty;
2106 return {ranges.size(), empty};
2107 }
2108
2109 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
2110
2111 // While `buffer` has space, take the next requested range and read
2112 // memory into a `buffer` piece, then slice it to remove the used memory.
2113 for (auto [addr, range_len] : ranges) {
2114 Status status;
2115 size_t num_bytes_read =
2116 ReadMemoryFromInferior(addr, buffer.data(), range_len, status);
2117 // FIXME: ReadMemoryFromInferior promises to return 0 in case of errors, but
2118 // it doesn't; it never checks for errors.
2119 if (status.Fail())
2120 num_bytes_read = 0;
2121
2122 assert(num_bytes_read <= range_len && "read more than requested bytes");
2123 if (num_bytes_read > range_len) {
2124 // In production builds, gracefully fail by returning length zero for this
2125 // range.
2126 results.emplace_back();
2127 continue;
2128 }
2129
2130 results.push_back(buffer.take_front(num_bytes_read));
2131 // Slice buffer to remove the used memory.
2132 buffer = buffer.drop_front(num_bytes_read);
2133 }
2134
2135 return results;
2136}
2137
2139 const uint8_t *buf, size_t size,
2140 AddressRanges &matches, size_t alignment,
2141 size_t max_matches) {
2142 // Inputs are already validated in FindInMemory() functions.
2143 assert(buf != nullptr);
2144 assert(size > 0);
2145 assert(alignment > 0);
2146 assert(max_matches > 0);
2147 assert(start_addr != LLDB_INVALID_ADDRESS);
2148 assert(end_addr != LLDB_INVALID_ADDRESS);
2149 assert(start_addr < end_addr);
2150
2151 lldb::addr_t start = llvm::alignTo(start_addr, alignment);
2152 while (matches.size() < max_matches && (start + size) < end_addr) {
2153 const lldb::addr_t found_addr = FindInMemory(start, end_addr, buf, size);
2154 if (found_addr == LLDB_INVALID_ADDRESS)
2155 break;
2156
2157 if (found_addr % alignment) {
2158 // We need to check the alignment because the FindInMemory uses a special
2159 // algorithm to efficiently search mememory but doesn't support alignment.
2160 start = llvm::alignTo(start + 1, alignment);
2161 continue;
2162 }
2163
2164 matches.emplace_back(found_addr, size);
2165 start = found_addr + alignment;
2166 }
2167}
2168
2169AddressRanges Process::FindRangesInMemory(const uint8_t *buf, uint64_t size,
2170 const AddressRanges &ranges,
2171 size_t alignment, size_t max_matches,
2172 Status &error) {
2173 AddressRanges matches;
2174 if (buf == nullptr) {
2175 error = Status::FromErrorString("buffer is null");
2176 return matches;
2177 }
2178 if (size == 0) {
2179 error = Status::FromErrorString("buffer size is zero");
2180 return matches;
2181 }
2182 if (ranges.empty()) {
2183 error = Status::FromErrorString("empty ranges");
2184 return matches;
2185 }
2186 if (alignment == 0) {
2187 error = Status::FromErrorString("alignment must be greater than zero");
2188 return matches;
2189 }
2190 if (max_matches == 0) {
2191 error = Status::FromErrorString("max_matches must be greater than zero");
2192 return matches;
2193 }
2194
2195 int resolved_ranges = 0;
2196 Target &target = GetTarget();
2197 for (size_t i = 0; i < ranges.size(); ++i) {
2198 if (matches.size() >= max_matches)
2199 break;
2200 const AddressRange &range = ranges[i];
2201 if (range.IsValid() == false)
2202 continue;
2203
2204 const lldb::addr_t start_addr =
2205 range.GetBaseAddress().GetLoadAddress(&target);
2206 if (start_addr == LLDB_INVALID_ADDRESS)
2207 continue;
2208
2209 ++resolved_ranges;
2210 const lldb::addr_t end_addr = start_addr + range.GetByteSize();
2211 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment,
2212 max_matches);
2213 }
2214
2215 if (resolved_ranges > 0)
2216 error.Clear();
2217 else
2218 error = Status::FromErrorString("unable to resolve any ranges");
2219
2220 return matches;
2221}
2222
2223lldb::addr_t Process::FindInMemory(const uint8_t *buf, uint64_t size,
2224 const AddressRange &range, size_t alignment,
2225 Status &error) {
2226 if (buf == nullptr) {
2227 error = Status::FromErrorString("buffer is null");
2228 return LLDB_INVALID_ADDRESS;
2229 }
2230 if (size == 0) {
2231 error = Status::FromErrorString("buffer size is zero");
2232 return LLDB_INVALID_ADDRESS;
2233 }
2234 if (!range.IsValid()) {
2235 error = Status::FromErrorString("range is invalid");
2236 return LLDB_INVALID_ADDRESS;
2237 }
2238 if (alignment == 0) {
2239 error = Status::FromErrorString("alignment must be greater than zero");
2240 return LLDB_INVALID_ADDRESS;
2241 }
2242
2243 Target &target = GetTarget();
2244 const lldb::addr_t start_addr =
2245 range.GetBaseAddress().GetLoadAddress(&target);
2246 if (start_addr == LLDB_INVALID_ADDRESS) {
2247 error = Status::FromErrorString("range load address is invalid");
2248 return LLDB_INVALID_ADDRESS;
2249 }
2250 const lldb::addr_t end_addr = start_addr + range.GetByteSize();
2251
2252 AddressRanges matches;
2253 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment, 1);
2254 if (matches.empty())
2255 return LLDB_INVALID_ADDRESS;
2256
2257 error.Clear();
2258 return matches[0].GetBaseAddress().GetLoadAddress(&target);
2259}
2260
2261llvm::SmallVector<std::optional<std::string>>
2262Process::ReadCStringsFromMemory(llvm::ArrayRef<lldb::addr_t> addresses) {
2263 llvm::SmallVector<std::optional<std::string>> output_strs(addresses.size(),
2264 "");
2265 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2266 llvm::map_range(addresses, [=](addr_t ptr) {
2268 })};
2269
2270 std::vector<uint8_t> buffer(g_string_read_width * addresses.size(), 0);
2271 uint64_t num_completed_strings = 0;
2272
2273 while (num_completed_strings != addresses.size()) {
2274 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
2275 ReadMemoryRanges(ranges, buffer);
2276
2277 // Each iteration of this loop either increments num_completed_strings or
2278 // updates the base pointer of some range, guaranteeing forward progress of
2279 // the outer loop.
2280 for (auto [range, read_result, output_str] :
2281 llvm::zip(ranges, read_results, output_strs)) {
2282 // A previously completed string.
2283 if (range.GetByteSize() == 0)
2284 continue;
2285
2286 // The read failed, set the range to 0 to avoid reading it again.
2287 if (read_result.empty()) {
2288 output_str = std::nullopt;
2289 range.SetByteSize(0);
2290 num_completed_strings++;
2291 continue;
2292 }
2293
2294 // Convert ArrayRef to StringRef so the pointers work with std::string.
2295 auto read_result_str = llvm::toStringRef(read_result);
2296
2297 const char *null_terminator_pos = llvm::find(read_result_str, '\0');
2298 output_str->append(read_result_str.begin(), null_terminator_pos);
2299
2300 // If the terminator was found, this string is complete.
2301 if (null_terminator_pos != read_result_str.end()) {
2302 range.SetByteSize(0);
2303 num_completed_strings++;
2304 }
2305 // Otherwise increment the base pointer for the next read.
2306 else {
2307 range.SetRangeBase(range.GetRangeBase() + read_result.size());
2308 }
2309 }
2310 }
2311
2312 return output_strs;
2313}
2314
2315size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2316 Status &error) {
2317 char buf[g_string_read_width];
2318 out_str.clear();
2319 addr_t curr_addr = addr;
2320 while (true) {
2321 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2322 if (length == 0)
2323 break;
2324 out_str.append(buf, length);
2325 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2326 // to read some more characters
2327 if (length == sizeof(buf) - 1)
2328 curr_addr += length;
2329 else
2330 break;
2331 }
2332 return out_str.size();
2333}
2334
2335// Deprecated in favor of ReadStringFromMemory which has wchar support and
2336// correct code to find null terminators.
2338 size_t dst_max_len,
2339 Status &result_error) {
2340 size_t total_cstr_len = 0;
2341 if (dst && dst_max_len) {
2342 result_error.Clear();
2343 // NULL out everything just to be safe
2344 memset(dst, 0, dst_max_len);
2345 addr_t curr_addr = addr;
2346 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2347 size_t bytes_left = dst_max_len - 1;
2348 char *curr_dst = dst;
2349
2350 while (bytes_left > 0) {
2351 addr_t cache_line_bytes_left =
2352 cache_line_size - (curr_addr % cache_line_size);
2353 addr_t bytes_to_read =
2354 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2355 Status error;
2356 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2357
2358 if (bytes_read == 0) {
2359 result_error = std::move(error);
2360 dst[total_cstr_len] = '\0';
2361 break;
2362 }
2363 const size_t len = strlen(curr_dst);
2364
2365 total_cstr_len += len;
2366
2367 if (len < bytes_to_read)
2368 break;
2369
2370 curr_dst += bytes_read;
2371 curr_addr += bytes_read;
2372 bytes_left -= bytes_read;
2373 }
2374 } else {
2375 if (dst == nullptr)
2376 result_error = Status::FromErrorString("invalid arguments");
2377 else
2378 result_error.Clear();
2379 }
2380 return total_cstr_len;
2381}
2382
2383size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2384 Status &error) {
2386
2387 if (ABISP abi_sp = GetABI())
2388 addr = abi_sp->FixAnyAddress(addr);
2389
2390 if (buf == nullptr || size == 0)
2391 return 0;
2392
2393 size_t bytes_read = 0;
2394 uint8_t *bytes = (uint8_t *)buf;
2395
2396 while (bytes_read < size) {
2397 const size_t curr_size = size - bytes_read;
2398 const size_t curr_bytes_read =
2399 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2400 bytes_read += curr_bytes_read;
2401 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2402 break;
2403 }
2404
2405 // Replace any software breakpoint opcodes that fall into this range back
2406 // into "buf" before we return
2407 if (bytes_read > 0)
2408 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2409 return bytes_read;
2410}
2411
2413 lldb::addr_t chunk_size,
2414 lldb::offset_t size,
2415 ReadMemoryChunkCallback callback) {
2416 // Safety check to prevent an infinite loop.
2417 if (chunk_size == 0)
2418 return 0;
2419
2420 // Buffer for when a NULL buf is provided, initialized
2421 // to 0 bytes, we set it to chunk_size and then replace buf
2422 // with the new buffer.
2423 DataBufferHeap data_buffer;
2424 if (!buf) {
2425 data_buffer.SetByteSize(chunk_size);
2426 buf = data_buffer.GetBytes();
2427 }
2428
2429 uint64_t bytes_remaining = size;
2430 uint64_t bytes_read = 0;
2431 Status error;
2432 while (bytes_remaining > 0) {
2433 // Get the next read chunk size as the minimum of the remaining bytes and
2434 // the write chunk max size.
2435 const lldb::addr_t bytes_to_read = std::min(bytes_remaining, chunk_size);
2436 const lldb::addr_t current_addr = vm_addr + bytes_read;
2437 const lldb::addr_t bytes_read_for_chunk =
2438 ReadMemoryFromInferior(current_addr, buf, bytes_to_read, error);
2439
2440 bytes_read += bytes_read_for_chunk;
2441 // If the bytes read in this chunk would cause us to overflow, something
2442 // went wrong and we should fail fast.
2443 if (bytes_read_for_chunk > bytes_remaining)
2444 return 0;
2445 else
2446 bytes_remaining -= bytes_read_for_chunk;
2447
2448 if (callback(error, current_addr, buf, bytes_read_for_chunk) ==
2450 break;
2451 }
2452
2453 return bytes_read;
2454}
2455
2457 size_t integer_byte_size,
2458 uint64_t fail_value,
2459 Status &error) {
2460 Scalar scalar;
2461 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2462 error))
2463 return scalar.ULongLong(fail_value);
2464 return fail_value;
2465}
2466
2467llvm::SmallVector<std::optional<uint64_t>>
2468Process::ReadUnsignedIntegersFromMemory(llvm::ArrayRef<addr_t> addresses,
2469 unsigned integer_byte_size) {
2470 if (addresses.empty())
2471 return {};
2472 // Like ReadUnsignedIntegerFromMemory, this only supports a handful
2473 // of widths.
2474 if (!llvm::is_contained({1u, 2u, 4u, 8u}, integer_byte_size))
2475 return llvm::SmallVector<std::optional<uint64_t>>(addresses.size(),
2476 std::nullopt);
2477
2478 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2479 llvm::map_range(addresses, [=](addr_t ptr) {
2480 return Range<addr_t, size_t>(ptr, integer_byte_size);
2481 })};
2482
2483 std::vector<uint8_t> buffer(integer_byte_size * addresses.size(), 0);
2484 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory =
2485 ReadMemoryRanges(ranges, buffer);
2486
2487 llvm::SmallVector<std::optional<uint64_t>> result;
2488 result.reserve(addresses.size());
2489 const uint32_t addr_size = GetAddressByteSize();
2490 const ByteOrder byte_order = GetByteOrder();
2491
2492 for (llvm::MutableArrayRef<uint8_t> range : memory) {
2493 if (range.size() != integer_byte_size) {
2494 result.push_back(std::nullopt);
2495 continue;
2496 }
2497
2498 DataExtractor data(range.data(), integer_byte_size, byte_order, addr_size);
2499 offset_t offset = 0;
2500 result.push_back(data.GetMaxU64(&offset, integer_byte_size));
2501 assert(offset == integer_byte_size);
2502 }
2503 return result;
2504}
2505
2507 size_t integer_byte_size,
2508 int64_t fail_value,
2509 Status &error) {
2510 Scalar scalar;
2511 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2512 error))
2513 return scalar.SLongLong(fail_value);
2514 return fail_value;
2515}
2516
2518 Scalar scalar;
2519 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2520 error))
2521 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2522 return LLDB_INVALID_ADDRESS;
2523}
2524
2525llvm::SmallVector<std::optional<addr_t>>
2526Process::ReadPointersFromMemory(llvm::ArrayRef<addr_t> ptr_locs) {
2527 const size_t ptr_size = GetAddressByteSize();
2528 return ReadUnsignedIntegersFromMemory(ptr_locs, ptr_size);
2529}
2530
2532 Status &error) {
2533 Scalar scalar;
2534 const uint32_t addr_byte_size = GetAddressByteSize();
2535 if (addr_byte_size <= 4)
2536 scalar = (uint32_t)ptr_value;
2537 else
2538 scalar = ptr_value;
2539 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2540 addr_byte_size;
2541}
2542
2543size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2544 Status &error) {
2545 size_t bytes_written = 0;
2546 const uint8_t *bytes = (const uint8_t *)buf;
2547
2548 while (bytes_written < size) {
2549 const size_t curr_size = size - bytes_written;
2550 const size_t curr_bytes_written = DoWriteMemory(
2551 addr + bytes_written, bytes + bytes_written, curr_size, error);
2552 bytes_written += curr_bytes_written;
2553 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2554 break;
2555 }
2556 return bytes_written;
2557}
2558
2559size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2560 Status &error) {
2561 if (ABISP abi_sp = GetABI())
2562 addr = abi_sp->FixAnyAddress(addr);
2563
2564 m_memory_cache.Flush(addr, size);
2565
2566 if (buf == nullptr || size == 0)
2567 return 0;
2568
2569 if (TrackMemoryCacheChanges() || !m_allocated_memory_cache.IsInCache(addr))
2570 m_mod_id.BumpMemoryID();
2571
2572 // We need to write any data that would go where any current software traps
2573 // (enabled software breakpoints) any software traps (breakpoints) that we
2574 // may have placed in our tasks memory.
2575
2576 StopPointSiteList<BreakpointSite> bp_sites_in_range;
2577 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2578 return WriteMemoryPrivate(addr, buf, size, error);
2579
2580 // No breakpoint sites overlap
2581 if (bp_sites_in_range.IsEmpty())
2582 return WriteMemoryPrivate(addr, buf, size, error);
2583
2584 const uint8_t *ubuf = (const uint8_t *)buf;
2585 uint64_t bytes_written = 0;
2586
2587 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2588 &error](BreakpointSite *bp) -> void {
2589 if (error.Fail())
2590 return;
2591
2593 return;
2594
2595 addr_t intersect_addr;
2596 size_t intersect_size;
2597 size_t opcode_offset;
2598 const bool intersects = bp->IntersectsRange(
2599 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2600 UNUSED_IF_ASSERT_DISABLED(intersects);
2601 assert(intersects);
2602 assert(addr <= intersect_addr && intersect_addr < addr + size);
2603 assert(addr < intersect_addr + intersect_size &&
2604 intersect_addr + intersect_size <= addr + size);
2605 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2606
2607 // Check for bytes before this breakpoint
2608 const addr_t curr_addr = addr + bytes_written;
2609 if (intersect_addr > curr_addr) {
2610 // There are some bytes before this breakpoint that we need to just
2611 // write to memory
2612 size_t curr_size = intersect_addr - curr_addr;
2613 size_t curr_bytes_written =
2614 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2615 bytes_written += curr_bytes_written;
2616 if (curr_bytes_written != curr_size) {
2617 // We weren't able to write all of the requested bytes, we are
2618 // done looping and will return the number of bytes that we have
2619 // written so far.
2620 if (error.Success())
2621 error = Status::FromErrorString("could not write all bytes");
2622 }
2623 }
2624 // Now write any bytes that would cover up any software breakpoints
2625 // directly into the breakpoint opcode buffer
2626 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2627 intersect_size);
2628 bytes_written += intersect_size;
2629 });
2630
2631 // Write any remaining bytes after the last breakpoint if we have any left
2632 if (bytes_written < size)
2633 bytes_written +=
2634 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2635 size - bytes_written, error);
2636
2637 return bytes_written;
2638}
2639
2640size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2641 size_t byte_size, Status &error) {
2642 if (byte_size == UINT32_MAX)
2643 byte_size = scalar.GetByteSize();
2644 if (byte_size > 0) {
2645 uint8_t buf[32];
2646 const size_t mem_size =
2647 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2648 if (mem_size > 0)
2649 return WriteMemory(addr, buf, mem_size, error);
2650 else
2651 error = Status::FromErrorString("failed to get scalar as memory data");
2652 } else {
2653 error = Status::FromErrorString("invalid scalar value");
2654 }
2655 return 0;
2656}
2657
2658size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2659 bool is_signed, Scalar &scalar,
2660 Status &error) {
2661 uint64_t uval = 0;
2662 if (byte_size == 0) {
2663 error = Status::FromErrorString("byte size is zero");
2664 } else if (byte_size & (byte_size - 1)) {
2666 "byte size %u is not a power of 2", byte_size);
2667 } else if (byte_size <= sizeof(uval)) {
2668 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2669 if (bytes_read == byte_size) {
2670 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2672 lldb::offset_t offset = 0;
2673 if (byte_size <= 4)
2674 scalar = data.GetMaxU32(&offset, byte_size);
2675 else
2676 scalar = data.GetMaxU64(&offset, byte_size);
2677 if (is_signed) {
2678 scalar.MakeSigned();
2679 scalar.SignExtend(byte_size * 8);
2680 }
2681 return bytes_read;
2682 }
2683 } else {
2685 "byte size of %u is too large for integer scalar type", byte_size);
2686 }
2687 return 0;
2688}
2689
2690Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2691 Status error;
2692 for (const auto &Entry : entries) {
2693 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2694 error);
2695 if (!error.Success())
2696 break;
2697 }
2698 return error;
2699}
2700
2701addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2702 Status &error) {
2703 if (GetPrivateState() != eStateStopped) {
2705 "cannot allocate memory while process is running");
2706 return LLDB_INVALID_ADDRESS;
2707 }
2708
2709 addr_t alloced_addr =
2710 m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2712
2713 return alloced_addr;
2714}
2715
2716addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2717 Status &error) {
2718 addr_t return_addr = AllocateMemory(size, permissions, error);
2719 if (error.Success()) {
2720 std::string buffer(size, 0);
2721 WriteMemory(return_addr, buffer.c_str(), size, error);
2722 }
2723 return return_addr;
2724}
2725
2727 if (m_can_jit == eCanJITDontKnow) {
2728 Log *log = GetLog(LLDBLog::Process);
2729 Status err;
2730
2731 uint64_t allocated_memory = AllocateMemory(
2732 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2733 err);
2734
2735 if (err.Success()) {
2737 LLDB_LOGF(log,
2738 "Process::%s pid %" PRIu64
2739 " allocation test passed, CanJIT () is true",
2740 __FUNCTION__, GetID());
2741 } else {
2743 LLDB_LOGF(log,
2744 "Process::%s pid %" PRIu64
2745 " allocation test failed, CanJIT () is false: %s",
2746 __FUNCTION__, GetID(), err.AsCString());
2747 }
2748
2749 DeallocateMemory(allocated_memory);
2750 }
2751
2752 return m_can_jit == eCanJITYes;
2753}
2754
2755void Process::SetCanJIT(bool can_jit) {
2756 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2757}
2758
2759void Process::SetCanRunCode(bool can_run_code) {
2760 SetCanJIT(can_run_code);
2761 m_can_interpret_function_calls = can_run_code;
2762}
2763
2765 Status error;
2767 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2769 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2770 }
2771 return error;
2772}
2773
2775 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2776 return *subclass_override;
2777
2778 bool reported_after = true;
2779 const ArchSpec &arch = GetTarget().GetArchitecture();
2780 if (!arch.IsValid())
2781 return reported_after;
2782 llvm::Triple triple = arch.GetTriple();
2783
2784 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2785 triple.isAArch64() || triple.isArmMClass() || triple.isARM() ||
2786 triple.isLoongArch())
2787 reported_after = false;
2788
2789 return reported_after;
2790}
2791
2792llvm::Expected<ModuleSP>
2794 lldb::addr_t header_addr, size_t size_to_read) {
2796 "Process::ReadModuleFromMemory reading %s binary from memory",
2797 file_spec.GetPath().c_str());
2798 ModuleSP module_sp = std::make_shared<Module>(file_spec, ArchSpec());
2799 if (!module_sp)
2800 return llvm::createStringError("failed to allocate module");
2801
2802 Status error;
2803 std::unique_ptr<Progress> progress_up;
2804 // Reading an ObjectFile from a local corefile is very fast,
2805 // only print a progress update if we're reading from a
2806 // live session which might go over gdb remote serial protocol.
2807 if (IsLiveDebugSession())
2808 progress_up = std::make_unique<Progress>("Reading binary from memory",
2809 file_spec.GetFilename().str());
2810
2811 if (ObjectFile *_ = module_sp->GetMemoryObjectFile(
2812 shared_from_this(), header_addr, error, size_to_read))
2813 return module_sp;
2814
2815 return error.takeError();
2816}
2817
2819 uint32_t &permissions) {
2820 MemoryRegionInfo range_info;
2821 permissions = 0;
2822 Status error(GetMemoryRegionInfo(load_addr, range_info));
2823 if (!error.Success())
2824 return false;
2825 if (range_info.GetReadable() == eLazyBoolDontKnow ||
2826 range_info.GetWritable() == eLazyBoolDontKnow ||
2827 range_info.GetExecutable() == eLazyBoolDontKnow) {
2828 return false;
2829 }
2830 permissions = range_info.GetLLDBPermissions();
2831 return true;
2832}
2833
2835 Status error;
2836 error = Status::FromErrorString("watchpoints are not supported");
2837 return error;
2838}
2839
2841 Status error;
2842 error = Status::FromErrorString("watchpoints are not supported");
2843 return error;
2844}
2845
2848 const Timeout<std::micro> &timeout) {
2849 StateType state;
2850
2851 while (true) {
2852 event_sp.reset();
2853 state = GetStateChangedEventsPrivate(event_sp, timeout);
2854
2855 if (StateIsStoppedState(state, false))
2856 break;
2857
2858 // If state is invalid, then we timed out
2859 if (state == eStateInvalid)
2860 break;
2861
2862 if (event_sp)
2863 HandlePrivateEvent(event_sp);
2864 }
2865 return state;
2866}
2867
2869 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
2870 if (flush)
2871 m_thread_list.Clear();
2872 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2873 if (flush)
2874 Flush();
2875}
2876
2878 StateType state_after_launch = eStateInvalid;
2879 EventSP first_stop_event_sp;
2880 Status status =
2881 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2882 if (status.Fail())
2883 return status;
2884
2885 if (state_after_launch != eStateStopped &&
2886 state_after_launch != eStateCrashed)
2887 return Status();
2888
2889 // Note, the stop event was consumed above, but not handled. This
2890 // was done to give DidLaunch a chance to run. The target is either
2891 // stopped or crashed. Directly set the state. This is done to
2892 // prevent a stop message with a bunch of spurious output on thread
2893 // status, as well as not pop a ProcessIOHandler.
2894
2896 SetPublicState(state_after_launch, false);
2898 } else {
2899 StartPrivateStateThread(state_after_launch, false);
2901 // We are not going to get any further here. The only way this could fail
2902 // is if we can't start a host thread, so we're pretty much toast at that
2903 // point.
2904 return Status::FromErrorString("could not start private state thread.");
2905 }
2906 }
2907
2908 // Target was stopped at entry as was intended. Need to notify the
2909 // listeners about it.
2910 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2911 HandlePrivateEvent(first_stop_event_sp);
2912
2913 return Status();
2914}
2915
2917 EventSP &event_sp) {
2918 Status error;
2919 m_abi_sp.reset();
2920 m_dyld_up.reset();
2921 m_jit_loaders_up.reset();
2922 m_system_runtime_up.reset();
2923 m_os_up.reset();
2925
2926 {
2927 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2928 m_process_input_reader.reset();
2929 }
2930
2932
2933 // The "remote executable path" is hooked up to the local Executable
2934 // module. But we should be able to debug a remote process even if the
2935 // executable module only exists on the remote. However, there needs to
2936 // be a way to express this path, without actually having a module.
2937 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2938 // Figure that out here:
2939
2940 FileSpec exe_spec_to_use;
2941 if (!exe_module) {
2942 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
2943 error = Status::FromErrorString("executable module does not exist");
2944 return error;
2945 }
2946 exe_spec_to_use = launch_info.GetExecutableFile();
2947 } else
2948 exe_spec_to_use = exe_module->GetFileSpec();
2949
2950 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2951 // Install anything that might need to be installed prior to launching.
2952 // For host systems, this will do nothing, but if we are connected to a
2953 // remote platform it will install any needed binaries
2954 error = GetTarget().Install(&launch_info);
2955 if (error.Fail())
2956 return error;
2957 }
2958
2959 // Listen and queue events that are broadcasted during the process launch.
2960 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2961 HijackProcessEvents(listener_sp);
2962 llvm::scope_exit on_exit([this]() { RestoreProcessEvents(); });
2963
2966
2967 error = WillLaunch(exe_module);
2968 if (error.Fail()) {
2969 std::string local_exec_file_path = exe_spec_to_use.GetPath();
2970 return Status::FromErrorStringWithFormat("file doesn't exist: '%s'",
2971 local_exec_file_path.c_str());
2972 }
2973
2974 const bool restarted = false;
2975 SetPublicState(eStateLaunching, restarted);
2976 m_should_detach = false;
2977
2979 error = DoLaunch(exe_module, launch_info);
2980
2981 if (error.Fail()) {
2982 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2984 const char *error_string = error.AsCString();
2985 if (error_string == nullptr)
2986 error_string = "launch failed";
2987 SetExitStatus(-1, error_string);
2988 }
2989 return error;
2990 }
2991
2992 // Now wait for the process to launch and return control to us, and then
2993 // call DidLaunch:
2994 state = WaitForProcessStopPrivate(event_sp, seconds(10));
2995
2996 if (state == eStateInvalid || !event_sp) {
2997 // We were able to launch the process, but we failed to catch the
2998 // initial stop.
2999 error = Status::FromErrorString("failed to catch stop after launch");
3000 SetExitStatus(0, error.AsCString());
3001 Destroy(false);
3002 return error;
3003 }
3004
3005 if (state == eStateExited) {
3006 // We exited while trying to launch somehow. Don't call DidLaunch
3007 // as that's not likely to work, and return an invalid pid.
3008 HandlePrivateEvent(event_sp);
3009 return Status();
3010 }
3011
3012 if (state == eStateStopped || state == eStateCrashed) {
3013 DidLaunch();
3014
3015 // Now that we know the process type, update its signal responses from the
3016 // ones stored in the Target:
3019 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());
3020
3022 if (dyld)
3023 dyld->DidLaunch();
3024
3026
3027 SystemRuntime *system_runtime = GetSystemRuntime();
3028 if (system_runtime)
3029 system_runtime->DidLaunch();
3030
3031 if (!m_os_up)
3033
3034 // We successfully launched the process and stopped, now it the
3035 // right time to set up signal filters before resuming.
3037 return Status();
3038 }
3039
3041 "Unexpected process state after the launch: %s, expected %s, "
3042 "%s, %s or %s",
3046}
3047
3051 if (error.Success()) {
3052 ListenerSP listener_sp(
3053 Listener::MakeListener("lldb.process.load_core_listener"));
3054 HijackProcessEvents(listener_sp);
3055
3058 else {
3060 /*RunLock is stopped*/ false);
3062 // We are not going to get any further here. The only way this
3063 // could fail is if we can't start a host thread, so we're pretty much
3064 // toast at that point.
3065 return Status::FromErrorString("could not start private state thread.");
3066 }
3067 }
3068
3070 if (dyld)
3071 dyld->DidAttach();
3072
3074
3075 SystemRuntime *system_runtime = GetSystemRuntime();
3076 if (system_runtime)
3077 system_runtime->DidAttach();
3078
3079 if (!m_os_up)
3081
3082 // We successfully loaded a core file, now pretend we stopped so we can
3083 // show all of the threads in the core file and explore the crashed state.
3085
3086 // Wait for a stopped event since we just posted one above...
3087 lldb::EventSP event_sp;
3088 StateType state =
3089 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
3090 nullptr, true, SelectMostRelevantFrame);
3091
3092 if (!StateIsStoppedState(state, false)) {
3093 Log *log = GetLog(LLDBLog::Process);
3094 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
3095 StateAsCString(state));
3097 "Did not get stopped event after loading the core file.");
3098 }
3100 // Since we hijacked the event stream, we will have we won't have run the
3101 // stop hooks. Make sure we do that here:
3102 GetTarget().RunStopHooks(/* at_initial_stop= */ true);
3103 }
3104 return error;
3105}
3106
3108 if (!m_dyld_up)
3109 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3110 return m_dyld_up.get();
3111}
3112
3114 m_dyld_up = std::move(dyld_up);
3115}
3116
3118
3119llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
3120 return false;
3121}
3122
3124 if (!m_jit_loaders_up) {
3125 m_jit_loaders_up = std::make_unique<JITLoaderList>();
3127 }
3128 return *m_jit_loaders_up;
3129}
3130
3136
3138 uint32_t exec_count)
3139 : NextEventAction(process), m_exec_count(exec_count) {
3140 Log *log = GetLog(LLDBLog::Process);
3141 LLDB_LOGF(
3142 log,
3143 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
3144 __FUNCTION__, static_cast<void *>(process), exec_count);
3145}
3146
3149 Log *log = GetLog(LLDBLog::Process);
3150
3151 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3152 LLDB_LOGF(log,
3153 "Process::AttachCompletionHandler::%s called with state %s (%d)",
3154 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
3155
3156 switch (state) {
3157 case eStateAttaching:
3158 return eEventActionSuccess;
3159
3160 case eStateRunning:
3161 case eStateConnected:
3162 return eEventActionRetry;
3163
3164 case eStateStopped:
3165 case eStateCrashed:
3166 // During attach, prior to sending the eStateStopped event,
3167 // lldb_private::Process subclasses must set the new process ID.
3168 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
3169 // We don't want these events to be reported, so go set the
3170 // ShouldReportStop here:
3171 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
3172
3173 if (m_exec_count > 0) {
3174 --m_exec_count;
3175
3176 LLDB_LOGF(log,
3177 "Process::AttachCompletionHandler::%s state %s: reduced "
3178 "remaining exec count to %" PRIu32 ", requesting resume",
3179 __FUNCTION__, StateAsCString(state), m_exec_count);
3180
3181 RequestResume();
3182 return eEventActionRetry;
3183 } else {
3184 LLDB_LOGF(log,
3185 "Process::AttachCompletionHandler::%s state %s: no more "
3186 "execs expected to start, continuing with attach",
3187 __FUNCTION__, StateAsCString(state));
3188
3189 m_process->CompleteAttach();
3190 return eEventActionSuccess;
3191 }
3192 break;
3193
3194 default:
3195 case eStateExited:
3196 case eStateInvalid:
3197 break;
3198 }
3199
3200 m_exit_string.assign("No valid Process");
3201 return eEventActionExit;
3202}
3203
3208
3210 return m_exit_string.c_str();
3211}
3212
3214 if (m_listener_sp)
3215 return m_listener_sp;
3216 else
3217 return debugger.GetListener();
3218}
3219
3221 return DoWillLaunch(module);
3222}
3223
3227
3229 bool wait_for_launch) {
3230 return DoWillAttachToProcessWithName(process_name, wait_for_launch);
3231}
3232
3234 m_abi_sp.reset();
3235 {
3236 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3237 m_process_input_reader.reset();
3238 }
3239 m_dyld_up.reset();
3240 m_jit_loaders_up.reset();
3241 m_system_runtime_up.reset();
3242 m_os_up.reset();
3244
3245 lldb::pid_t attach_pid = attach_info.GetProcessID();
3246 Status error;
3247 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3248 char process_name[PATH_MAX];
3249
3250 if (attach_info.GetExecutableFile().GetPath(process_name,
3251 sizeof(process_name))) {
3252 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3253
3254 if (wait_for_launch) {
3255 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3256 if (error.Success()) {
3257 m_should_detach = true;
3258 // Now attach using these arguments.
3259 error = DoAttachToProcessWithName(process_name, attach_info);
3260
3261 if (error.Fail()) {
3262 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3264 if (error.AsCString() == nullptr)
3265 error = Status::FromErrorString("attach failed");
3266
3267 SetExitStatus(-1, error.AsCString());
3268 }
3269 } else {
3271 this, attach_info.GetResumeCount()));
3274 // We are not going to get any further here. The only way
3275 // this could fail is if we can't start a host thread, and we're
3276 // pretty much toast at that point.
3278 "could not start private state thread.");
3279 }
3280 }
3281 return error;
3282 }
3283 } else {
3284 ProcessInstanceInfoList process_infos;
3285 PlatformSP platform_sp(GetTarget().GetPlatform());
3286
3287 if (platform_sp) {
3288 ProcessInstanceInfoMatch match_info;
3289 match_info.GetProcessInfo() = attach_info;
3291 platform_sp->FindProcesses(match_info, process_infos);
3292 const uint32_t num_matches = process_infos.size();
3293 if (num_matches == 1) {
3294 attach_pid = process_infos[0].GetProcessID();
3295 // Fall through and attach using the above process ID
3296 } else {
3298 process_name, sizeof(process_name));
3299 if (num_matches > 1) {
3300 StreamString s;
3302 for (size_t i = 0; i < num_matches; i++) {
3303 process_infos[i].DumpAsTableRow(
3304 s, platform_sp->GetUserIDResolver(), true, false);
3305 }
3307 "more than one process named %s:\n%s", process_name,
3308 s.GetData());
3309 } else
3311 "could not find a process named %s", process_name);
3312 }
3313 } else {
3315 "invalid platform, can't find processes by name");
3316 return error;
3317 }
3318 }
3319 } else {
3320 error = Status::FromErrorString("invalid process name");
3321 }
3322 }
3323
3324 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3325 error = WillAttachToProcessWithID(attach_pid);
3326 if (error.Success()) {
3327 // Now attach using these arguments.
3328 m_should_detach = true;
3329 error = DoAttachToProcessWithID(attach_pid, attach_info);
3330
3331 if (error.Success()) {
3333 this, attach_info.GetResumeCount()));
3334
3337 // We are not going to get any further here. The only way this
3338 // could fail is if we can't start a host thread, so we're pretty much
3339 // toast at thatpoint.
3341 "could not start private state thread.");
3342 }
3343 } else {
3346
3347 const char *error_string = error.AsCString();
3348 if (error_string == nullptr)
3349 error_string = "attach failed";
3350
3351 SetExitStatus(-1, error_string);
3352 }
3353 }
3354 }
3355 return error;
3356}
3357
3360 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
3361
3362 // Let the process subclass figure out at much as it can about the process
3363 // before we go looking for a dynamic loader plug-in.
3364 ArchSpec process_arch;
3365 DidAttach(process_arch);
3366
3367 if (process_arch.IsValid()) {
3368 LLDB_LOG(log,
3369 "Process::{0} replacing process architecture with DidAttach() "
3370 "architecture: \"{1}\"",
3371 __FUNCTION__, process_arch.GetTriple().getTriple());
3372 GetTarget().SetArchitecture(process_arch);
3373 }
3374
3375 // We just attached. If we have a platform, ask it for the process
3376 // architecture, and if it isn't the same as the one we've already set,
3377 // switch architectures.
3378 PlatformSP platform_sp(GetTarget().GetPlatform());
3379 assert(platform_sp);
3380 ArchSpec process_host_arch = GetSystemArchitecture();
3381 if (platform_sp) {
3382 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3383 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
3384 target_arch, process_host_arch,
3385 ArchSpec::CompatibleMatch, nullptr)) {
3386 ArchSpec platform_arch;
3388 target_arch, process_host_arch, &platform_arch);
3389 if (platform_sp) {
3390 GetTarget().SetPlatform(platform_sp);
3391 GetTarget().SetArchitecture(platform_arch);
3392 LLDB_LOG(log,
3393 "switching platform to {0} and architecture to {1} based on "
3394 "info from attach",
3395 platform_sp->GetName(), platform_arch.GetTriple().getTriple());
3396 }
3397 } else if (!process_arch.IsValid()) {
3398 ProcessInstanceInfo process_info;
3399 GetProcessInfo(process_info);
3400 const ArchSpec &process_arch = process_info.GetArchitecture();
3401 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3402 if (process_arch.IsValid() &&
3403 target_arch.IsCompatibleMatch(process_arch) &&
3404 !target_arch.IsExactMatch(process_arch)) {
3405 GetTarget().SetArchitecture(process_arch);
3406 LLDB_LOGF(log,
3407 "Process::%s switching architecture to %s based on info "
3408 "the platform retrieved for pid %" PRIu64,
3409 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3410 GetID());
3411 }
3412 }
3413 }
3414 // Now that we know the process type, update its signal responses from the
3415 // ones stored in the Target:
3418 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());
3419
3420 // We have completed the attach, now it is time to find the dynamic loader
3421 // plug-in
3423 if (dyld) {
3424 dyld->DidAttach();
3425 if (log) {
3426 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3427 LLDB_LOG(log,
3428 "after DynamicLoader::DidAttach(), target "
3429 "executable is {0} (using {1} plugin)",
3430 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3431 dyld->GetPluginName());
3432 }
3433 }
3434
3436
3437 SystemRuntime *system_runtime = GetSystemRuntime();
3438 if (system_runtime) {
3439 system_runtime->DidAttach();
3440 if (log) {
3441 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3442 LLDB_LOG(log,
3443 "after SystemRuntime::DidAttach(), target "
3444 "executable is {0} (using {1} plugin)",
3445 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3446 system_runtime->GetPluginName());
3447 }
3448 }
3449
3450 // If we don't have an operating system plugin loaded yet, see if
3451 // LoadOperatingSystemPlugin can find one (and stuff it in m_os_up).
3452 if (!m_os_up)
3454
3455 if (m_os_up) {
3456 // Somebody might have gotten threads before we loaded the OS Plugin above,
3457 // so we need to force the update now or the newly loaded plugin won't get
3458 // a chance to process the threads.
3459 m_thread_list.Clear();
3461 }
3462
3463 // Figure out which one is the executable, and set that in our target:
3464 ModuleSP new_executable_module_sp;
3465 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
3466 if (module_sp && module_sp->IsExecutable()) {
3467 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3468 new_executable_module_sp = module_sp;
3469 break;
3470 }
3471 }
3472 if (new_executable_module_sp) {
3473 GetTarget().SetExecutableModule(new_executable_module_sp,
3475 if (log) {
3476 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3477 LLDB_LOGF(
3478 log,
3479 "Process::%s after looping through modules, target executable is %s",
3480 __FUNCTION__,
3481 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3482 : "<none>");
3483 }
3484 }
3485 // Since we hijacked the event stream, we will have we won't have run the
3486 // stop hooks. Make sure we do that here:
3487 GetTarget().RunStopHooks(/* at_initial_stop= */ true);
3488}
3489
3490Status Process::ConnectRemote(llvm::StringRef remote_url) {
3491 m_abi_sp.reset();
3492 {
3493 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3494 m_process_input_reader.reset();
3495 }
3496
3497 // Find the process and its architecture. Make sure it matches the
3498 // architecture of the current Target, and if not adjust it.
3499
3500 Status error(DoConnectRemote(remote_url));
3501 if (error.Success()) {
3502 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3503 EventSP event_sp;
3504 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
3505
3506 if (state == eStateStopped || state == eStateCrashed) {
3507 // If we attached and actually have a process on the other end, then
3508 // this ended up being the equivalent of an attach.
3509 SetShouldDetach(true);
3511
3512 // This delays passing the stopped event to listeners till
3513 // CompleteAttach gets a chance to complete...
3514 HandlePrivateEvent(event_sp);
3515 }
3516 }
3517
3520 else {
3522 /*RunLock is stopped */ false);
3524 // We are not going to get any further here. The only way this
3525 // could fail is if we can't start a host thread, so we're pretty much
3526 // toast at that point.
3527 return Status::FromErrorString("could not start private state thread.");
3528 }
3529 }
3530 }
3531 return error;
3532}
3533
3535 if (m_base_direction == direction)
3536 return;
3537 m_thread_list.DiscardThreadPlans();
3538 m_base_direction = direction;
3539}
3540
3543 LLDB_LOGF(log,
3544 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3545 "private state: %s",
3546 m_mod_id.GetStopID(), StateAsCString(GetPublicState()),
3548
3549 // If signals handing status changed we might want to update our signal
3550 // filters before resuming.
3552 // Clear any crash info we accumulated for this stop, but don't do so if we
3553 // are running functions; we don't want to wipe out the real stop's info.
3554 if (!GetModID().IsLastResumeForUserExpression())
3556
3558 // Tell the process it is about to resume before the thread list
3559 if (error.Success()) {
3560 // Now let the thread list know we are about to resume so it can let all of
3561 // our threads know that they are about to be resumed. Threads will each be
3562 // called with Thread::WillResume(StateType) where StateType contains the
3563 // state that they are supposed to have when the process is resumed
3564 // (suspended/running/stepping). Threads should also check their resume
3565 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3566 // start back up with a signal.
3567 RunDirection direction;
3568 if (m_thread_list.WillResume(direction)) {
3569 LLDB_LOGF(log, "Process::PrivateResume WillResume direction=%d",
3570 direction);
3571 // Last thing, do the PreResumeActions.
3572 if (!RunPreResumeActions()) {
3574 "Process::PrivateResume PreResumeActions failed, not resuming.");
3575 LLDB_LOGF(
3576 log,
3577 "Process::PrivateResume PreResumeActions failed, not resuming.");
3578 } else {
3579 m_mod_id.BumpResumeID();
3580 if (auto E = FlushDelayedBreakpoints())
3581 LLDB_LOG_ERROR(log, std::move(E),
3582 "Failed to update some delayed breakpoints: {0}");
3583 error = DoResume(direction);
3584 if (error.Success()) {
3585 DidResume();
3586 m_thread_list.DidResume();
3587 LLDB_LOGF(log,
3588 "Process::PrivateResume thinks the process has resumed.");
3589 } else {
3590 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3591 return error;
3592 }
3593 }
3594 } else {
3595 // Somebody wanted to run without running (e.g. we were faking a step
3596 // from one frame of a set of inlined frames that share the same PC to
3597 // another.) So generate a continue & a stopped event, and let the world
3598 // handle them.
3599 LLDB_LOGF(log,
3600 "Process::PrivateResume() asked to simulate a start & stop.");
3601
3604 }
3605 } else
3606 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3607 error.AsCString("<unknown error>"));
3608 return error;
3609}
3610
3611Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3613 return Status::FromErrorString("Process is not running.");
3614
3615 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3616 // case it was already set and some thread plan logic calls halt on its own.
3617 m_clear_thread_plans_on_stop |= clear_thread_plans;
3618
3619 ListenerSP halt_listener_sp(
3620 Listener::MakeListener("lldb.process.halt_listener"));
3621 HijackProcessEvents(halt_listener_sp);
3622
3623 EventSP event_sp;
3624
3626
3628 // Don't hijack and eat the eStateExited as the code that was doing the
3629 // attach will be waiting for this event...
3631 Destroy(false);
3632 SetExitStatus(SIGKILL, "Cancelled async attach.");
3633 return Status();
3634 }
3635
3636 // Wait for the process halt timeout seconds for the process to stop.
3637 // If we are going to use the run lock, that means we're stopping out to the
3638 // user, so we should also select the most relevant frame.
3639 SelectMostRelevant select_most_relevant =
3641 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3642 halt_listener_sp, nullptr,
3643 use_run_lock, select_most_relevant);
3645
3646 if (state == eStateInvalid || !event_sp) {
3647 // We timed out and didn't get a stop event...
3648 return Status::FromErrorStringWithFormat("Halt timed out. State = %s",
3650 }
3651
3652 BroadcastEvent(event_sp);
3653
3654 return Status();
3655}
3656
3658 const uint8_t *buf, size_t size) {
3659 const size_t region_size = high - low;
3660
3661 if (region_size < size)
3662 return LLDB_INVALID_ADDRESS;
3663
3664 // See "Boyer-Moore string search algorithm".
3665 std::vector<size_t> bad_char_heuristic(256, size);
3666 for (size_t idx = 0; idx < size - 1; idx++) {
3667 decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];
3668 bad_char_heuristic[bcu_idx] = size - idx - 1;
3669 }
3670
3671 // Memory we're currently searching through.
3672 llvm::SmallVector<uint8_t, 0> mem;
3673 // Position of the memory buffer.
3674 addr_t mem_pos = low;
3675 // Maximum number of bytes read (and buffered). We need to read at least
3676 // `size` bytes for a successful match.
3677 const size_t max_read_size = std::max<size_t>(size, 0x10000);
3678
3679 for (addr_t cur_addr = low; cur_addr <= (high - size);) {
3680 if (cur_addr + size > mem_pos + mem.size()) {
3681 // We need to read more data. We don't attempt to reuse the data we've
3682 // already read (up to `size-1` bytes from `cur_addr` to
3683 // `mem_pos+mem.size()`). This is fine for patterns much smaller than
3684 // max_read_size. For very
3685 // long patterns we may need to do something more elaborate.
3686 mem.resize_for_overwrite(max_read_size);
3687 Status error;
3688 mem.resize(ReadMemory(cur_addr, mem.data(),
3689 std::min<addr_t>(mem.size(), high - cur_addr),
3690 error));
3691 mem_pos = cur_addr;
3692 if (size > mem.size()) {
3693 // We didn't read enough data. Skip to the next memory region.
3694 MemoryRegionInfo info;
3695 error = GetMemoryRegionInfo(mem_pos + mem.size(), info);
3696 if (error.Fail())
3697 break;
3698 cur_addr = info.GetRange().GetRangeEnd();
3699 continue;
3700 }
3701 }
3702 int64_t j = size - 1;
3703 while (j >= 0 && buf[j] == mem[cur_addr + j - mem_pos])
3704 j--;
3705 if (j < 0)
3706 return cur_addr; // We have a match.
3707 cur_addr += bad_char_heuristic[mem[cur_addr + size - 1 - mem_pos]];
3708 }
3709
3710 return LLDB_INVALID_ADDRESS;
3711}
3712
3714 Status error;
3715
3716 // Check both the public & private states here. If we're hung evaluating an
3717 // expression, for instance, then the public state will be stopped, but we
3718 // still need to interrupt.
3720 Log *log = GetLog(LLDBLog::Process);
3721 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3722
3723 ListenerSP listener_sp(
3724 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3725 HijackProcessEvents(listener_sp);
3726
3728
3729 // Consume the interrupt event.
3731 &exit_event_sp, true, listener_sp);
3732
3734
3735 // If the process exited while we were waiting for it to stop, put the
3736 // exited event into the shared pointer passed in and return. Our caller
3737 // doesn't need to do anything else, since they don't have a process
3738 // anymore...
3739
3740 if (state == eStateExited || GetPrivateState() == eStateExited) {
3741 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3742 __FUNCTION__);
3743 return error;
3744 } else
3745 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3746
3747 if (state != eStateStopped) {
3748 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3749 StateAsCString(state));
3750 // If we really couldn't stop the process then we should just error out
3751 // here, but if the lower levels just bobbled sending the event and we
3752 // really are stopped, then continue on.
3753 StateType private_state = GetPrivateState();
3754 if (private_state != eStateStopped) {
3756 "Attempt to stop the target in order to detach timed out. "
3757 "State = %s",
3759 }
3760 }
3761 }
3762 return error;
3763}
3764
3765Status Process::Detach(bool keep_stopped) {
3766 EventSP exit_event_sp;
3767 Status error;
3768 m_destroy_in_process = true;
3769
3770 error = WillDetach();
3771
3772 if (error.Success()) {
3773 if (DetachRequiresHalt()) {
3774 error = StopForDestroyOrDetach(exit_event_sp);
3775 if (!error.Success()) {
3776 m_destroy_in_process = false;
3777 return error;
3778 } else if (exit_event_sp) {
3779 // We shouldn't need to do anything else here. There's no process left
3780 // to detach from...
3782 m_destroy_in_process = false;
3783 return error;
3784 }
3785 }
3786
3787 m_thread_list.DiscardThreadPlans();
3789 if (auto error = FlushDelayedBreakpoints())
3791 GetLog(LLDBLog::Process), std::move(error),
3792 "Failed to update some delayed breakpoints during detach: {0}");
3793
3794 error = DoDetach(keep_stopped);
3795 if (error.Success()) {
3796 DidDetach();
3798 } else {
3799 return error;
3800 }
3801 }
3802 m_destroy_in_process = false;
3803
3804 // If we exited when we were waiting for a process to stop, then forward the
3805 // event here so we don't lose the event
3806 if (exit_event_sp) {
3807 // Directly broadcast our exited event because we shut down our private
3808 // state thread above
3809 BroadcastEvent(exit_event_sp);
3810 }
3811
3812 // If we have been interrupted (to kill us) in the middle of running, we may
3813 // not end up propagating the last events through the event system, in which
3814 // case we might strand the write lock. Unlock it here so when we do to tear
3815 // down the process we don't get an error destroying the lock.
3816
3818 return error;
3819}
3820
3821Status Process::Destroy(bool force_kill) {
3822 // If we've already called Process::Finalize then there's nothing useful to
3823 // be done here. Finalize has actually called Destroy already.
3824 if (m_finalizing)
3825 return {};
3826 return DestroyImpl(force_kill);
3827}
3828
3830 // Tell ourselves we are in the process of destroying the process, so that we
3831 // don't do any unnecessary work that might hinder the destruction. Remember
3832 // to set this back to false when we are done. That way if the attempt
3833 // failed and the process stays around for some reason it won't be in a
3834 // confused state.
3835
3836 if (force_kill)
3837 m_should_detach = false;
3838
3839 if (GetShouldDetach()) {
3840 // FIXME: This will have to be a process setting:
3841 bool keep_stopped = false;
3842 Detach(keep_stopped);
3843 }
3844
3845 m_destroy_in_process = true;
3846
3848 if (error.Success()) {
3849 EventSP exit_event_sp;
3850 if (DestroyRequiresHalt()) {
3851 error = StopForDestroyOrDetach(exit_event_sp);
3852 }
3853
3854 if (GetPublicState() == eStateStopped) {
3855 // Ditch all thread plans, and remove all our breakpoints: in case we
3856 // have to restart the target to kill it, we don't want it hitting a
3857 // breakpoint... Only do this if we've stopped, however, since if we
3858 // didn't manage to halt it above, then we're not going to have much luck
3859 // doing this now.
3860 m_thread_list.DiscardThreadPlans();
3862 if (auto error = FlushDelayedBreakpoints())
3864 GetLog(LLDBLog::Process), std::move(error),
3865 "Failed to update some delayed breakpoints during destroy: {0}");
3866 }
3867
3868 error = DoDestroy();
3869 if (error.Success()) {
3870 DidDestroy();
3872 }
3873 m_stdio_communication.StopReadThread();
3874 m_stdio_communication.Disconnect();
3875 m_stdin_forward = false;
3876
3877 {
3878 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3880 m_process_input_reader->SetIsDone(true);
3881 m_process_input_reader->Cancel();
3882 m_process_input_reader.reset();
3883 }
3884 }
3885
3886 // If we exited when we were waiting for a process to stop, then forward
3887 // the event here so we don't lose the event
3888 if (exit_event_sp) {
3889 // Directly broadcast our exited event because we shut down our private
3890 // state thread above
3891 BroadcastEvent(exit_event_sp);
3892 }
3893
3894 // If we have been interrupted (to kill us) in the middle of running, we
3895 // may not end up propagating the last events through the event system, in
3896 // which case we might strand the write lock. Unlock it here so when we do
3897 // to tear down the process we don't get an error destroying the lock.
3899 }
3900
3901 m_destroy_in_process = false;
3902
3903 return error;
3904}
3905
3908 if (error.Success()) {
3909 error = DoSignal(signal);
3910 if (error.Success())
3911 DidSignal();
3912 }
3913 return error;
3914}
3915
3917 assert(signals_sp && "null signals_sp");
3918 m_unix_signals_sp = std::move(signals_sp);
3919}
3920
3922 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3923 return m_unix_signals_sp;
3924}
3925
3929
3933
3935 const StateType state =
3937 bool return_value = true;
3939
3940 switch (state) {
3941 case eStateDetached:
3942 case eStateExited:
3943 case eStateUnloaded:
3944 m_stdio_communication.SynchronizeWithReadThread();
3945 m_stdio_communication.StopReadThread();
3946 m_stdio_communication.Disconnect();
3947 m_stdin_forward = false;
3948
3949 [[fallthrough]];
3950 case eStateConnected:
3951 case eStateAttaching:
3952 case eStateLaunching:
3953 // These events indicate changes in the state of the debugging session,
3954 // always report them.
3955 return_value = true;
3956 break;
3957 case eStateInvalid:
3958 // We stopped for no apparent reason, don't report it.
3959 return_value = false;
3960 break;
3961 case eStateRunning:
3962 case eStateStepping:
3963 // If we've started the target running, we handle the cases where we are
3964 // already running and where there is a transition from stopped to running
3965 // differently. running -> running: Automatically suppress extra running
3966 // events stopped -> running: Report except when there is one or more no
3967 // votes
3968 // and no yes votes.
3971 return_value = true;
3972 else {
3973 switch (m_last_broadcast_state) {
3974 case eStateRunning:
3975 case eStateStepping:
3976 // We always suppress multiple runnings with no PUBLIC stop in between.
3977 return_value = false;
3978 break;
3979 default:
3980 // TODO: make this work correctly. For now always report
3981 // run if we aren't running so we don't miss any running events. If I
3982 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3983 // and hit the breakpoints on multiple threads, then somehow during the
3984 // stepping over of all breakpoints no run gets reported.
3985
3986 // This is a transition from stop to run.
3987 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3988 case eVoteYes:
3989 case eVoteNoOpinion:
3990 return_value = true;
3991 break;
3992 case eVoteNo:
3993 return_value = false;
3994 break;
3995 }
3996 break;
3997 }
3998 }
3999 break;
4000 case eStateStopped:
4001 case eStateCrashed:
4002 case eStateSuspended:
4003 // We've stopped. First see if we're going to restart the target. If we
4004 // are going to stop, then we always broadcast the event. If we aren't
4005 // going to stop, let the thread plans decide if we're going to report this
4006 // event. If no thread has an opinion, we don't report it.
4007
4008 m_stdio_communication.SynchronizeWithReadThread();
4011 LLDB_LOGF(log,
4012 "Process::ShouldBroadcastEvent (%p) stopped due to an "
4013 "interrupt, state: %s",
4014 static_cast<void *>(event_ptr), StateAsCString(state));
4015 // Even though we know we are going to stop, we should let the threads
4016 // have a look at the stop, so they can properly set their state.
4017 m_thread_list.ShouldStop(event_ptr);
4018 return_value = true;
4019 } else {
4020 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
4021 bool should_resume = false;
4022
4023 // It makes no sense to ask "ShouldStop" if we've already been
4024 // restarted... Asking the thread list is also not likely to go well,
4025 // since we are running again. So in that case just report the event.
4026
4027 if (!was_restarted)
4028 should_resume = !m_thread_list.ShouldStop(event_ptr);
4029
4030 if (was_restarted || should_resume || m_resume_requested) {
4031 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
4032 LLDB_LOGF(log,
4033 "Process::ShouldBroadcastEvent: should_resume: %i state: "
4034 "%s was_restarted: %i report_stop_vote: %d.",
4035 should_resume, StateAsCString(state), was_restarted,
4036 report_stop_vote);
4037
4038 switch (report_stop_vote) {
4039 case eVoteYes:
4040 return_value = true;
4041 break;
4042 case eVoteNoOpinion:
4043 case eVoteNo:
4044 return_value = false;
4045 break;
4046 }
4047
4048 if (!was_restarted) {
4049 LLDB_LOGF(log,
4050 "Process::ShouldBroadcastEvent (%p) Restarting process "
4051 "from state: %s",
4052 static_cast<void *>(event_ptr), StateAsCString(state));
4054 PrivateResume();
4055 }
4056 } else {
4057 return_value = true;
4059 }
4060 }
4061 break;
4062 }
4063
4064 // Forcing the next event delivery is a one shot deal. So reset it here.
4066
4067 // We do some coalescing of events (for instance two consecutive running
4068 // events get coalesced.) But we only coalesce against events we actually
4069 // broadcast. So we use m_last_broadcast_state to track that. NB - you
4070 // can't use "m_public_state.GetValue()" for that purpose, as was originally
4071 // done, because the PublicState reflects the last event pulled off the
4072 // queue, and there may be several events stacked up on the queue unserviced.
4073 // So the PublicState may not reflect the last broadcasted event yet.
4074 // m_last_broadcast_state gets updated here.
4075
4076 if (return_value)
4077 m_last_broadcast_state = state;
4078
4079 LLDB_LOGF(log,
4080 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
4081 "broadcast state: %s - %s",
4082 static_cast<void *>(event_ptr), StateAsCString(state),
4084 return_value ? "YES" : "NO");
4085 return return_value;
4086}
4087
4089 llvm::Expected<HostThread> private_state_thread =
4092 [this] { return m_process.RunPrivateStateThread(m_purpose); },
4093 8 * 1024 * 1024);
4094 if (!private_state_thread) {
4095 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
4096 "failed to launch host thread: {0}");
4097 return false;
4098 }
4099
4100 assert(private_state_thread->IsJoinable());
4101 m_private_state_thread = *private_state_thread;
4102 m_is_running = true;
4103 m_process.ResumePrivateStateThread();
4104 return true;
4105}
4106
4108 return m_private_state_thread.EqualsThread(thread);
4109}
4110
4117
4119 lldb::StateType state, bool run_lock_is_running,
4120 std::shared_ptr<PrivateStateThread> *backup_ptr) {
4121 Log *log = GetLog(LLDBLog::Events);
4122
4123 bool already_running = PrivateStateThreadIsRunning();
4124 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
4125 already_running ? " already running"
4126 : " starting private state thread");
4127
4128 if (backup_ptr == nullptr && already_running)
4129 return true;
4130
4131 // Create a thread that watches our internal state and controls which events
4132 // make it to clients (into the DCProcess event queue).
4133 char thread_name[1024];
4134 uint32_t max_len = llvm::get_max_thread_name_length();
4135 if (max_len > 0 && max_len <= 30) {
4136 // On platforms with abbreviated thread name lengths, choose thread names
4137 // that fit within the limit.
4138 if (already_running)
4139 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4140 else
4141 snprintf(thread_name, sizeof(thread_name), "intern-state");
4142 } else {
4143 if (already_running)
4144 snprintf(thread_name, sizeof(thread_name),
4145 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
4146 GetID());
4147 else
4148 snprintf(thread_name, sizeof(thread_name),
4149 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
4150 }
4151
4152 if (backup_ptr) {
4153 // StartupThread expects the m_current_private_state_thread_sp to be in
4154 // place already, so do that first:
4157 *this, GetPublicState(), GetPrivateState(), thread_name,
4158 PrivateStateThread::Purpose::RunningExpression));
4159 } else
4160 m_current_private_state_thread_sp->SetThreadName(thread_name);
4161
4162 SetPublicState(state, /*restarted=*/false);
4163 if (run_lock_is_running)
4165 else
4167
4168 return m_current_private_state_thread_sp->StartupThread();
4169}
4170
4174
4178
4181 return;
4182
4183 if (m_current_private_state_thread_sp->IsJoinable())
4185 else {
4186 Log *log = GetLog(LLDBLog::Process);
4187 LLDB_LOGF(
4188 log,
4189 "Went to stop the private state thread, but it was already invalid.");
4190 }
4191}
4192
4194 Log *log = GetLog(LLDBLog::Process);
4195
4196 assert(signal == eBroadcastInternalStateControlStop ||
4199
4200 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
4201
4202 // Signal the private state thread
4203 if (m_current_private_state_thread_sp->IsJoinable()) {
4204 // Broadcast the event.
4205 // It is important to do this outside of the if below, because it's
4206 // possible that the thread state is invalid but that the thread is waiting
4207 // on a control event instead of simply being on its way out (this should
4208 // not happen, but it apparently can).
4209 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
4210 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
4211 m_private_state_control_broadcaster.BroadcastEvent(signal,
4212 event_receipt_sp);
4213
4214 // Wait for the event receipt or for the private state thread to exit
4215 bool receipt_received = false;
4217 while (!receipt_received) {
4218 // Check for a receipt for n seconds and then check if the private
4219 // state thread is still around.
4220 receipt_received =
4221 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
4222 if (!receipt_received) {
4223 // Check if the private state thread is still around. If it isn't
4224 // then we are done waiting
4226 break; // Private state thread exited or is exiting, we are done
4227 }
4228 }
4229 }
4230
4232 m_current_private_state_thread_sp->JoinAndReset();
4233
4234 } else {
4235 LLDB_LOGF(
4236 log,
4237 "Private state thread already dead, no need to signal it to stop.");
4238 }
4239}
4240
4242 if (thread != nullptr)
4243 m_interrupt_tid = thread->GetProtocolID();
4244 else
4248 nullptr);
4249 else
4251}
4252
4254 Log *log = GetLog(LLDBLog::Process);
4255 m_resume_requested = false;
4256
4257 const StateType new_state =
4259
4260 // First check to see if anybody wants a shot at this event:
4263 m_next_event_action_up->PerformAction(event_sp);
4264 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
4265
4266 switch (action_result) {
4268 SetNextEventAction(nullptr);
4269 break;
4270
4272 break;
4273
4275 // Handle Exiting Here. If we already got an exited event, we should
4276 // just propagate it. Otherwise, swallow this event, and set our state
4277 // to exit so the next event will kill us.
4278 if (new_state != eStateExited) {
4279 // FIXME: should cons up an exited event, and discard this one.
4280 SetExitStatus(0, m_next_event_action_up->GetExitString());
4281 SetNextEventAction(nullptr);
4282 return;
4283 }
4284 SetNextEventAction(nullptr);
4285 break;
4286 }
4287 }
4288
4289 // See if we should broadcast this state to external clients?
4290 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
4291
4292 if (should_broadcast) {
4293 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
4294 LLDB_LOGF(log,
4295 "Process::%s (pid = %" PRIu64
4296 ") broadcasting new state %s (old state %s) to %s",
4297 __FUNCTION__, GetID(), StateAsCString(new_state),
4298 StateAsCString(GetState()), is_hijacked ? "hijacked" : "public");
4300 if (StateIsRunningState(new_state)) {
4301 // Only push the input handler if we aren't fowarding events, as this
4302 // means the curses GUI is in use... Or don't push it if we are launching
4303 // since it will come up stopped.
4304 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
4305 new_state != eStateLaunching && new_state != eStateAttaching) {
4307 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
4309 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
4310 __FUNCTION__, m_iohandler_sync.GetValue());
4311 }
4312 } else if (StateIsStoppedState(new_state, false)) {
4314 // If the lldb_private::Debugger is handling the events, we don't want
4315 // to pop the process IOHandler here, we want to do it when we receive
4316 // the stopped event so we can carefully control when the process
4317 // IOHandler is popped because when we stop we want to display some
4318 // text stating how and why we stopped, then maybe some
4319 // process/thread/frame info, and then we want the "(lldb) " prompt to
4320 // show up. If we pop the process IOHandler here, then we will cause
4321 // the command interpreter to become the top IOHandler after the
4322 // process pops off and it will update its prompt right away... See the
4323 // Debugger.cpp file where it calls the function as
4324 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4325 // Otherwise we end up getting overlapping "(lldb) " prompts and
4326 // garbled output.
4327 //
4328 // If we aren't handling the events in the debugger (which is indicated
4329 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
4330 // we are hijacked, then we always pop the process IO handler manually.
4331 // Hijacking happens when the internal process state thread is running
4332 // thread plans, or when commands want to run in synchronous mode and
4333 // they call "process->WaitForProcessToStop()". An example of something
4334 // that will hijack the events is a simple expression:
4335 //
4336 // (lldb) expr (int)puts("hello")
4337 //
4338 // This will cause the internal process state thread to resume and halt
4339 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4340 // events) and we do need the IO handler to be pushed and popped
4341 // correctly.
4342
4343 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
4345 }
4346 }
4347
4348 BroadcastEvent(event_sp);
4349 } else {
4350 LLDB_LOGF(
4351 log,
4352 "Process::%s (pid = %" PRIu64
4353 ") suppressing state %s (old state %s): should_broadcast == false",
4354 __FUNCTION__, GetID(), StateAsCString(new_state),
4356 }
4357}
4358
4360 EventSP event_sp;
4362 if (error.Fail())
4363 return error;
4364
4365 // Ask the process subclass to actually halt our process
4366 bool caused_stop;
4367 error = DoHalt(caused_stop);
4368
4369 DidHalt();
4370 return error;
4371}
4372
4375 // All PSTs see the private reality (private state, private run lock).
4376 // A PST created to run an expression additionally skips frame providers
4377 // and recognizers, since that's the only reason RunThreadPlan spins up a
4378 // second, temporary PST while the primary one is backed up.
4379 PolicyStack::Guard policy_guard =
4381
4382 bool control_only = true;
4383
4384 Log *log = GetLog(LLDBLog::Process);
4385 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4386 __FUNCTION__, static_cast<void *>(this), GetID());
4387
4388 bool exit_now = false;
4389 bool interrupt_requested = false;
4390 while (!exit_now) {
4391 EventSP event_sp;
4392 GetEventsPrivate(event_sp, std::nullopt, control_only);
4393 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4394 LLDB_LOGF(log,
4395 "Process::%s (arg = %p, pid = %" PRIu64
4396 ") got a control event: %d",
4397 __FUNCTION__, static_cast<void *>(this), GetID(),
4398 event_sp->GetType());
4399
4400 switch (event_sp->GetType()) {
4402 exit_now = true;
4403 break; // doing any internal state management below
4404
4406 control_only = true;
4407 break;
4408
4410 control_only = false;
4411 break;
4412 }
4413
4414 continue;
4415 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4417 LLDB_LOGF(log,
4418 "Process::%s (arg = %p, pid = %" PRIu64
4419 ") woke up with an interrupt while attaching - "
4420 "forwarding interrupt.",
4421 __FUNCTION__, static_cast<void *>(this), GetID());
4422 // The server may be spinning waiting for a process to appear, in which
4423 // case we should tell it to stop doing that. Normally, we don't NEED
4424 // to do that because we will next close the communication to the stub
4425 // and that will get it to shut down. But there are remote debugging
4426 // cases where relying on that side-effect causes the shutdown to be
4427 // flakey, so we should send a positive signal to interrupt the wait.
4431 LLDB_LOGF(log,
4432 "Process::%s (arg = %p, pid = %" PRIu64
4433 ") woke up with an interrupt - Halting.",
4434 __FUNCTION__, static_cast<void *>(this), GetID());
4436 if (error.Fail() && log)
4437 LLDB_LOGF(log,
4438 "Process::%s (arg = %p, pid = %" PRIu64
4439 ") failed to halt the process: %s",
4440 __FUNCTION__, static_cast<void *>(this), GetID(),
4441 error.AsCString());
4442 // Halt should generate a stopped event. Make a note of the fact that
4443 // we were doing the interrupt, so we can set the interrupted flag
4444 // after we receive the event. We deliberately set this to true even if
4445 // HaltPrivate failed, so that we can interrupt on the next natural
4446 // stop.
4447 interrupt_requested = true;
4448 } else {
4449 // This can happen when someone (e.g. Process::Halt) sees that we are
4450 // running and sends an interrupt request, but the process actually
4451 // stops before we receive it. In that case, we can just ignore the
4452 // request. We use m_last_broadcast_state, because the Stopped event
4453 // may not have been popped of the event queue yet, which is when the
4454 // public state gets updated.
4455 LLDB_LOGF(log,
4456 "Process::%s ignoring interrupt as we have already stopped.",
4457 __FUNCTION__);
4458 }
4459 continue;
4460 }
4461
4462 const StateType internal_state =
4464
4465 if (internal_state != eStateInvalid) {
4467 StateIsStoppedState(internal_state, true)) {
4469 m_thread_list.DiscardThreadPlans();
4470 }
4471
4472 if (interrupt_requested) {
4473 if (StateIsStoppedState(internal_state, true)) {
4474 // Only mark interrupt event if it is not thread specific async
4475 // interrupt.
4477 // We requested the interrupt, so mark this as such in the stop
4478 // event so clients can tell an interrupted process from a natural
4479 // stop
4480 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4481 }
4482 interrupt_requested = false;
4483 } else {
4484 LLDB_LOGF(log,
4485 "Process::%s interrupt_requested, but a non-stopped "
4486 "state '%s' received.",
4487 __FUNCTION__, StateAsCString(internal_state));
4488 }
4489 }
4490
4491 HandlePrivateEvent(event_sp);
4492 }
4493
4494 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4495 internal_state == eStateDetached) {
4496 LLDB_LOGF(log,
4497 "Process::%s (arg = %p, pid = %" PRIu64
4498 ") about to exit with internal state %s...",
4499 __FUNCTION__, static_cast<void *>(this), GetID(),
4500 StateAsCString(internal_state));
4501
4502 break;
4503 }
4504 }
4505
4506 // Verify log is still enabled before attempting to write to it...
4507 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4508 __FUNCTION__, static_cast<void *>(this), GetID());
4509
4511 return {};
4512}
4513
4514// Process Event Data
4515
4517
4519 StateType state)
4520 : EventData(), m_process_wp(), m_state(state) {
4521 if (process_sp)
4522 m_process_wp = process_sp;
4523}
4524
4526
4528 return "Process::ProcessEventData";
4529}
4530
4534
4536 bool &found_valid_stopinfo) {
4537 found_valid_stopinfo = false;
4538
4539 ProcessSP process_sp(m_process_wp.lock());
4540 if (!process_sp)
4541 return false;
4542
4543 ThreadList &curr_thread_list = process_sp->GetThreadList();
4544 uint32_t num_threads = curr_thread_list.GetSize();
4545
4546 // The actions might change one of the thread's stop_info's opinions about
4547 // whether we should stop the process, so we need to query that as we go.
4548
4549 // One other complication here, is that we try to catch any case where the
4550 // target has run (except for expressions) and immediately exit, but if we
4551 // get that wrong (which is possible) then the thread list might have
4552 // changed, and that would cause our iteration here to crash. We could
4553 // make a copy of the thread list, but we'd really like to also know if it
4554 // has changed at all, so we store the original thread ID's of all threads and
4555 // check what we get back against this list & bag out if anything differs.
4556 std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;
4557 for (uint32_t idx = 0; idx < num_threads; ++idx) {
4558 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4559
4560 /*
4561 Filter out all suspended threads, they could not be the reason
4562 of stop and no need to perform any actions on them.
4563 */
4564 if (thread_sp->GetResumeState() != eStateSuspended)
4565 not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());
4566 }
4567
4568 // Use this to track whether we should continue from here. We will only
4569 // continue the target running if no thread says we should stop. Of course
4570 // if some thread's PerformAction actually sets the target running, then it
4571 // doesn't matter what the other threads say...
4572
4573 bool still_should_stop = false;
4574
4575 // Sometimes - for instance if we have a bug in the stub we are talking to,
4576 // we stop but no thread has a valid stop reason. In that case we should
4577 // just stop, because we have no way of telling what the right thing to do
4578 // is, and it's better to let the user decide than continue behind their
4579 // backs.
4580
4581 for (auto [thread_sp, thread_index] : not_suspended_threads) {
4582 if (curr_thread_list.GetSize() != num_threads) {
4584 LLDB_LOGF(
4585 log,
4586 "Number of threads changed from %u to %u while processing event.",
4587 num_threads, curr_thread_list.GetSize());
4588 break;
4589 }
4590
4591 if (thread_sp->GetIndexID() != thread_index) {
4593 LLDB_LOG(log,
4594 "The thread {0} changed from {1} to {2} while processing event.",
4595 thread_sp.get(), thread_index, thread_sp->GetIndexID());
4596 break;
4597 }
4598
4599 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4600 if (stop_info_sp && stop_info_sp->IsValid()) {
4601 found_valid_stopinfo = true;
4602 bool this_thread_wants_to_stop;
4603 if (stop_info_sp->GetOverrideShouldStop()) {
4604 this_thread_wants_to_stop =
4605 stop_info_sp->GetOverriddenShouldStopValue();
4606 } else {
4607 stop_info_sp->PerformAction(event_ptr);
4608 // The stop action might restart the target. If it does, then we
4609 // want to mark that in the event so that whoever is receiving it
4610 // will know to wait for the running event and reflect that state
4611 // appropriately. We also need to stop processing actions, since they
4612 // aren't expecting the target to be running.
4613
4614 // Clear the selected frame which may have been set as part of utility
4615 // expressions that have been run as part of this stop. If we didn't
4616 // clear this, then StopInfo::GetSuggestedStackFrameIndex would not
4617 // take affect when we next called SelectMostRelevantFrame.
4618 // PerformAction should not be the one setting a selected frame, instead
4619 // this should be done via GetSuggestedStackFrameIndex.
4620 thread_sp->ClearSelectedFrameIndex();
4621
4622 // FIXME: we might have run.
4623 if (stop_info_sp->HasTargetRunSinceMe()) {
4624 SetRestarted(true);
4625 break;
4626 }
4627
4628 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4629 }
4630
4631 if (!still_should_stop)
4632 still_should_stop = this_thread_wants_to_stop;
4633 }
4634 }
4635
4636 return still_should_stop;
4637}
4638
4640 Event *event_ptr) {
4641 // STDIO and the other async event notifications should always be forwarded.
4642 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4643 return true;
4644
4645 // For state changed events, if the update state is zero, we are handling
4646 // this on the private state thread. We should wait for the public event.
4647 // After the primary listener processes it in DoOnRemoval, m_update_state
4648 // is incremented from 1 to 2, which is when we forward to pending
4649 // (secondary) listeners.
4650 return m_update_state > 1;
4651}
4652
4654 // We only have work to do for state changed events:
4655 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4656 return;
4657
4658 ProcessSP process_sp(m_process_wp.lock());
4659
4660 if (!process_sp)
4661 return;
4662
4663 // This function gets called twice for each event, once when the event gets
4664 // pulled off of the private process event queue, and then any number of
4665 // times, first when it gets pulled off of the public event queue, then other
4666 // times when we're pretending that this is where we stopped at the end of
4667 // expression evaluation. m_update_state is used to distinguish these
4668 // cases; it is 0 when we're just pulling it off for private handling, 1
4669 // when the primary public listener consumes it, and > 1 after that (e.g.
4670 // secondary listeners or expression evaluation) where we don't want to
4671 // redo the breakpoint command handling or stop hooks.
4672 if (m_update_state != 1)
4673 return;
4675
4676 process_sp->SetPublicState(
4678
4679 if (m_state == eStateStopped && !m_restarted) {
4680 // Let process subclasses know we are about to do a public stop and do
4681 // anything they might need to in order to speed up register and memory
4682 // accesses.
4683 process_sp->WillPublicStop();
4684 }
4685
4686 // If this is a halt event, even if the halt stopped with some reason other
4687 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4688 // the halt request came through) don't do the StopInfo actions, as they may
4689 // end up restarting the process.
4690 if (m_interrupted)
4691 return;
4692
4693 // If we're not stopped or have restarted, then skip the StopInfo actions:
4694 if (m_state != eStateStopped || m_restarted) {
4695 return;
4696 }
4697
4698 bool does_anybody_have_an_opinion = false;
4699 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4700
4701 if (GetRestarted()) {
4702 return;
4703 }
4704
4705 if (!still_should_stop && does_anybody_have_an_opinion) {
4706 // We've been asked to continue, so do that here.
4707 SetRestarted(true);
4708 // Use the private resume method here, since we aren't changing the run
4709 // lock state.
4710 process_sp->PrivateResume();
4711 } else {
4712 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4713 !process_sp->StateChangedIsHijackedForSynchronousResume();
4714
4715 if (!hijacked) {
4716 // If we didn't restart, run the Stop Hooks here.
4717 // Don't do that if state changed events aren't hooked up to the
4718 // public (or SyncResume) broadcasters. StopHooks are just for
4719 // real public stops. They might also restart the target,
4720 // so watch for that.
4721 if (process_sp->GetTarget().RunStopHooks())
4722 SetRestarted(true);
4723 }
4724 }
4725}
4726
4728 ProcessSP process_sp(m_process_wp.lock());
4729
4730 if (process_sp)
4731 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4732 static_cast<void *>(process_sp.get()), process_sp->GetID());
4733 else
4734 s->PutCString(" process = NULL, ");
4735
4736 s->Printf("state = %s", StateAsCString(GetState()));
4737}
4738
4741 if (event_ptr) {
4742 const EventData *event_data = event_ptr->GetData();
4743 if (event_data &&
4745 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4746 }
4747 return nullptr;
4748}
4749
4752 ProcessSP process_sp;
4753 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4754 if (data)
4755 process_sp = data->GetProcessSP();
4756 return process_sp;
4757}
4758
4760 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4761 if (data == nullptr)
4762 return eStateInvalid;
4763 else
4764 return data->GetState();
4765}
4766
4768 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4769 if (data == nullptr)
4770 return false;
4771 else
4772 return data->GetRestarted();
4773}
4774
4776 bool new_value) {
4777 ProcessEventData *data =
4778 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4779 if (data != nullptr)
4780 data->SetRestarted(new_value);
4781}
4782
4783size_t
4785 ProcessEventData *data =
4786 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4787 if (data != nullptr)
4788 return data->GetNumRestartedReasons();
4789 else
4790 return 0;
4791}
4792
4793const char *
4795 size_t idx) {
4796 ProcessEventData *data =
4797 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4798 if (data != nullptr)
4799 return data->GetRestartedReasonAtIndex(idx);
4800 else
4801 return nullptr;
4802}
4803
4805 const char *reason) {
4806 ProcessEventData *data =
4807 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4808 if (data != nullptr)
4809 data->AddRestartedReason(reason);
4810}
4811
4813 const Event *event_ptr) {
4814 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4815 if (data == nullptr)
4816 return false;
4817 else
4818 return data->GetInterrupted();
4819}
4820
4822 bool new_value) {
4823 ProcessEventData *data =
4824 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4825 if (data != nullptr)
4826 data->SetInterrupted(new_value);
4827}
4828
4830 ProcessEventData *data =
4831 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4832 if (data) {
4834 return true;
4835 }
4836 return false;
4837}
4838
4840
4842 exe_ctx.SetTargetPtr(&GetTarget());
4843 exe_ctx.SetProcessPtr(this);
4844 exe_ctx.SetThreadPtr(nullptr);
4845 exe_ctx.SetFramePtr(nullptr);
4846}
4847
4848// uint32_t
4849// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4850// std::vector<lldb::pid_t> &pids)
4851//{
4852// return 0;
4853//}
4854//
4855// ArchSpec
4856// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4857//{
4858// return Host::GetArchSpecForExistingProcess (pid);
4859//}
4860//
4861// ArchSpec
4862// Process::GetArchSpecForExistingProcess (const char *process_name)
4863//{
4864// return Host::GetArchSpecForExistingProcess (process_name);
4865//}
4866
4868 auto event_data_sp =
4869 std::make_shared<ProcessEventData>(shared_from_this(), GetState());
4870 return std::make_shared<Event>(event_type, event_data_sp);
4871}
4872
4873void Process::AppendSTDOUT(const char *s, size_t len) {
4874 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4875 m_stdout_data.append(s, len);
4877 BroadcastEventIfUnique(event_sp);
4878}
4879
4880void Process::AppendSTDERR(const char *s, size_t len) {
4881 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4882 m_stderr_data.append(s, len);
4884 BroadcastEventIfUnique(event_sp);
4885}
4886
4887void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4888 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4889 m_profile_data.push_back(one_profile_data);
4891 BroadcastEventIfUnique(event_sp);
4892}
4893
4895 const StructuredDataPluginSP &plugin_sp) {
4896 auto data_sp = std::make_shared<EventDataStructuredData>(
4897 shared_from_this(), object_sp, plugin_sp);
4899}
4900
4902Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4903 auto find_it = m_structured_data_plugin_map.find(type_name);
4904 if (find_it != m_structured_data_plugin_map.end())
4905 return find_it->second;
4906 else
4907 return StructuredDataPluginSP();
4908}
4909
4910size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4911 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4912 if (m_profile_data.empty())
4913 return 0;
4914
4915 std::string &one_profile_data = m_profile_data.front();
4916 size_t bytes_available = one_profile_data.size();
4917 if (bytes_available > 0) {
4918 Log *log = GetLog(LLDBLog::Process);
4919 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4920 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4921 if (bytes_available > buf_size) {
4922 memcpy(buf, one_profile_data.c_str(), buf_size);
4923 one_profile_data.erase(0, buf_size);
4924 bytes_available = buf_size;
4925 } else {
4926 memcpy(buf, one_profile_data.c_str(), bytes_available);
4927 m_profile_data.erase(m_profile_data.begin());
4928 }
4929 }
4930 return bytes_available;
4931}
4932
4933// Process STDIO
4934
4935size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4936 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4937 size_t bytes_available = m_stdout_data.size();
4938 if (bytes_available > 0) {
4939 Log *log = GetLog(LLDBLog::Process);
4940 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4941 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4942 if (bytes_available > buf_size) {
4943 memcpy(buf, m_stdout_data.c_str(), buf_size);
4944 m_stdout_data.erase(0, buf_size);
4945 bytes_available = buf_size;
4946 } else {
4947 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4948 m_stdout_data.clear();
4949 }
4950 }
4951 return bytes_available;
4952}
4953
4954size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4955 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4956 size_t bytes_available = m_stderr_data.size();
4957 if (bytes_available > 0) {
4958 Log *log = GetLog(LLDBLog::Process);
4959 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4960 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4961 if (bytes_available > buf_size) {
4962 memcpy(buf, m_stderr_data.c_str(), buf_size);
4963 m_stderr_data.erase(0, buf_size);
4964 bytes_available = buf_size;
4965 } else {
4966 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4967 m_stderr_data.clear();
4968 }
4969 }
4970 return bytes_available;
4971}
4972
4973void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4974 size_t src_len) {
4975 Process *process = (Process *)baton;
4976 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4977}
4978
4980 // First set up the Read Thread for reading/handling process I/O
4981 m_stdio_communication.SetConnection(
4982 std::make_unique<ConnectionFileDescriptor>(fd, true));
4983 if (m_stdio_communication.IsConnected()) {
4984 m_stdio_communication.SetReadThreadBytesReceivedCallback(
4986 m_stdio_communication.StartReadThread();
4987
4988 // Now read thread is set up, set up input reader.
4989 {
4990 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
4993 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
4994 }
4995 }
4996}
4997
4999 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5000 IOHandlerSP io_handler_sp(m_process_input_reader);
5001 if (io_handler_sp)
5002 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
5003 return false;
5004}
5005
5007 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5008 IOHandlerSP io_handler_sp(m_process_input_reader);
5009 if (io_handler_sp) {
5010 Log *log = GetLog(LLDBLog::Process);
5011 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
5012
5013 io_handler_sp->SetIsDone(false);
5014 // If we evaluate an utility function, then we don't cancel the current
5015 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
5016 // existing IOHandler that potentially provides the user interface (e.g.
5017 // the IOHandler for Editline).
5018 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
5019 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
5020 cancel_top_handler);
5021 return true;
5022 }
5023 return false;
5024}
5025
5027 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5028 IOHandlerSP io_handler_sp(m_process_input_reader);
5029 if (io_handler_sp)
5030 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
5031 return false;
5032}
5033
5034// The process needs to know about installed plug-ins
5036
5038
5039namespace {
5040// RestorePlanState is used to record the "is private", "is controlling" and
5041// "okay
5042// to discard" fields of the plan we are running, and reset it on Clean or on
5043// destruction. It will only reset the state once, so you can call Clean and
5044// then monkey with the state and it won't get reset on you again.
5045
5046class RestorePlanState {
5047public:
5048 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
5049 : m_thread_plan_sp(thread_plan_sp) {
5050 if (m_thread_plan_sp) {
5051 m_private = m_thread_plan_sp->GetPrivate();
5052 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
5053 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5054 }
5055 }
5056
5057 ~RestorePlanState() { Clean(); }
5058
5059 void Clean() {
5060 if (!m_already_reset && m_thread_plan_sp) {
5061 m_already_reset = true;
5062 m_thread_plan_sp->SetPrivate(m_private);
5063 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
5064 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5065 }
5066 }
5067
5068private:
5069 lldb::ThreadPlanSP m_thread_plan_sp;
5070 bool m_already_reset = false;
5071 bool m_private = false;
5072 bool m_is_controlling = false;
5073 bool m_okay_to_discard = false;
5074};
5075} // anonymous namespace
5076
5077static microseconds
5079 const milliseconds default_one_thread_timeout(250);
5080
5081 // If the overall wait is forever, then we don't need to worry about it.
5082 if (!options.GetTimeout()) {
5083 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
5084 : default_one_thread_timeout;
5085 }
5086
5087 // If the one thread timeout is set, use it.
5088 if (options.GetOneThreadTimeout())
5089 return *options.GetOneThreadTimeout();
5090
5091 // Otherwise use half the total timeout, bounded by the
5092 // default_one_thread_timeout.
5093 return std::min<microseconds>(default_one_thread_timeout,
5094 *options.GetTimeout() / 2);
5095}
5096
5097static Timeout<std::micro>
5099 bool before_first_timeout) {
5100 // If we are going to run all threads the whole time, or if we are only going
5101 // to run one thread, we can just return the overall timeout.
5102 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5103 return options.GetTimeout();
5104
5105 if (before_first_timeout)
5106 return GetOneThreadExpressionTimeout(options);
5107
5108 if (!options.GetTimeout())
5109 return std::nullopt;
5110 else
5111 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
5112}
5113
5114static std::optional<ExpressionResults>
5115HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
5116 RestorePlanState &restorer, const EventSP &event_sp,
5117 EventSP &event_to_broadcast_sp,
5118 const EvaluateExpressionOptions &options,
5119 bool handle_interrupts) {
5121
5122 ThreadSP thread_sp = thread_plan_sp->GetTarget()
5123 .GetProcessSP()
5124 ->GetThreadList()
5125 .FindThreadByID(thread_id);
5126 if (!thread_sp) {
5127 LLDB_LOG(log,
5128 "The thread on which we were running the "
5129 "expression: tid = {0}, exited while "
5130 "the expression was running.",
5131 thread_id);
5133 }
5134
5135 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
5136 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
5137 LLDB_LOG(log, "execution completed successfully");
5138
5139 // Restore the plan state so it will get reported as intended when we are
5140 // done.
5141 restorer.Clean();
5142 return eExpressionCompleted;
5143 }
5144
5145 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5146 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
5147 stop_info_sp->ShouldNotify(event_sp.get())) {
5148 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
5149 if (!options.DoesIgnoreBreakpoints()) {
5150 // Restore the plan state and then force Private to false. We are going
5151 // to stop because of this plan so we need it to become a public plan or
5152 // it won't report correctly when we continue to its termination later
5153 // on.
5154 restorer.Clean();
5155 thread_plan_sp->SetPrivate(false);
5156 event_to_broadcast_sp = event_sp;
5157 }
5159 }
5160
5161 if (!handle_interrupts &&
5163 return std::nullopt;
5164
5165 LLDB_LOG(log, "thread plan did not successfully complete");
5166 if (!options.DoesUnwindOnError())
5167 event_to_broadcast_sp = event_sp;
5169}
5170
5173 lldb::ThreadPlanSP &thread_plan_sp,
5174 const EvaluateExpressionOptions &options,
5175 DiagnosticManager &diagnostic_manager) {
5177
5178 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
5179
5180 if (!thread_plan_sp) {
5181 diagnostic_manager.PutString(
5182 lldb::eSeverityError, "RunThreadPlan called with empty thread plan.");
5183 return eExpressionSetupError;
5184 }
5185
5186 if (!thread_plan_sp->ValidatePlan(nullptr)) {
5187 diagnostic_manager.PutString(
5189 "RunThreadPlan called with an invalid thread plan.");
5190 return eExpressionSetupError;
5191 }
5192
5193 if (exe_ctx.GetProcessPtr() != this) {
5194 diagnostic_manager.PutString(lldb::eSeverityError,
5195 "RunThreadPlan called on wrong process.");
5196 return eExpressionSetupError;
5197 }
5198
5199 Thread *thread = exe_ctx.GetThreadPtr();
5200 if (thread == nullptr) {
5201 diagnostic_manager.PutString(lldb::eSeverityError,
5202 "RunThreadPlan called with invalid thread.");
5203 return eExpressionSetupError;
5204 }
5205
5206 // Record the thread's id so we can tell when a thread we were using
5207 // to run the expression exits during the expression evaluation.
5208 lldb::tid_t expr_thread_id = thread->GetID();
5209
5210 // We need to change some of the thread plan attributes for the thread plan
5211 // runner. This will restore them when we are done:
5212
5213 RestorePlanState thread_plan_restorer(thread_plan_sp);
5214
5215 // We rely on the thread plan we are running returning "PlanCompleted" if
5216 // when it successfully completes. For that to be true the plan can't be
5217 // private - since private plans suppress themselves in the GetCompletedPlan
5218 // call.
5219
5220 thread_plan_sp->SetPrivate(false);
5221
5222 // The plans run with RunThreadPlan also need to be terminal controlling plans
5223 // or when they are done we will end up asking the plan above us whether we
5224 // should stop, which may give the wrong answer.
5225
5226 thread_plan_sp->SetIsControllingPlan(true);
5227 thread_plan_sp->SetOkayToDiscard(false);
5228
5229 // If we are running some utility expression for LLDB, we now have to mark
5230 // this in the ProcesModID of this process. This RAII takes care of marking
5231 // and reverting the mark it once we are done running the expression.
5232 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
5233
5234 if (GetPrivateState() != eStateStopped) {
5235 diagnostic_manager.PutString(
5237 "RunThreadPlan called while the private state was not stopped.");
5238 return eExpressionSetupError;
5239 }
5240
5241 // Save the thread & frame from the exe_ctx for restoration after we run
5242 const uint32_t thread_idx_id = thread->GetIndexID();
5243 StackFrameSP selected_frame_sp =
5244 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5245 if (!selected_frame_sp) {
5246 thread->SetSelectedFrame(nullptr);
5247 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5248 if (!selected_frame_sp) {
5249 diagnostic_manager.Printf(
5251 "RunThreadPlan called without a selected frame on thread %d",
5252 thread_idx_id);
5253 return eExpressionSetupError;
5254 }
5255 }
5256
5257 // Make sure the timeout values make sense. The one thread timeout needs to
5258 // be smaller than the overall timeout.
5259 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
5260 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
5261 diagnostic_manager.PutString(lldb::eSeverityError,
5262 "RunThreadPlan called with one thread "
5263 "timeout greater than total timeout");
5264 return eExpressionSetupError;
5265 }
5266
5267 // If the ExecutionContext has a frame, we want to make sure to save/restore
5268 // that frame into exe_ctx. This can happen when we run expressions from a
5269 // non-selected SBFrame, in which case we don't want some thread-plan
5270 // to overwrite the ExecutionContext frame.
5271 StackID ctx_frame_id = exe_ctx.HasFrameScope()
5272 ? exe_ctx.GetFrameRef().GetStackID()
5273 : selected_frame_sp->GetStackID();
5274
5275 // N.B. Running the target may unset the currently selected thread and frame.
5276 // We don't want to do that either, so we should arrange to reset them as
5277 // well.
5278
5279 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
5280
5281 uint32_t selected_tid;
5282 StackID selected_stack_id;
5283 if (selected_thread_sp) {
5284 selected_tid = selected_thread_sp->GetIndexID();
5285 selected_stack_id =
5286 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
5287 ->GetStackID();
5288 } else {
5289 selected_tid = LLDB_INVALID_THREAD_ID;
5290 }
5291
5292 std::shared_ptr<PrivateStateThread> backup_private_state_thread;
5293 lldb::StateType old_state = eStateInvalid;
5294 lldb::ThreadPlanSP stopper_base_plan_sp;
5295
5298 // Yikes, we are running on the private state thread! So we can't wait for
5299 // public events on this thread, since we are the thread that is generating
5300 // public events. The simplest thing to do is to spin up a temporary thread
5301 // to handle private state thread events while we are fielding public
5302 // events here.
5303 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
5304 "another state thread to handle the events.");
5305
5306 // One other bit of business: we want to run just this thread plan and
5307 // anything it pushes, and then stop, returning control here. But in the
5308 // normal course of things, the plan above us on the stack would be given a
5309 // shot at the stop event before deciding to stop, and we don't want that.
5310 // So we insert a "stopper" base plan on the stack before the plan we want
5311 // to run. Since base plans always stop and return control to the user,
5312 // that will do just what we want.
5313 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
5314 thread->QueueThreadPlan(stopper_base_plan_sp, false);
5315 // Have to make sure our public state is stopped, since otherwise the
5316 // reporting logic below doesn't work correctly.
5317 old_state = GetPublicState();
5318 m_current_private_state_thread_sp->SetPublicStateNoLock(eStateStopped);
5319
5320 // Now spin up the private state thread:
5321 StartPrivateStateThread(lldb::eStateStopped, /* RunLock is stopped*/ false,
5322 &backup_private_state_thread);
5324 // If we can't spin up a thread here we can't run this expression. But
5325 // presumably the old private state thread is still good, so just put it
5326 // back and return an error.
5327 diagnostic_manager.Printf(
5329 "could not spin up a thread to handle events for an expression"
5330 " run on the private state thread.");
5331 m_current_private_state_thread_sp = backup_private_state_thread;
5332 return eExpressionSetupError;
5333 }
5334 }
5335
5336 thread->QueueThreadPlan(
5337 thread_plan_sp, false); // This used to pass "true" does that make sense?
5338
5339 if (options.GetDebug()) {
5340 // In this case, we aren't actually going to run, we just want to stop
5341 // right away. Flush this thread so we will refetch the stacks and show the
5342 // correct backtrace.
5343 // FIXME: To make this prettier we should invent some stop reason for this,
5344 // but that
5345 // is only cosmetic, and this functionality is only of use to lldb
5346 // developers who can live with not pretty...
5347 thread->Flush();
5349 }
5350
5351 ListenerSP listener_sp(
5352 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5353
5354 lldb::EventSP event_to_broadcast_sp;
5355
5356 {
5357 // This process event hijacker Hijacks the Public events and its destructor
5358 // makes sure that the process events get restored on exit to the function.
5359 //
5360 // If the event needs to propagate beyond the hijacker (e.g., the process
5361 // exits during execution), then the event is put into
5362 // event_to_broadcast_sp for rebroadcasting.
5363
5364 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5365
5366 if (log) {
5367 StreamString s;
5368 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5369 LLDB_LOGF(log,
5370 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5371 " to run thread plan \"%s\".",
5372 thread_idx_id, expr_thread_id, s.GetData());
5373 }
5374
5375 bool got_event;
5376 lldb::EventSP event_sp;
5378
5379 bool before_first_timeout = true; // This is set to false the first time
5380 // that we have to halt the target.
5381 bool do_resume = true;
5382 bool handle_running_event = true;
5383
5384 // This is just for accounting:
5385 uint32_t num_resumes = 0;
5386
5387 // If we are going to run all threads the whole time, or if we are only
5388 // going to run one thread, then we don't need the first timeout. So we
5389 // pretend we are after the first timeout already.
5390 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5391 before_first_timeout = false;
5392
5393 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
5394 options.GetStopOthers(), options.GetTryAllThreads(),
5395 before_first_timeout);
5396
5397 // This isn't going to work if there are unfetched events on the queue. Are
5398 // there cases where we might want to run the remaining events here, and
5399 // then try to call the function? That's probably being too tricky for our
5400 // own good.
5401
5402 Event *other_events = listener_sp->PeekAtNextEvent();
5403 if (other_events != nullptr) {
5404 diagnostic_manager.PutString(
5406 "RunThreadPlan called with pending events on the queue.");
5407 return eExpressionSetupError;
5408 }
5409
5410 // We also need to make sure that the next event is delivered. We might be
5411 // calling a function as part of a thread plan, in which case the last
5412 // delivered event could be the running event, and we don't want event
5413 // coalescing to cause us to lose OUR running event...
5415
5416// This while loop must exit out the bottom, there's cleanup that we need to do
5417// when we are done. So don't call return anywhere within it.
5418
5419#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5420 // It's pretty much impossible to write test cases for things like: One
5421 // thread timeout expires, I go to halt, but the process already stopped on
5422 // the function call stop breakpoint. Turning on this define will make us
5423 // not fetch the first event till after the halt. So if you run a quick
5424 // function, it will have completed, and the completion event will be
5425 // waiting, when you interrupt for halt. The expression evaluation should
5426 // still succeed.
5427 bool miss_first_event = true;
5428#endif
5429 bool pending_stop_on_vfork_done = false;
5430
5431 // If we spawned an override PST, mark the current (original) PST so
5432 // GetStackFrameList returns parent frames during event processing.
5433 std::optional<PolicyStack::Guard> policy_guard;
5434 if (backup_private_state_thread)
5435 policy_guard = PolicyStack::Get().PushPrivateState(
5437
5438 while (true) {
5439 // We usually want to resume the process if we get to the top of the
5440 // loop. The only exception is if we get two running events with no
5441 // intervening stop, which can happen, we will just wait for then next
5442 // stop event.
5443 LLDB_LOGF(log,
5444 "Top of while loop: do_resume: %i handle_running_event: %i "
5445 "before_first_timeout: %i.",
5446 do_resume, handle_running_event, before_first_timeout);
5447
5448 if (do_resume || handle_running_event) {
5449 // Do the initial resume and wait for the running event before going
5450 // further.
5451
5452 if (do_resume) {
5453 num_resumes++;
5454 Status resume_error = PrivateResume();
5455 if (!resume_error.Success()) {
5456 diagnostic_manager.Printf(
5458 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5459 resume_error.AsCString());
5460 return_value = eExpressionSetupError;
5461 break;
5462 }
5463 }
5464
5465 got_event =
5466 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5467 if (!got_event) {
5468 LLDB_LOGF(log,
5469 "Process::RunThreadPlan(): didn't get any event after "
5470 "resume %" PRIu32 ", exiting.",
5471 num_resumes);
5472
5473 diagnostic_manager.Printf(lldb::eSeverityError,
5474 "didn't get any event after resume %" PRIu32
5475 ", exiting.",
5476 num_resumes);
5477 return_value = eExpressionSetupError;
5478 break;
5479 }
5480
5481 stop_state =
5483
5484 if (stop_state != eStateRunning) {
5485 bool restarted = false;
5486
5487 if (stop_state == eStateStopped) {
5489 event_sp.get());
5490 LLDB_LOGF(
5491 log,
5492 "Process::RunThreadPlan(): didn't get running event after "
5493 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5494 "handle_running_event: %i).",
5495 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5496 handle_running_event);
5497 }
5498
5499 if (restarted) {
5500 // This is probably an overabundance of caution, I don't think I
5501 // should ever get a stopped & restarted event here. But if I do,
5502 // the best thing is to Halt and then get out of here.
5503 const bool clear_thread_plans = false;
5504 const bool use_run_lock = false;
5505 Halt(clear_thread_plans, use_run_lock);
5506 }
5507
5508 diagnostic_manager.Printf(lldb::eSeverityError,
5509 "didn't get running event after initial "
5510 "resume, got %s instead.",
5511 StateAsCString(stop_state));
5512 return_value = eExpressionSetupError;
5513 break;
5514 }
5515
5516 if (log)
5517 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5518 // We need to call the function synchronously, so spin waiting for it
5519 // to return. If we get interrupted while executing, we're going to
5520 // lose our context, and won't be able to gather the result at this
5521 // point. We set the timeout AFTER the resume, since the resume takes
5522 // some time and we don't want to charge that to the timeout.
5523 } else {
5524 if (log)
5525 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5526 }
5527
5528 do_resume = true;
5529 handle_running_event = true;
5530
5531 // Now wait for the process to stop again:
5532 event_sp.reset();
5533
5534 Timeout<std::micro> timeout =
5535 GetExpressionTimeout(options, before_first_timeout);
5536 if (log) {
5537 if (timeout) {
5538 auto now = system_clock::now();
5539 LLDB_LOGF(log,
5540 "Process::RunThreadPlan(): about to wait - now is %s - "
5541 "endpoint is %s",
5542 llvm::to_string(now).c_str(),
5543 llvm::to_string(now + *timeout).c_str());
5544 } else {
5545 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
5546 }
5547 }
5548
5549#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5550 // See comment above...
5551 if (miss_first_event) {
5552 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5553 miss_first_event = false;
5554 got_event = false;
5555 } else
5556#endif
5557 got_event = listener_sp->GetEvent(event_sp, timeout);
5558
5559 if (got_event) {
5560 if (event_sp) {
5561 bool keep_going = false;
5562 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5563 const bool clear_thread_plans = false;
5564 const bool use_run_lock = false;
5565 Halt(clear_thread_plans, use_run_lock);
5566 return_value = eExpressionInterrupted;
5567 diagnostic_manager.PutString(lldb::eSeverityInfo,
5568 "execution halted by user interrupt.");
5569 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5570 "eBroadcastBitInterrupted, exiting.");
5571 break;
5572 } else {
5573 stop_state =
5575 LLDB_LOGF(log,
5576 "Process::RunThreadPlan(): in while loop, got event: %s.",
5577 StateAsCString(stop_state));
5578
5579 switch (stop_state) {
5580 case lldb::eStateStopped: {
5582 event_sp.get())) {
5583 // If we were restarted, we just need to go back up to fetch
5584 // another event.
5585 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5586 "restart, so we'll continue waiting.");
5587 keep_going = true;
5588 do_resume = false;
5589 handle_running_event = true;
5590 } else {
5591 // Check for fork/vfork/vforkdone stop reasons. DidFork /
5592 // DidVFork / DidVForkDone have already been called by
5593 // PerformAction (via DoOnRemoval).
5594 bool handled_fork = false;
5595 if (ThreadSP fork_thread_sp =
5596 GetThreadList().FindThreadByID(expr_thread_id)) {
5597 if (StopInfoSP stop_info_sp = fork_thread_sp->GetStopInfo()) {
5598 StopReason reason = stop_info_sp->GetStopReason();
5599 if (reason == eStopReasonFork ||
5600 reason == eStopReasonVFork ||
5601 reason == eStopReasonVForkDone) {
5602 handled_fork = true;
5603 if (reason == eStopReasonFork &&
5604 options.GetStopOnFork()) {
5605 // Fork + stop-on-fork: DidFork already ran via
5606 // PerformAction. Parent breakpoints are unaffected.
5607 LLDB_LOGF(log, "Process::RunThreadPlan(): stopped for "
5608 "fork, stop-on-fork is set.");
5609 return_value = eExpressionInterrupted;
5610 } else if (reason == eStopReasonVFork &&
5611 options.GetStopOnFork()) {
5612 // VFork + stop-on-fork: DidVFork already disabled
5613 // software breakpoints (parent and child share
5614 // address space). Interrupting now would leave the
5615 // user with non-functional breakpoints. Defer the
5616 // stop until vforkdone, when DidVForkDone restores
5617 // breakpoint state.
5618 LLDB_LOGF(log,
5619 "Process::RunThreadPlan(): got vfork with "
5620 "stop-on-fork, deferring stop to "
5621 "vforkdone.");
5622 pending_stop_on_vfork_done = true;
5623 keep_going = true;
5624 do_resume = true;
5625 handle_running_event = true;
5626 } else if (reason == eStopReasonVForkDone &&
5627 pending_stop_on_vfork_done) {
5628 // Deferred vfork stop: the vfork cycle has
5629 // completed. DidVForkDone has re-enabled software
5630 // breakpoints and decremented
5631 // m_vfork_in_progress_count.
5632 LLDB_LOGF(log, "Process::RunThreadPlan(): vfork cycle "
5633 "complete, stop-on-fork is set.");
5634 pending_stop_on_vfork_done = false;
5635 return_value = eExpressionInterrupted;
5636 } else {
5637 LLDB_LOGF(log, "Process::RunThreadPlan(): got fork "
5638 "event, continuing.");
5639 keep_going = true;
5640 do_resume = true;
5641 handle_running_event = true;
5642 }
5643 }
5644 }
5645 }
5646
5647 if (!handled_fork) {
5648 const bool handle_interrupts = true;
5649 return_value = *HandleStoppedEvent(
5650 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5651 event_sp, event_to_broadcast_sp, options,
5652 handle_interrupts);
5653 if (return_value == eExpressionThreadVanished)
5654 keep_going = false;
5655 }
5656 }
5657 } break;
5658
5660 // This shouldn't really happen, but sometimes we do get two
5661 // running events without an intervening stop, and in that case
5662 // we should just go back to waiting for the stop.
5663 do_resume = false;
5664 keep_going = true;
5665 handle_running_event = false;
5666 break;
5667
5668 default:
5669 LLDB_LOGF(log,
5670 "Process::RunThreadPlan(): execution stopped with "
5671 "unexpected state: %s.",
5672 StateAsCString(stop_state));
5673
5674 if (stop_state == eStateExited)
5675 event_to_broadcast_sp = event_sp;
5676
5677 diagnostic_manager.PutString(
5679 "execution stopped with unexpected state.");
5680 return_value = eExpressionInterrupted;
5681 break;
5682 }
5683 }
5684
5685 if (keep_going)
5686 continue;
5687 else
5688 break;
5689 } else {
5690 if (log)
5691 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5692 "the event pointer was null. How odd...");
5693 return_value = eExpressionInterrupted;
5694 break;
5695 }
5696 } else {
5697 // If we didn't get an event that means we've timed out... We will
5698 // interrupt the process here. Depending on what we were asked to do
5699 // we will either exit, or try with all threads running for the same
5700 // timeout.
5701
5702 if (log) {
5703 if (options.GetTryAllThreads()) {
5704 if (before_first_timeout) {
5705 LLDB_LOG(log,
5706 "Running function with one thread timeout timed out.");
5707 } else
5708 LLDB_LOG(log, "Restarting function with all threads enabled and "
5709 "timeout: {0} timed out, abandoning execution.",
5710 timeout);
5711 } else
5712 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5713 "abandoning execution.",
5714 timeout);
5715 }
5716
5717 // It is possible that between the time we issued the Halt, and we get
5718 // around to calling Halt the target could have stopped. That's fine,
5719 // Halt will figure that out and send the appropriate Stopped event.
5720 // BUT it is also possible that we stopped & restarted (e.g. hit a
5721 // signal with "stop" set to false.) In
5722 // that case, we'll get the stopped & restarted event, and we should go
5723 // back to waiting for the Halt's stopped event. That's what this
5724 // while loop does.
5725
5726 bool back_to_top = true;
5727 uint32_t try_halt_again = 0;
5728 bool do_halt = true;
5729 const uint32_t num_retries = 5;
5730 while (try_halt_again < num_retries) {
5731 Status halt_error;
5732 if (do_halt) {
5733 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5734 const bool clear_thread_plans = false;
5735 const bool use_run_lock = false;
5736 Halt(clear_thread_plans, use_run_lock);
5737 }
5738 if (halt_error.Success()) {
5739 if (log)
5740 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5741
5742 got_event =
5743 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5744
5745 if (got_event) {
5746 stop_state =
5748 if (log) {
5749 LLDB_LOGF(log,
5750 "Process::RunThreadPlan(): Stopped with event: %s",
5751 StateAsCString(stop_state));
5752 if (stop_state == lldb::eStateStopped &&
5754 event_sp.get()))
5755 log->PutCString(" Event was the Halt interruption event.");
5756 }
5757
5758 if (stop_state == lldb::eStateStopped) {
5760 event_sp.get())) {
5761 if (log)
5762 log->PutCString("Process::RunThreadPlan(): Went to halt "
5763 "but got a restarted event, there must be "
5764 "an un-restarted stopped event so try "
5765 "again... "
5766 "Exiting wait loop.");
5767 try_halt_again++;
5768 do_halt = false;
5769 continue;
5770 }
5771
5772 // Between the time we initiated the Halt and the time we
5773 // delivered it, the process could have already finished its
5774 // job. Check that here:
5775 const bool handle_interrupts = false;
5776 if (auto result = HandleStoppedEvent(
5777 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5778 event_sp, event_to_broadcast_sp, options,
5779 handle_interrupts)) {
5780 return_value = *result;
5781 back_to_top = false;
5782 break;
5783 }
5784
5785 if (!options.GetTryAllThreads()) {
5786 if (log)
5787 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5788 "was false, we stopped so now we're "
5789 "quitting.");
5790 return_value = eExpressionInterrupted;
5791 back_to_top = false;
5792 break;
5793 }
5794
5795 if (before_first_timeout) {
5796 // Set all the other threads to run, and return to the top of
5797 // the loop, which will continue;
5798 before_first_timeout = false;
5799 thread_plan_sp->SetStopOthers(false);
5800 if (log)
5801 log->PutCString(
5802 "Process::RunThreadPlan(): about to resume.");
5803
5804 back_to_top = true;
5805 break;
5806 } else {
5807 // Running all threads failed, so return Interrupted.
5808 if (log)
5809 log->PutCString("Process::RunThreadPlan(): running all "
5810 "threads timed out.");
5811 return_value = eExpressionInterrupted;
5812 back_to_top = false;
5813 break;
5814 }
5815 }
5816 } else {
5817 if (log)
5818 log->PutCString("Process::RunThreadPlan(): halt said it "
5819 "succeeded, but I got no event. "
5820 "I'm getting out of here passing Interrupted.");
5821 return_value = eExpressionInterrupted;
5822 back_to_top = false;
5823 break;
5824 }
5825 } else {
5826 try_halt_again++;
5827 continue;
5828 }
5829 }
5830
5831 if (!back_to_top || try_halt_again > num_retries)
5832 break;
5833 else
5834 continue;
5835 }
5836 } // END WAIT LOOP
5837
5838 policy_guard.reset();
5839
5840 // If we had to start up a temporary private state thread to run this
5841 // thread plan, shut it down now.
5842 if (backup_private_state_thread &&
5843 backup_private_state_thread->IsJoinable()) {
5845 Status error;
5846 m_current_private_state_thread_sp = backup_private_state_thread;
5847 if (stopper_base_plan_sp) {
5848 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5849 }
5850 if (old_state != eStateInvalid)
5851 m_current_private_state_thread_sp->SetPublicStateNoLock(old_state);
5852 }
5853
5854 // If our thread went away on us, we need to get out of here without
5855 // doing any more work. We don't have to clean up the thread plan, that
5856 // will have happened when the Thread was destroyed.
5857 if (return_value == eExpressionThreadVanished) {
5858 return return_value;
5859 }
5860
5861 if (return_value != eExpressionCompleted && log) {
5862 // Print a backtrace into the log so we can figure out where we are:
5863 StreamString s;
5864 s.PutCString("Thread state after unsuccessful completion: \n");
5865 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX,
5866 /*show_hidden*/ true);
5867 log->PutString(s.GetString());
5868 }
5869 // Restore the thread state if we are going to discard the plan execution.
5870 // There are three cases where this could happen: 1) The execution
5871 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5872 // was true 3) We got some other error, and discard_on_error was true
5873 bool should_unwind = (return_value == eExpressionInterrupted &&
5874 options.DoesUnwindOnError()) ||
5875 (return_value == eExpressionHitBreakpoint &&
5876 options.DoesIgnoreBreakpoints());
5877
5878 if (return_value == eExpressionCompleted || should_unwind) {
5879 thread_plan_sp->RestoreThreadState();
5880 }
5881
5882 // Now do some processing on the results of the run:
5883 if (return_value == eExpressionInterrupted ||
5884 return_value == eExpressionHitBreakpoint) {
5885 if (log) {
5886 StreamString s;
5887 if (event_sp)
5888 event_sp->Dump(&s);
5889 else {
5890 log->PutCString("Process::RunThreadPlan(): Stop event that "
5891 "interrupted us is NULL.");
5892 }
5893
5894 StreamString ts;
5895
5896 const char *event_explanation = nullptr;
5897
5898 do {
5899 if (!event_sp) {
5900 event_explanation = "<no event>";
5901 break;
5902 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
5903 event_explanation = "<user interrupt>";
5904 break;
5905 } else {
5906 const Process::ProcessEventData *event_data =
5908 event_sp.get());
5909
5910 if (!event_data) {
5911 event_explanation = "<no event data>";
5912 break;
5913 }
5914
5915 Process *process = event_data->GetProcessSP().get();
5916
5917 if (!process) {
5918 event_explanation = "<no process>";
5919 break;
5920 }
5921
5922 ThreadList &thread_list = process->GetThreadList();
5923
5924 uint32_t num_threads = thread_list.GetSize();
5925 uint32_t thread_index;
5926
5927 ts.Printf("<%u threads> ", num_threads);
5928
5929 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
5930 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
5931
5932 if (!thread) {
5933 ts.Printf("<?> ");
5934 continue;
5935 }
5936
5937 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
5938 RegisterContext *register_context =
5939 thread->GetRegisterContext().get();
5940
5941 if (register_context)
5942 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
5943 else
5944 ts.Printf("[ip unknown] ");
5945
5946 // Show the private stop info here, the public stop info will be
5947 // from the last natural stop.
5948 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
5949 if (stop_info_sp) {
5950 const char *stop_desc = stop_info_sp->GetDescription();
5951 if (stop_desc)
5952 ts.PutCString(stop_desc);
5953 }
5954 ts.Printf(">");
5955 }
5956
5957 event_explanation = ts.GetData();
5958 }
5959 } while (false);
5960
5961 if (event_explanation)
5962 LLDB_LOGF(log,
5963 "Process::RunThreadPlan(): execution interrupted: %s %s",
5964 s.GetData(), event_explanation);
5965 else
5966 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
5967 s.GetData());
5968 }
5969
5970 if (should_unwind) {
5971 LLDB_LOGF(log,
5972 "Process::RunThreadPlan: ExecutionInterrupted - "
5973 "discarding thread plans up to %p.",
5974 static_cast<void *>(thread_plan_sp.get()));
5975 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5976 } else {
5977 LLDB_LOGF(log,
5978 "Process::RunThreadPlan: ExecutionInterrupted - for "
5979 "plan: %p not discarding.",
5980 static_cast<void *>(thread_plan_sp.get()));
5981 }
5982 } else if (return_value == eExpressionSetupError) {
5983 if (log)
5984 log->PutCString("Process::RunThreadPlan(): execution set up error.");
5985
5986 if (options.DoesUnwindOnError()) {
5987 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
5988 }
5989 } else {
5990 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
5991 if (log)
5992 log->PutCString("Process::RunThreadPlan(): thread plan is done");
5993 return_value = eExpressionCompleted;
5994 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
5995 if (log)
5996 log->PutCString(
5997 "Process::RunThreadPlan(): thread plan was discarded");
5998 return_value = eExpressionDiscarded;
5999 } else {
6000 if (log)
6001 log->PutCString(
6002 "Process::RunThreadPlan(): thread plan stopped in mid course");
6003 if (options.DoesUnwindOnError() && thread_plan_sp) {
6004 if (log)
6005 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
6006 "'cause unwind_on_error is set.");
6007 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6008 }
6009 }
6010 }
6011
6012 // Thread we ran the function in may have gone away because we ran the
6013 // target Check that it's still there, and if it is put it back in the
6014 // context. Also restore the frame in the context if it is still present.
6015 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6016 if (thread) {
6017 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
6018 }
6019
6020 // Also restore the current process'es selected frame & thread, since this
6021 // function calling may be done behind the user's back.
6022
6023 if (selected_tid != LLDB_INVALID_THREAD_ID) {
6024 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
6025 selected_stack_id.IsValid()) {
6026 // We were able to restore the selected thread, now restore the frame:
6027 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6028 StackFrameSP old_frame_sp =
6029 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
6030 selected_stack_id);
6031 if (old_frame_sp)
6032 GetThreadList().GetSelectedThread()->SetSelectedFrame(
6033 old_frame_sp.get());
6034 }
6035 }
6036 }
6037
6038 // If the process exited during the run of the thread plan, notify everyone.
6039
6040 if (event_to_broadcast_sp) {
6041 if (log)
6042 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6043 BroadcastEvent(event_to_broadcast_sp);
6044 }
6045
6046 return return_value;
6047}
6048
6049void Process::GetStatus(Stream &strm, bool is_verbose) {
6050 const StateType state = GetState();
6051 if (StateIsStoppedState(state, false)) {
6052 if (state == eStateExited) {
6053 int exit_status = GetExitStatus();
6054 const char *exit_description = GetExitDescription();
6055 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
6056 GetID(), exit_status, exit_status,
6057 exit_description ? exit_description : "");
6058 } else {
6059 if (state == eStateConnected)
6060 strm.Printf("Connected to remote target.\n");
6061 else {
6062 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
6063 if (auto core_args = GetCoreFileArgs(); core_args && is_verbose)
6064 core_args->Format(strm);
6065 }
6066 }
6067 } else {
6068 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
6069 }
6070}
6071
6073 bool only_threads_with_stop_reason,
6074 uint32_t start_frame, uint32_t num_frames,
6075 uint32_t num_frames_with_source,
6076 bool stop_format) {
6077 size_t num_thread_infos_dumped = 0;
6078
6079 // You can't hold the thread list lock while calling Thread::GetStatus. That
6080 // very well might run code (e.g. if we need it to get return values or
6081 // arguments.) For that to work the process has to be able to acquire it.
6082 // So instead copy the thread ID's, and look them up one by one:
6083
6084 uint32_t num_threads;
6085 std::vector<lldb::tid_t> thread_id_array;
6086 // Scope for thread list locker;
6087 {
6088 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6089 ThreadList &curr_thread_list = GetThreadList();
6090 num_threads = curr_thread_list.GetSize();
6091 uint32_t idx;
6092 thread_id_array.resize(num_threads);
6093 for (idx = 0; idx < num_threads; ++idx)
6094 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
6095 }
6096
6097 for (uint32_t i = 0; i < num_threads; i++) {
6098 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
6099 if (thread_sp) {
6100 if (only_threads_with_stop_reason) {
6101 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
6102 if (!stop_info_sp || !stop_info_sp->ShouldShow())
6103 continue;
6104 }
6105 thread_sp->GetStatus(strm, start_frame, num_frames,
6106 num_frames_with_source, stop_format,
6107 /*show_hidden*/ num_frames <= 1);
6108 ++num_thread_infos_dumped;
6109 } else {
6110 Log *log = GetLog(LLDBLog::Process);
6111 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
6112 " vanished while running Thread::GetStatus.");
6113 }
6114 }
6115 return num_thread_infos_dumped;
6116}
6117
6119 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6120}
6121
6123 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
6124 region.GetByteSize());
6125}
6126
6128 void *baton) {
6129 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
6130}
6131
6133 bool result = true;
6134 while (!m_pre_resume_actions.empty()) {
6135 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6136 m_pre_resume_actions.pop_back();
6137 bool this_result = action.callback(action.baton);
6138 if (result)
6139 result = this_result;
6140 }
6141 return result;
6142}
6143
6145
6147{
6148 PreResumeCallbackAndBaton element(callback, baton);
6149 auto found_iter = llvm::find(m_pre_resume_actions, element);
6150 if (found_iter != m_pre_resume_actions.end())
6151 {
6152 m_pre_resume_actions.erase(found_iter);
6153 }
6154}
6155
6159
6161 m_thread_list.Flush();
6162 m_extended_thread_list.Flush();
6164 m_queue_list.Clear();
6167}
6168
6170 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6171 return AddressableBits::AddressableBitToMask(num_bits_setting);
6172
6173 return m_code_address_mask;
6174}
6175
6177 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6178 return AddressableBits::AddressableBitToMask(num_bits_setting);
6179
6180 return m_data_address_mask;
6181}
6182
6191
6200
6203 "Setting Process code address mask to {0:x}", code_address_mask);
6204 m_code_address_mask = code_address_mask;
6205}
6206
6209 "Setting Process data address mask to {0:x}", data_address_mask);
6210 m_data_address_mask = data_address_mask;
6211}
6212
6215 "Setting Process highmem code address mask to {0:x}",
6216 code_address_mask);
6217 m_highmem_code_address_mask = code_address_mask;
6218}
6219
6222 "Setting Process highmem data address mask to {0:x}",
6223 data_address_mask);
6224 m_highmem_data_address_mask = data_address_mask;
6225}
6226
6228 if (ABISP abi_sp = GetABI())
6229 addr = abi_sp->FixCodeAddress(addr);
6230 return addr;
6231}
6232
6234 if (ABISP abi_sp = GetABI())
6235 addr = abi_sp->FixDataAddress(addr);
6236 return addr;
6237}
6238
6240 if (ABISP abi_sp = GetABI())
6241 addr = abi_sp->FixAnyAddress(addr);
6242 return addr;
6243}
6244
6246 Log *log = GetLog(LLDBLog::Process);
6247 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
6248
6249 Target &target = GetTarget();
6250 target.CleanupProcess();
6251 target.ClearModules(false);
6252 m_dynamic_checkers_up.reset();
6253 m_abi_sp.reset();
6254 m_system_runtime_up.reset();
6255 m_os_up.reset();
6256 m_dyld_up.reset();
6257 m_jit_loaders_up.reset();
6258 m_image_tokens.clear();
6259 // After an exec, the inferior is a new process and these memory regions are
6260 // no longer allocated.
6261 m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);
6262 {
6263 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
6264 m_language_runtimes.clear();
6265 }
6267 m_thread_list.DiscardThreadPlans();
6268 m_memory_cache.Clear(true);
6270 DoDidExec();
6272 // Flush the process (threads and all stack frames) after running
6273 // CompleteAttach() in case the dynamic loader loaded things in new
6274 // locations.
6275 Flush();
6276
6277 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
6278 // let the target know so it can do any cleanup it needs to.
6279 target.DidExec();
6280}
6281
6283 if (address == nullptr) {
6284 error = Status::FromErrorString("Invalid address argument");
6285 return LLDB_INVALID_ADDRESS;
6286 }
6287
6288 addr_t function_addr = LLDB_INVALID_ADDRESS;
6289
6290 addr_t addr = address->GetLoadAddress(&GetTarget());
6291 std::map<addr_t, addr_t>::const_iterator iter =
6293 if (iter != m_resolved_indirect_addresses.end()) {
6294 function_addr = (*iter).second;
6295 } else {
6296 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
6297 const Symbol *symbol = address->CalculateSymbolContextSymbol();
6299 "Unable to call resolver for indirect function %s",
6300 symbol ? symbol->GetName().AsCString(nullptr) : "<UNKNOWN>");
6301 function_addr = LLDB_INVALID_ADDRESS;
6302 } else {
6303 if (ABISP abi_sp = GetABI())
6304 function_addr = abi_sp->FixCodeAddress(function_addr);
6306 std::pair<addr_t, addr_t>(addr, function_addr));
6307 }
6308 }
6309 return function_addr;
6310}
6311
6313 // Inform the system runtime of the modified modules.
6314 SystemRuntime *sys_runtime = GetSystemRuntime();
6315 if (sys_runtime)
6316 sys_runtime->ModulesDidLoad(module_list);
6317
6318 GetJITLoaders().ModulesDidLoad(module_list);
6319
6320 // Give the instrumentation runtimes a chance to be created before informing
6321 // them of the modified modules.
6324 for (auto &runtime : m_instrumentation_runtimes)
6325 runtime.second->ModulesDidLoad(module_list);
6326
6327 // Give the language runtimes a chance to be created before informing them of
6328 // the modified modules.
6329 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
6330 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
6331 runtime->ModulesDidLoad(module_list);
6332 }
6333
6334 // If we don't have an operating system plug-in, try to load one since
6335 // loading shared libraries might cause a new one to try and load
6336 if (!m_os_up)
6338
6339 // Inform the structured-data plugins of the modified modules.
6340 for (auto &pair : m_structured_data_plugin_map) {
6341 if (pair.second)
6342 pair.second->ModulesDidLoad(*this, module_list);
6343 }
6344}
6345
6348 return;
6349 if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())
6350 return;
6351 sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
6352}
6353
6356 return;
6357 if (!sc.module_sp)
6358 return;
6359 LanguageType language = sc.GetLanguage();
6360 if (language == eLanguageTypeUnknown ||
6361 language == lldb::eLanguageTypeAssembly ||
6363 return;
6364 LanguageSet plugins =
6366 if (plugins[language])
6367 return;
6368 sc.module_sp->ReportWarningUnsupportedLanguage(
6369 language, GetTarget().GetDebugger().GetID());
6370}
6371
6373 info.Clear();
6374
6375 PlatformSP platform_sp = GetTarget().GetPlatform();
6376 if (!platform_sp)
6377 return false;
6378
6379 return platform_sp->GetProcessInfo(GetID(), info);
6380}
6381
6383 return spec.GetUUID().IsValid();
6384}
6385
6387 ThreadCollectionSP threads;
6388
6389 const MemoryHistorySP &memory_history =
6390 MemoryHistory::FindPlugin(shared_from_this());
6391
6392 if (!memory_history) {
6393 return threads;
6394 }
6395
6396 threads = std::make_shared<ThreadCollection>(
6397 memory_history->GetHistoryThreads(addr));
6398
6399 return threads;
6400}
6401
6404 InstrumentationRuntimeCollection::iterator pos;
6405 pos = m_instrumentation_runtimes.find(type);
6406 if (pos == m_instrumentation_runtimes.end()) {
6407 return InstrumentationRuntimeSP();
6408 } else
6409 return (*pos).second;
6410}
6411
6412bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6413 const ArchSpec &arch, ModuleSpec &module_spec) {
6414 module_spec.Clear();
6415 return false;
6416}
6417
6419 m_image_tokens.push_back(image_ptr);
6420 return m_image_tokens.size() - 1;
6421}
6422
6424 if (token < m_image_tokens.size())
6425 return m_image_tokens[token];
6426 return LLDB_INVALID_ADDRESS;
6427}
6428
6429void Process::ResetImageToken(size_t token) {
6430 if (token < m_image_tokens.size())
6432}
6433
6434Address
6436 AddressRange range_bounds) {
6437 Target &target = GetTarget();
6438 DisassemblerSP disassembler_sp;
6439 InstructionList *insn_list = nullptr;
6440
6441 Address retval = default_stop_addr;
6442
6443 if (!target.GetUseFastStepping())
6444 return retval;
6445 if (!default_stop_addr.IsValid())
6446 return retval;
6447
6448 const char *plugin_name = nullptr;
6449 const char *flavor = nullptr;
6450 const char *cpu = nullptr;
6451 const char *features = nullptr;
6452 disassembler_sp = Disassembler::DisassembleRange(
6453 target.GetArchitecture(), plugin_name, flavor, cpu, features, GetTarget(),
6454 range_bounds);
6455 if (disassembler_sp)
6456 insn_list = &disassembler_sp->GetInstructionList();
6457
6458 if (insn_list == nullptr) {
6459 return retval;
6460 }
6461
6462 size_t insn_offset =
6463 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6464 if (insn_offset == UINT32_MAX) {
6465 return retval;
6466 }
6467
6468 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
6469 insn_offset, false /* ignore_calls*/, nullptr);
6470 if (branch_index == UINT32_MAX) {
6471 return retval;
6472 }
6473
6474 if (branch_index > insn_offset) {
6475 Address next_branch_insn_address =
6476 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6477 if (next_branch_insn_address.IsValid() &&
6478 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6479 retval = next_branch_insn_address;
6480 }
6481 }
6482
6483 return retval;
6484}
6485
6487 MemoryRegionInfo &range_info) {
6488 if (const lldb::ABISP &abi = GetABI())
6489 load_addr = abi->FixAnyAddress(load_addr);
6490
6491 std::optional<MemoryRegionInfo> cached_region =
6492 m_memory_region_infos_cache.GetMemoryRegion(load_addr);
6493 if (cached_region) {
6494 range_info = *cached_region;
6495 return Status();
6496 }
6497
6498 Status error = DoGetMemoryRegionInfo(load_addr, range_info);
6499 if (error.Success()) {
6500 // Reject a region that does not contain the requested address.
6501 if (!range_info.GetRange().Contains(load_addr))
6502 error = Status::FromErrorString("Invalid memory region");
6503 else
6504 m_memory_region_infos_cache.AddRegion(range_info);
6505 }
6506
6507 return error;
6508}
6509
6511 Status error;
6512
6513 lldb::addr_t range_end = 0;
6514 const lldb::ABISP &abi = GetABI();
6515
6516 region_list.clear();
6517 do {
6519 error = GetMemoryRegionInfo(range_end, region_info);
6520 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6521 if (error.Fail()) {
6522 region_list.clear();
6523 break;
6524 }
6525
6526 // We only check the end address, not start and end, because we assume that
6527 // the start will not have non-address bits until the first unmappable
6528 // region. We will have exited the loop by that point because the previous
6529 // region, the last mappable region, will have non-address bits in its end
6530 // address.
6531 range_end = region_info.GetRange().GetRangeEnd();
6532 if (region_info.GetMapped() == eLazyBoolYes) {
6533 region_list.push_back(std::move(region_info));
6534 }
6535 } while (
6536 // For a process with no non-address bits, all address bits
6537 // set means the end of memory.
6538 range_end != LLDB_INVALID_ADDRESS &&
6539 // If we have non-address bits and some are set then the end
6540 // is at or beyond the end of mappable memory.
6541 !(abi && (abi->FixAnyAddress(range_end) != range_end)));
6542
6543 return error;
6544}
6545
6546Status
6547Process::ConfigureStructuredData(llvm::StringRef type_name,
6548 const StructuredData::ObjectSP &config_sp) {
6549 // If you get this, the Process-derived class needs to implement a method to
6550 // enable an already-reported asynchronous structured data feature. See
6551 // ProcessGDBRemote for an example implementation over gdb-remote.
6552 return Status::FromErrorString("unimplemented");
6553}
6554
6556 const StructuredData::Array &supported_type_names) {
6557 Log *log = GetLog(LLDBLog::Process);
6558
6559 // Bail out early if there are no type names to map.
6560 if (supported_type_names.GetSize() == 0) {
6561 LLDB_LOG(log, "no structured data types supported");
6562 return;
6563 }
6564
6565 // These StringRefs are backed by the input parameter.
6566 std::set<llvm::StringRef> type_names;
6567
6568 LLDB_LOG(log,
6569 "the process supports the following async structured data types:");
6570
6571 supported_type_names.ForEach(
6572 [&type_names, &log](StructuredData::Object *object) {
6573 // There shouldn't be null objects in the array.
6574 if (!object)
6575 return false;
6576
6577 // All type names should be strings.
6578 const llvm::StringRef type_name = object->GetStringValue();
6579 if (type_name.empty())
6580 return false;
6581
6582 type_names.insert(type_name);
6583 LLDB_LOG(log, "- {0}", type_name);
6584 return true;
6585 });
6586
6587 // For each StructuredDataPlugin, if the plugin handles any of the types in
6588 // the supported_type_names, map that type name to that plugin. Stop when
6589 // we've consumed all the type names.
6590 // FIXME: should we return an error if there are type names nobody
6591 // supports?
6593 if (type_names.empty())
6594 break;
6595
6596 // Create the plugin.
6597 StructuredDataPluginSP plugin_sp = (*cbs.create_callback)(*this);
6598 if (!plugin_sp) {
6599 // This plugin doesn't think it can work with the process. Move on to the
6600 // next.
6601 continue;
6602 }
6603
6604 // For any of the remaining type names, map any that this plugin supports.
6605 std::vector<llvm::StringRef> names_to_remove;
6606 for (llvm::StringRef type_name : type_names) {
6607 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6609 std::make_pair(type_name, plugin_sp));
6610 names_to_remove.push_back(type_name);
6611 LLDB_LOG(log, "using plugin {0} for type name {1}",
6612 plugin_sp->GetPluginName(), type_name);
6613 }
6614 }
6615
6616 // Remove the type names that were consumed by this plugin.
6617 for (llvm::StringRef type_name : names_to_remove)
6618 type_names.erase(type_name);
6619 }
6620}
6621
6623 const StructuredData::ObjectSP object_sp) {
6624 // Nothing to do if there's no data.
6625 if (!object_sp)
6626 return false;
6627
6628 // The contract is this must be a dictionary, so we can look up the routing
6629 // key via the top-level 'type' string value within the dictionary.
6630 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6631 if (!dictionary)
6632 return false;
6633
6634 // Grab the async structured type name (i.e. the feature/plugin name).
6635 llvm::StringRef type_name;
6636 if (!dictionary->GetValueForKeyAsString("type", type_name))
6637 return false;
6638
6639 // Check if there's a plugin registered for this type name.
6640 auto find_it = m_structured_data_plugin_map.find(type_name);
6641 if (find_it == m_structured_data_plugin_map.end()) {
6642 // We don't have a mapping for this structured data type.
6643 return false;
6644 }
6645
6646 // Route the structured data to the plugin.
6647 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6648 return true;
6649}
6650
6652 // Default implementation does nothign.
6653 // No automatic signal filtering to speak of.
6654 return Status();
6655}
6656
6658 Platform *platform,
6659 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
6660 if (platform != GetTarget().GetPlatform().get())
6661 return nullptr;
6662 llvm::call_once(m_dlopen_utility_func_flag_once,
6663 [&] { m_dlopen_utility_func_up = factory(); });
6664 return m_dlopen_utility_func_up.get();
6665}
6666
6667llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6668 if (!IsLiveDebugSession())
6669 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6670 "Can't trace a non-live process.");
6671 return llvm::make_error<UnimplementedError>();
6672}
6673
6675 addr_t &returned_func,
6676 bool trap_exceptions) {
6678 if (thread == nullptr || address == nullptr)
6679 return false;
6680
6682 options.SetStopOthers(true);
6683 options.SetUnwindOnError(true);
6684 options.SetIgnoreBreakpoints(true);
6685 options.SetTryAllThreads(true);
6686 options.SetDebug(false);
6688 options.SetTrapExceptions(trap_exceptions);
6689
6690 auto type_system_or_err =
6692 if (!type_system_or_err) {
6693 llvm::consumeError(type_system_or_err.takeError());
6694 return false;
6695 }
6696 auto ts = *type_system_or_err;
6697 if (!ts)
6698 return false;
6699 CompilerType void_ptr_type =
6702 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6703 if (call_plan_sp) {
6704 DiagnosticManager diagnostics;
6705
6706 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6707 if (frame) {
6708 ExecutionContext exe_ctx;
6709 frame->CalculateExecutionContext(exe_ctx);
6710 ExpressionResults result =
6711 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6712 if (result == eExpressionCompleted) {
6713 returned_func =
6714 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6716
6717 if (GetAddressByteSize() == 4) {
6718 if (returned_func == UINT32_MAX)
6719 return false;
6720 } else if (GetAddressByteSize() == 8) {
6721 if (returned_func == UINT64_MAX)
6722 return false;
6723 }
6724 return true;
6725 }
6726 }
6727 }
6728
6729 return false;
6730}
6731
6732llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6734 const MemoryTagManager *tag_manager =
6735 arch ? arch->GetMemoryTagManager() : nullptr;
6736 if (!arch || !tag_manager) {
6737 return llvm::createStringError(
6738 llvm::inconvertibleErrorCode(),
6739 "This architecture does not support memory tagging");
6740 }
6741
6742 if (!SupportsMemoryTagging()) {
6743 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6744 "Process does not support memory tagging");
6745 }
6746
6747 return tag_manager;
6748}
6749
6750llvm::Expected<std::vector<lldb::addr_t>>
6752 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6754 if (!tag_manager_or_err)
6755 return tag_manager_or_err.takeError();
6756
6757 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6758 llvm::Expected<std::vector<uint8_t>> tag_data =
6759 DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6760 if (!tag_data)
6761 return tag_data.takeError();
6762
6763 return tag_manager->UnpackTagsData(*tag_data,
6764 len / tag_manager->GetGranuleSize());
6765}
6766
6768 const std::vector<lldb::addr_t> &tags) {
6769 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6771 if (!tag_manager_or_err)
6772 return Status::FromError(tag_manager_or_err.takeError());
6773
6774 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6775 llvm::Expected<std::vector<uint8_t>> packed_tags =
6776 tag_manager->PackTags(tags);
6777 if (!packed_tags) {
6778 return Status::FromError(packed_tags.takeError());
6779 }
6780
6781 return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6782 *packed_tags);
6783}
6784
6785// Create a CoreFileMemoryRange from a MemoryRegionInfo
6788 const addr_t addr = region.GetRange().GetRangeBase();
6789 llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());
6790 return {range, region.GetLLDBPermissions()};
6791}
6792
6793// Add dirty pages to the core file ranges and return true if dirty pages
6794// were added. Return false if the dirty page information is not valid or in
6795// the region.
6797 CoreFileMemoryRanges &ranges) {
6798 const auto &dirty_page_list = region.GetDirtyPageList();
6799 if (!dirty_page_list)
6800 return false;
6801 const uint32_t lldb_permissions = region.GetLLDBPermissions();
6802 const addr_t page_size = region.GetPageSize();
6803 if (page_size == 0)
6804 return false;
6805 llvm::AddressRange range(0, 0);
6806 for (addr_t page_addr : *dirty_page_list) {
6807 if (range.empty()) {
6808 // No range yet, initialize the range with the current dirty page.
6809 range = llvm::AddressRange(page_addr, page_addr + page_size);
6810 } else {
6811 if (range.end() == page_addr) {
6812 // Combine consective ranges.
6813 range = llvm::AddressRange(range.start(), page_addr + page_size);
6814 } else {
6815 // Add previous contiguous range and init the new range with the
6816 // current dirty page.
6817 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6818 range = llvm::AddressRange(page_addr, page_addr + page_size);
6819 }
6820 }
6821 }
6822 // The last range
6823 if (!range.empty())
6824 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6825 return true;
6826}
6827
6828// Given a region, add the region to \a ranges.
6829//
6830// Only add the region if it isn't empty and if it has some permissions.
6831// If \a try_dirty_pages is true, then try to add only the dirty pages for a
6832// given region. If the region has dirty page information, only dirty pages
6833// will be added to \a ranges, else the entire range will be added to \a
6834// ranges.
6836 bool try_dirty_pages, CoreFileMemoryRanges &ranges) {
6837 // Don't add empty ranges.
6838 if (region.GetRange().GetByteSize() == 0)
6839 return;
6840 // Don't add ranges with no read permissions.
6841 if ((region.GetLLDBPermissions() & lldb::ePermissionsReadable) == 0)
6842 return;
6843 if (try_dirty_pages && AddDirtyPages(region, ranges))
6844 return;
6845
6846 ranges.Append(region.GetRange().GetRangeBase(),
6847 region.GetRange().GetByteSize(),
6849}
6850
6852 const SaveCoreOptions &options,
6853 CoreFileMemoryRanges &ranges,
6854 std::set<addr_t> &stack_ends) {
6855 DynamicLoader *dyld = process.GetDynamicLoader();
6856 if (!dyld)
6857 return;
6858
6859 std::vector<lldb_private::MemoryRegionInfo> dynamic_loader_mem_regions;
6860 std::function<bool(const lldb_private::Thread &)> save_thread_predicate =
6861 [&](const lldb_private::Thread &t) -> bool {
6862 return options.ShouldThreadBeSaved(t.GetID());
6863 };
6864 dyld->CalculateDynamicSaveCoreRanges(process, dynamic_loader_mem_regions,
6865 save_thread_predicate);
6866 for (const auto &region : dynamic_loader_mem_regions) {
6867 // The Dynamic Loader can give us regions that could include a truncated
6868 // stack
6869 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
6870 AddRegion(region, true, ranges);
6871 }
6872}
6873
6875 const SaveCoreOptions &core_options,
6876 const MemoryRegionInfos &regions,
6877 CoreFileMemoryRanges &ranges,
6878 std::set<addr_t> &stack_ends) {
6879 const bool try_dirty_pages = true;
6880
6881 // Before we take any dump, we want to save off the used portions of the
6882 // stacks and mark those memory regions as saved. This prevents us from saving
6883 // the unused portion of the stack below the stack pointer. Saving space on
6884 // the dump.
6885 for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {
6886 if (!thread_sp)
6887 continue;
6888 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
6889 if (!frame_sp)
6890 continue;
6891 RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();
6892 if (!reg_ctx_sp)
6893 continue;
6894 const addr_t sp = reg_ctx_sp->GetSP();
6895 const size_t red_zone = process.GetABI()->GetRedZoneSize();
6897 if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {
6898 const size_t stack_head = (sp - red_zone);
6899 const size_t stack_size = sp_region.GetRange().GetRangeEnd() - stack_head;
6900 // Even if the SaveCoreOption doesn't want us to save the stack
6901 // we still need to populate the stack_ends set so it doesn't get saved
6902 // off in other calls
6903 sp_region.GetRange().SetRangeBase(stack_head);
6904 sp_region.GetRange().SetByteSize(stack_size);
6905 const addr_t range_end = sp_region.GetRange().GetRangeEnd();
6906 stack_ends.insert(range_end);
6907 // This will return true if the threadlist the user specified is empty,
6908 // or contains the thread id from thread_sp.
6909 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
6910 AddRegion(sp_region, try_dirty_pages, ranges);
6911 }
6912 }
6913 }
6914}
6915
6916// Save all memory regions that are not empty or have at least some permissions
6917// for a full core file style.
6919 const MemoryRegionInfos &regions,
6920 CoreFileMemoryRanges &ranges,
6921 std::set<addr_t> &stack_ends) {
6922
6923 // Don't add only dirty pages, add full regions.
6924 const bool try_dirty_pages = false;
6925 for (const auto &region : regions)
6926 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
6927 AddRegion(region, try_dirty_pages, ranges);
6928}
6929
6930// Save only the dirty pages to the core file. Make sure the process has at
6931// least some dirty pages, as some OS versions don't support reporting what
6932// pages are dirty within an memory region. If no memory regions have dirty
6933// page information fall back to saving out all ranges with write permissions.
6935 const MemoryRegionInfos &regions,
6936 CoreFileMemoryRanges &ranges,
6937 std::set<addr_t> &stack_ends) {
6938
6939 // Iterate over the regions and find all dirty pages.
6940 bool have_dirty_page_info = false;
6941 for (const auto &region : regions) {
6942 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
6943 AddDirtyPages(region, ranges))
6944 have_dirty_page_info = true;
6945 }
6946
6947 if (!have_dirty_page_info) {
6948 // We didn't find support for reporting dirty pages from the process
6949 // plug-in so fall back to any region with write access permissions.
6950 const bool try_dirty_pages = false;
6951 for (const auto &region : regions)
6952 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
6953 region.GetWritable() == eLazyBoolYes)
6954 AddRegion(region, try_dirty_pages, ranges);
6955 }
6956}
6957
6958// Save all thread stacks to the core file. Some OS versions support reporting
6959// when a memory region is stack related. We check on this information, but we
6960// also use the stack pointers of each thread and add those in case the OS
6961// doesn't support reporting stack memory. This function also attempts to only
6962// emit dirty pages from the stack if the memory regions support reporting
6963// dirty regions as this will make the core file smaller. If the process
6964// doesn't support dirty regions, then it will fall back to adding the full
6965// stack region.
6967 const MemoryRegionInfos &regions,
6968 CoreFileMemoryRanges &ranges,
6969 std::set<addr_t> &stack_ends) {
6970 const bool try_dirty_pages = true;
6971 // Some platforms support annotating the region information that tell us that
6972 // it comes from a thread stack. So look for those regions first.
6973
6974 for (const auto &region : regions) {
6975 // Save all the stack memory ranges not associated with a stack pointer.
6976 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
6977 region.IsStackMemory() == eLazyBoolYes)
6978 AddRegion(region, try_dirty_pages, ranges);
6979 }
6980}
6981
6982// TODO: We should refactor CoreFileMemoryRanges to use the lldb range type, and
6983// then add an intersect method on it, or MemoryRegionInfo.
6984static lldb_private::MemoryRegionInfo
6987
6989 region_info.SetLLDBPermissions(lhs.GetLLDBPermissions());
6990 region_info.GetRange() = lhs.GetRange().Intersect(rhs);
6991
6992 return region_info;
6993}
6994
6996 const MemoryRegionInfos &regions,
6997 const SaveCoreOptions &options,
6998 CoreFileMemoryRanges &ranges) {
6999 const auto &option_ranges = options.GetCoreFileMemoryRanges();
7000 if (option_ranges.IsEmpty())
7001 return;
7002
7003 for (const auto &range : regions) {
7004 auto *entry = option_ranges.FindEntryThatIntersects(range.GetRange());
7005 if (entry) {
7006 if (*entry != range.GetRange()) {
7007 AddRegion(Intersect(range, *entry), true, ranges);
7008 } else {
7009 // If they match, add the range directly.
7010 AddRegion(range, true, ranges);
7011 }
7012 }
7013 }
7014}
7015
7017 CoreFileMemoryRanges &ranges) {
7019 Status err = GetMemoryRegions(regions);
7020 SaveCoreStyle core_style = options.GetStyle();
7021 if (err.Fail())
7022 return err;
7023 if (regions.empty())
7025 "failed to get any valid memory regions from the process");
7026 if (core_style == eSaveCoreUnspecified)
7028 "callers must set the core_style to something other than "
7029 "eSaveCoreUnspecified");
7030
7031 GetUserSpecifiedCoreFileSaveRanges(*this, regions, options, ranges);
7032
7033 std::set<addr_t> stack_ends;
7034 // For fully custom set ups, we don't want to even look at threads if there
7035 // are no threads specified.
7036 if (core_style != lldb::eSaveCoreCustomOnly ||
7037 options.HasSpecifiedThreads()) {
7038 SaveOffRegionsWithStackPointers(*this, options, regions, ranges,
7039 stack_ends);
7040 // Save off the dynamic loader sections, so if we are on an architecture
7041 // that supports Thread Locals, that we include those as well.
7042 SaveDynamicLoaderSections(*this, options, ranges, stack_ends);
7043 }
7044
7045 switch (core_style) {
7048 break;
7049
7050 case eSaveCoreFull:
7051 GetCoreFileSaveRangesFull(*this, regions, ranges, stack_ends);
7052 break;
7053
7054 case eSaveCoreDirtyOnly:
7055 GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges, stack_ends);
7056 break;
7057
7058 case eSaveCoreStackOnly:
7059 GetCoreFileSaveRangesStackOnly(*this, regions, ranges, stack_ends);
7060 break;
7061 }
7062
7063 if (err.Fail())
7064 return err;
7065
7066 if (ranges.IsEmpty())
7068 "no valid address ranges found for core style");
7069
7070 return ranges.FinalizeCoreFileSaveRanges();
7071}
7072
7073std::vector<ThreadSP>
7075 std::vector<ThreadSP> thread_list;
7076 for (const lldb::ThreadSP &thread_sp : m_thread_list.Threads()) {
7077 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
7078 thread_list.push_back(thread_sp);
7079 }
7080 }
7081
7082 return thread_list;
7083}
7084
7086 uint32_t low_memory_addr_bits = bit_masks.GetLowmemAddressableBits();
7087 uint32_t high_memory_addr_bits = bit_masks.GetHighmemAddressableBits();
7088
7089 if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)
7090 return;
7091
7092 if (low_memory_addr_bits != 0) {
7093 addr_t low_addr_mask =
7094 AddressableBits::AddressableBitToMask(low_memory_addr_bits);
7095 SetCodeAddressMask(low_addr_mask);
7096 SetDataAddressMask(low_addr_mask);
7097 }
7098
7099 if (high_memory_addr_bits != 0) {
7100 addr_t high_addr_mask =
7101 AddressableBits::AddressableBitToMask(high_memory_addr_bits);
7102 SetHighmemCodeAddressMask(high_addr_mask);
7103 SetHighmemDataAddressMask(high_addr_mask);
7104 }
7105}
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:376
#define LLDB_LOGF(log,...)
Definition Log.h:390
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:406
static void GetCoreFileSaveRangesFull(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6918
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:5115
static void SaveDynamicLoaderSections(Process &process, const SaveCoreOptions &options, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6851
static CoreFileMemoryRange CreateCoreFileMemoryRange(const lldb_private::MemoryRegionInfo &region)
Definition Process.cpp:6787
static constexpr unsigned g_string_read_width
Definition Process.cpp:135
static bool AddDirtyPages(const lldb_private::MemoryRegionInfo &region, CoreFileMemoryRanges &ranges)
Definition Process.cpp:6796
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:6995
static void GetCoreFileSaveRangesDirtyOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6934
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:6835
static Timeout< std::micro > GetExpressionTimeout(const EvaluateExpressionOptions &options, bool before_first_timeout)
Definition Process.cpp:5098
static microseconds GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options)
Definition Process.cpp:5078
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:6985
static void SaveOffRegionsWithStackPointers(Process &process, const SaveCoreOptions &core_options, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6874
static void GetCoreFileSaveRangesStackOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6966
@ 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:396
void SetTryAllThreads(bool try_others=true)
Definition Target.h:429
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:417
void SetStopOthers(bool stop_others=true)
Definition Target.h:433
const Timeout< std::micro > & GetTimeout() const
Definition Target.h:415
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:400
const Timeout< std::micro > & GetOneThreadTimeout() const
Definition Target.h:419
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:57
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:249
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
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:504
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(const char *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 object file parsers.
Definition ObjectFile.h:46
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:110
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:132
static PolicyStack & Get()
Definition Policy.cpp:21
Policy Current() const
Definition Policy.cpp:26
uint32_t GetResumeCount() const
Definition Process.h:158
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3213
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:124
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:3205
EventActionResult PerformAction(lldb::EventSP &event_sp) override
Definition Process.cpp:3148
AttachCompletionHandler(Process *process, uint32_t exec_count)
Definition Process.cpp:3137
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4767
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
Definition Process.cpp:4535
static void AddRestartedReason(Event *event_ptr, const char *reason)
Definition Process.cpp:4804
void SetInterrupted(bool new_value)
Definition Process.h:493
lldb::ProcessSP GetProcessSP() const
Definition Process.h:441
void SetRestarted(bool new_value)
Definition Process.h:491
static void SetRestartedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4775
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4751
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4821
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:4639
llvm::StringRef GetFlavor() const override
Definition Process.cpp:4531
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition Process.cpp:4812
const char * GetRestartedReasonAtIndex(size_t idx)
Definition Process.h:448
static bool SetUpdateStateOnRemoval(Event *event_ptr)
Definition Process.cpp:4829
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4759
lldb::StateType GetState() const
Definition Process.h:443
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Process.cpp:4740
static llvm::StringRef GetFlavorString()
Definition Process.cpp:4527
void DoOnRemoval(Event *event_ptr) override
Definition Process.cpp:4653
void Dump(Stream *s) const override
Definition Process.cpp:4727
A plug-in interface definition class for debugging a process.
Definition Process.h:359
virtual Status EnableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2296
Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.cpp:3228
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
Definition Process.cpp:6667
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3547
friend class ProcessProperties
Definition Process.h:2513
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:6657
virtual Status DoSignal(int signal)
Sends a process a UNIX signal signal.
Definition Process.h:1205
virtual Status WillResume()
Called before resuming to a process.
Definition Process.h:1092
std::mutex m_process_input_reader_mutex
Definition Process.h:3548
lldb::addr_t m_code_address_mask
Mask for code an data addresses.
Definition Process.h:3598
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1571
std::vector< lldb::addr_t > m_image_tokens
Definition Process.h:3530
virtual Status DoHalt(bool &caused_stop)
Halts a running process.
Definition Process.h:1152
virtual void DidLaunch()
Called after launching a process.
Definition Process.h:1084
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:543
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:1199
void ResetImageToken(size_t token)
Definition Process.cpp:6429
lldb::JITLoaderListUP m_jit_loaders_up
Definition Process.h:3536
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:2716
void SetNextEventAction(Process::NextEventAction *next_event_action)
Definition Process.h:3159
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:3821
virtual Status WillDetach()
Called before detaching from a process.
Definition Process.h:1169
virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.h:1076
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:3532
void ControlPrivateStateThread(uint32_t signal)
Definition Process.cpp:4193
ThreadList & GetThreadList()
Definition Process.h:2394
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7085
virtual DataExtractor GetAuxvData()
Definition Process.cpp:3117
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:5172
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:6354
Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state, lldb::EventSP &event_sp)
Definition Process.cpp:2916
std::vector< std::string > m_profile_data
Definition Process.h:3556
bool m_can_interpret_function_calls
Definition Process.h:3611
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:3559
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3916
virtual void DidExit()
Definition Process.h:1453
std::string m_stdout_data
Remember if stdin must be forwarded to remote debug server.
Definition Process.h:3553
bool RemoveInvalidMemoryRange(const LoadRange &region)
Definition Process.cpp:6122
DelayedBreakpointCache m_delayed_breakpoints
Definition Process.h:3639
uint32_t GetNextThreadIndexID(uint64_t thread_id)
Definition Process.cpp:1264
Status PrivateResume()
The "private" side of resuming a process.
Definition Process.cpp:3541
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition Process.cpp:1567
void SendAsyncInterrupt(Thread *thread=nullptr)
Send an async interrupt request.
Definition Process.cpp:4241
void AddInvalidMemoryRegion(const LoadRange &region)
Definition Process.cpp:6118
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6312
InstrumentationRuntimeCollection m_instrumentation_runtimes
Definition Process.h:3565
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:3586
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:3491
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:3084
@ eBroadcastInternalStateControlResume
Definition Process.h:389
@ eBroadcastInternalStateControlStop
Definition Process.h:387
@ eBroadcastInternalStateControlPause
Definition Process.h:388
int GetExitStatus()
Get the exit status for a process.
Definition Process.cpp:1032
OperatingSystem * GetOperatingSystem()
Definition Process.h:2539
Status WillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition Process.cpp:3224
virtual Status DoDetach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.h:1176
std::unique_ptr< UtilityFunction > m_dlopen_utility_func_up
Definition Process.h:3619
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:3495
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
Definition Process.cpp:2506
Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr, AddressRange range_bounds)
Find the next branch instruction to set a breakpoint on.
Definition Process.cpp:6435
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:2818
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:3439
virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error)
Get any available profile data.
Definition Process.cpp:4910
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6233
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2701
std::unique_ptr< NextEventAction > m_next_event_action_up
Definition Process.h:3566
void SetHighmemDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6220
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:1186
std::function< IterationAction(lldb_private::Status &error, lldb::addr_t bytes_addr, const void *bytes, lldb::offset_t bytes_size)> ReadMemoryChunkCallback
Definition Process.h:1694
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:2096
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:1501
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2383
size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error)
Definition Process.cpp:2658
virtual Status Launch(ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.cpp:2877
std::mutex m_run_thread_plan_lock
Definition Process.h:3614
static void SettingsInitialize()
Definition Process.cpp:5035
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:4894
void Flush()
Flush all data in the process.
Definition Process.cpp:6160
bool m_clear_thread_plans_on_stop
Definition Process.h:3604
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:2337
void ResumePrivateStateThread()
Definition Process.cpp:4175
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:6555
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:3546
virtual void DidSignal()
Called after sending a signal to a process.
Definition Process.h:1223
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2314
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3131
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3500
lldb::StateType GetPrivateState() const
Definition Process.h:3457
void SetPrivateStateNoLock(lldb::StateType new_state)
Definition Process.h:3469
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:3484
uint32_t m_extended_thread_stop_id
The natural stop id when extended_thread_list was last updated.
Definition Process.h:3520
bool PreResumeActionCallback(void *)
Definition Process.h:2719
lldb::RunDirection m_base_direction
ThreadPlanBase run direction.
Definition Process.h:3519
Range< lldb::addr_t, lldb::addr_t > LoadRange
Definition Process.h:392
static constexpr llvm::StringRef ResumeSynchronousHijackListenerName
Definition Process.h:409
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3729
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2531
QueueList m_queue_list
The list of libdispatch queues at a given stop point.
Definition Process.h:3523
void ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6146
virtual Status WillDestroy()
Definition Process.h:1211
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:3567
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2755
lldb::StateType GetStateChangedEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:997
void LoadOperatingSystemPlugin(bool flush)
Definition Process.cpp:2868
lldb::StructuredDataPluginSP GetStructuredDataPlugin(llvm::StringRef type_name) const
Returns the StructuredDataPlugin associated with a given type name, if there is one.
Definition Process.cpp:4902
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3535
friend class ProcessEventData
Definition Process.h:363
void ResetExtendedCrashInfoDict()
Definition Process.h:2799
AddressRanges FindRangesInMemory(const uint8_t *buf, uint64_t size, const AddressRanges &ranges, size_t alignment, size_t max_matches, Status &error)
Definition Process.cpp:2169
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:6412
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:1813
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2690
std::recursive_mutex m_stdio_communication_mutex
Definition Process.h:3550
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:3527
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:6732
~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:3287
std::recursive_mutex m_profile_data_comm_mutex
Definition Process.h:3555
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1676
lldb::InstrumentationRuntimeSP GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
Definition Process.cpp:6403
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:6239
virtual Status DoWillLaunch(Module *module)
Called before launching to a process.
Definition Process.h:1057
virtual Status ConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.cpp:3490
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4873
llvm::StringMap< lldb::StructuredDataPluginSP > m_structured_data_plugin_map
Definition Process.h:3615
virtual Status DisableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2301
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:6072
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Process.cpp:4841
virtual size_t ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2038
Event * PeekAtStateChangedEvents()
Definition Process.cpp:980
std::vector< Notifications > m_notifications
The list of notifications that this process can deliver.
Definition Process.h:3528
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:2468
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6418
llvm::Error FlushDelayedBreakpoints()
Definition Process.cpp:1738
lldb::StateType GetPrivateStateNoLock() const
Definition Process.h:3463
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:2138
virtual bool DestroyRequiresHalt()
Definition Process.h:1217
lldb::EventSP CreateEventFromProcessState(uint32_t event_type)
Definition Process.cpp:4867
StructuredData::DictionarySP m_crash_info_dict_sp
A repository for extra crash information, consulted in GetExtendedCrashInformation.
Definition Process.h:3627
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:7016
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4839
bool SetPublicRunLockToStopped()
Definition Process.h:3433
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6213
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3926
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.cpp:3765
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:6751
virtual void DidResume()
Called after resuming a process.
Definition Process.h:1127
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6245
void SetCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6201
AllocatedMemoryCache m_allocated_memory_cache
Definition Process.h:3560
virtual Status LoadCore()
Definition Process.cpp:3048
std::mutex m_exit_status_mutex
Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads.
Definition Process.h:3503
Status Signal(int signal)
Sends a process a UNIX signal signal.
Definition Process.cpp:3906
void SetDynamicLoader(lldb::DynamicLoaderUP dyld)
Definition Process.cpp:3113
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:3512
std::recursive_mutex m_thread_mutex
Definition Process.h:3505
virtual Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure asynchronous structured data feature.
Definition Process.cpp:6547
virtual Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.h:957
bool m_currently_handling_do_on_removals
Definition Process.h:3568
void HandlePrivateEvent(lldb::EventSP &event_sp)
Definition Process.cpp:4253
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4887
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:940
ProcessRunLock & GetRunLock()
Definition Process.cpp:6156
virtual Status DoLoadCore()
Definition Process.h:621
Predicate< uint32_t > m_iohandler_sync
Definition Process.h:3557
LanguageRuntimeCollection m_language_runtimes
Should we detach if the process object goes away with an explicit call to Kill or Detach?
Definition Process.h:3563
virtual Status GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list)
Obtain all the mapped memory regions within this process.
Definition Process.cpp:6510
size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, Status &error)
Definition Process.cpp:2543
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:3640
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:2793
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:3657
lldb::OperatingSystemUP m_os_up
Definition Process.h:3542
uint32_t GetLastNaturalStopID() const
Definition Process.h:1513
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:3545
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:3574
void SetDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6207
virtual Status DoConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.h:969
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:2456
llvm::once_flag m_dlopen_utility_func_flag_once
Definition Process.h:3620
virtual void UpdateQueueListIfNeeded()
Definition Process.cpp:1244
virtual Status UpdateAutomaticSignalFiltering()
Definition Process.cpp:6651
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:3609
virtual Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
Attach to an existing process using a process ID.
Definition Process.h:987
llvm::SmallVector< std::optional< std::string > > ReadCStringsFromMemory(llvm::ArrayRef< lldb::addr_t > addresses)
Definition Process.cpp:2262
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition Process.cpp:2759
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:4880
bool GetShouldDetach() const
Definition Process.h:766
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:3498
bool ProcessIOHandlerExists() const
Definition Process.h:3713
virtual Status DoResume(lldb::RunDirection direction)
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.h:1116
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6622
virtual void DidDestroy()
Definition Process.h:1215
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:2412
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2517
bool IsBreakpointSiteEnabled(const BreakpointSite &site)
Definition Process.cpp:1662
Broadcaster m_private_state_control_broadcaster
Definition Process.h:3480
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:6183
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:3477
virtual bool DetachRequiresHalt()
Definition Process.h:1188
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:3506
lldb::addr_t m_data_address_mask
Definition Process.h:3599
virtual ArchSpec GetSystemArchitecture()
Get the system architecture for this process.
Definition Process.h:732
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2764
virtual Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2840
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:1021
virtual lldb::addr_t ResolveIndirectFunction(const Address *address, Status &error)
Resolve dynamically loaded indirect functions.
Definition Process.cpp:6282
lldb::StateType m_last_broadcast_state
Definition Process.h:3606
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:3493
virtual bool FindModuleUUID(ModuleSpec &spec)
Given a module spec, try to find the UUID information.
Definition Process.cpp:6382
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:548
friend class Target
Definition Process.h:365
virtual JITLoaderList & GetJITLoaders()
Definition Process.cpp:3123
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:3524
void PrintWarningOptimization(const SymbolContext &sc)
Print a user-visible warning about a module being built with optimization.
Definition Process.cpp:6346
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:3104
static ProcessProperties & GetGlobalProperties()
Definition Process.cpp:556
lldb::addr_t m_highmem_code_address_mask
Definition Process.h:3600
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6423
int m_exit_status
The exit status of the process, or -1 if not set.
Definition Process.h:3501
std::vector< LanguageRuntime * > GetLanguageRuntimes()
Definition Process.cpp:1498
void SetShouldDetach(bool b)
Definition Process.h:768
bool StartPrivateStateThread(lldb::StateType state, bool run_lock_is_running, std::shared_ptr< PrivateStateThread > *backup_ptr=nullptr)
Definition Process.cpp:4118
MemoryCache m_memory_cache
Definition Process.h:3558
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4973
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
Definition Process.cpp:6372
virtual void DidHalt()
Called after halting a process.
Definition Process.h:1160
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:6227
lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:2847
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:3243
bool SetPrivateRunLockToRunning()
Definition Process.h:3427
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:3930
uint32_t GetStopID() const
Definition Process.h:1505
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1411
lldb::addr_t m_highmem_data_address_mask
Definition Process.h:3601
virtual Status DoDestroy()=0
Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Definition Process.cpp:3713
bool GetWatchpointReportedAfter()
Whether lldb will be notified about watchpoints after the instruction has completed executing,...
Definition Process.cpp:2774
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:3262
bool StateChangedIsExternallyHijacked()
Definition Process.cpp:1393
lldb::StateType GetPublicState() const
Definition Process.h:3451
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4954
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2559
virtual llvm::Expected< bool > SaveCore(llvm::StringRef outfile)
Save core dump into the specified file.
Definition Process.cpp:3119
bool ProcessIOHandlerIsActive()
Definition Process.cpp:4998
Status DestroyImpl(bool force_kill)
Definition Process.cpp:3829
bool m_force_next_event_delivery
Definition Process.h:3605
void GetStatus(Stream &ostrm, bool is_verbose=false)
Definition Process.cpp:6049
lldb::SystemRuntimeUP m_system_runtime_up
Definition Process.h:3543
virtual Status WillHalt()
Called before halting to a process.
Definition Process.h:1135
bool ShouldBroadcastEvent(Event *event_ptr)
This is the part of the event handling that for a process event.
Definition Process.cpp:3934
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3107
std::string m_exit_string
A textual description of why a process exited.
Definition Process.h:3502
lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up
The functions used by the expression parser to validate data that expressions use.
Definition Process.h:3537
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:3193
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:4979
virtual Status Attach(ProcessAttachInfo &attach_info)
Attach to an existing process using the process attach info.
Definition Process.cpp:3233
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:6176
std::recursive_mutex & GetPrivateStateMutex()
Definition Process.h:3446
virtual bool ShouldUseDelayedBreakpoints() const
Reports whether this process should delay physically enabling/disabling breakpoints until the process...
Definition Process.h:2363
void SynchronouslyNotifyStateChanged(lldb::StateType state)
Definition Process.cpp:639
bool SetPrivateRunLockToStopped()
Definition Process.h:3421
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2726
virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info)
Attach to an existing process using a partial process name.
Definition Process.h:1008
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3508
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:3921
void SetBaseDirection(lldb::RunDirection direction)
Set the base run direction for the process.
Definition Process.cpp:3534
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:6767
virtual size_t DoReadMemory(lldb::addr_t vm_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:1587
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
Definition Process.h:1549
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3475
virtual void DoDidExec()
Subclasses of Process should implement this function if they need to do anything after a process exec...
Definition Process.h:1033
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:2526
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:2083
lldb::addr_t GetCodeAddressMask()
Get the current address mask in the Process.
Definition Process.cpp:6169
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:6486
friend class DynamicLoader
Definition Process.h:362
static void SettingsTerminate()
Definition Process.cpp:5037
lldb::addr_t GetHighmemDataAddressMask()
Definition Process.cpp:6192
ThreadList m_extended_thread_list
Constituent for extended threads that may be generated, cleared on natural stops.
Definition Process.h:3517
bool CallVoidArgVoidPtrReturn(const Address *address, lldb::addr_t &returned_func, bool trap_exceptions=false)
Definition Process.cpp:6674
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6127
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:3611
lldb::pid_t m_pid
Definition Process.h:3476
const lldb::ABISP & GetABI()
Definition Process.cpp:1492
friend class Debugger
Definition Process.h:361
Status WillLaunch(Module *module)
Called before launching to a process.
Definition Process.cpp:3220
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:7074
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:2640
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4935
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
Definition Process.cpp:6386
bool PrivateStateThreadIsRunning() const
Definition Process.h:3182
lldb::thread_result_t RunPrivateStateThread(PrivateStateThread::Purpose purpose)
Definition Process.cpp:4374
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:3549
std::atomic< bool > m_finalizing
The tid of the thread that issued the async interrupt, used by thread plan timeout.
Definition Process.h:3581
std::recursive_mutex m_language_runtimes_mutex
Definition Process.h:3564
std::string m_stderr_data
Definition Process.h:3554
friend class ThreadList
Definition Process.h:366
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1258
virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2834
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:162
bool SignExtend(uint32_t bit_pos)
Definition Scalar.cpp:762
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:365
size_t GetAsMemoryData(void *dst, size_t dst_len, lldb::ByteOrder dst_byte_order, Status &error) const
Definition Scalar.cpp:788
long long SLongLong(long long fail_value=0) const
Definition Scalar.cpp:361
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:504
bool IsIndirect() const
Definition Symbol.cpp:223
ConstString GetName() const
Definition Symbol.cpp:511
Address GetAddress() const
Definition Symbol.h:89
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:5222
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:5215
Module * GetExecutableModulePointer()
Definition Target.cpp:1640
Debugger & GetDebugger() const
Definition Target.h:1326
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:4113
void ClearAllLoadedSections()
Definition Target.cpp:3565
void ClearModules(bool delete_locations)
Definition Target.cpp:1644
Architecture * GetArchitecturePlugin() const
Definition Target.h:1324
TargetStats & GetStatistics()
Definition Target.h:2181
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1786
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2706
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1624
void DidExec()
Called as the last function in Process::DidExec().
Definition Target.cpp:1651
bool RunStopHooks(bool at_initial_stop=false)
Definition Target.cpp:3232
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3455
lldb::PlatformSP GetPlatform()
Definition Target.h:1971
const ArchSpec & GetArchitecture() const
Definition Target.h:1285
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1657
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:1973
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:3764
"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:339
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:85
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:87
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:83
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:82
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:84
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:3636
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:421
void(* process_state_changed)(void *baton, Process *process, lldb::StateType state)
Definition Process.h:424
void(* initialize)(void *baton, Process *process)
Definition Process.h:423
The PrivateStateThread struct gathers all the bits of state needed to manage handling Process events,...
Definition Process.h:3316
Process & m_process
The process state that we show to client code.
Definition Process.h:3397
Purpose m_purpose
This will be the thread name given to the Private State HostThread when it gets spun up.
Definition Process.h:3415
bool IsOnThread(const HostThread &thread) const
Definition Process.cpp:4107
Policy::PrivateStatePurpose Purpose
Why this PST exists.
Definition Process.h:3323
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