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