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