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