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