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