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 // StartPrivateStateThread does nothing if the thread is already running, so
3264 // publish the state ourselves.
3265 auto start_private_state_thread = [this] {
3267 SetPublicState(lldb::eStateAttaching, /*restarted=*/false);
3269 } else {
3271 }
3272 };
3273
3274 lldb::pid_t attach_pid = attach_info.GetProcessID();
3275 Status error;
3276 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3277 char process_name[PATH_MAX];
3278
3279 if (attach_info.GetExecutableFile().GetPath(process_name,
3280 sizeof(process_name))) {
3281 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3282
3283 if (wait_for_launch) {
3284 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3285 if (error.Success()) {
3286 m_should_detach = true;
3287 // Now attach using these arguments.
3288 error = DoAttachToProcessWithName(process_name, attach_info);
3289
3290 if (error.Fail()) {
3291 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3293 if (error.AsCString() == nullptr)
3294 error = Status::FromErrorString("attach failed");
3295
3296 SetExitStatus(-1, error.AsCString());
3297 }
3298 } else {
3300 this, attach_info.GetResumeCount()));
3301 start_private_state_thread();
3303 // We are not going to get any further here. The only way
3304 // this could fail is if we can't start a host thread, and we're
3305 // pretty much toast at that point.
3307 "could not start private state thread.");
3308 }
3309 }
3310 return error;
3311 }
3312 } else {
3313 ProcessInstanceInfoList process_infos;
3314 PlatformSP platform_sp(GetTarget().GetPlatform());
3315
3316 if (platform_sp) {
3317 ProcessInstanceInfoMatch match_info;
3318 match_info.GetProcessInfo() = attach_info;
3320 platform_sp->FindProcesses(match_info, process_infos);
3321 const uint32_t num_matches = process_infos.size();
3322 if (num_matches == 1) {
3323 attach_pid = process_infos[0].GetProcessID();
3324 // Fall through and attach using the above process ID
3325 } else {
3327 process_name, sizeof(process_name));
3328 if (num_matches > 1) {
3329 StreamString s;
3331 for (size_t i = 0; i < num_matches; i++) {
3332 process_infos[i].DumpAsTableRow(
3333 s, platform_sp->GetUserIDResolver(), true, false);
3334 }
3336 "more than one process named %s:\n%s", process_name,
3337 s.GetData());
3338 } else
3340 "could not find a process named %s", process_name);
3341 }
3342 } else {
3344 "invalid platform, can't find processes by name");
3345 return error;
3346 }
3347 }
3348 } else {
3349 error = Status::FromErrorString("invalid process name");
3350 }
3351 }
3352
3353 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3354 error = WillAttachToProcessWithID(attach_pid);
3355 if (error.Success()) {
3356 // Now attach using these arguments.
3357 m_should_detach = true;
3358 error = DoAttachToProcessWithID(attach_pid, attach_info);
3359
3360 if (error.Success()) {
3362 this, attach_info.GetResumeCount()));
3363
3364 start_private_state_thread();
3366 // We are not going to get any further here. The only way this
3367 // could fail is if we can't start a host thread, so we're pretty much
3368 // toast at thatpoint.
3370 "could not start private state thread.");
3371 }
3372 } else {
3375
3376 const char *error_string = error.AsCString();
3377 if (error_string == nullptr)
3378 error_string = "attach failed";
3379
3380 SetExitStatus(-1, error_string);
3381 }
3382 }
3383 }
3384 return error;
3385}
3386
3389 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
3390
3391 // Let the process subclass figure out at much as it can about the process
3392 // before we go looking for a dynamic loader plug-in.
3393 ArchSpec process_arch;
3394 DidAttach(process_arch);
3395
3396 if (process_arch.IsValid()) {
3397 LLDB_LOG(log,
3398 "Process::{0} replacing process architecture with DidAttach() "
3399 "architecture: \"{1}\"",
3400 __FUNCTION__, process_arch.GetTriple().getTriple());
3401 GetTarget().SetArchitecture(process_arch);
3402 }
3403
3404 // We just attached. If we have a platform, ask it for the process
3405 // architecture, and if it isn't the same as the one we've already set,
3406 // switch architectures.
3407 PlatformSP platform_sp(GetTarget().GetPlatform());
3408 assert(platform_sp);
3409 ArchSpec process_host_arch = GetSystemArchitecture();
3410 if (platform_sp) {
3411 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3412 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
3413 target_arch, process_host_arch,
3414 ArchSpec::CompatibleMatch, nullptr)) {
3415 ArchSpec platform_arch;
3417 target_arch, process_host_arch, &platform_arch);
3418 if (platform_sp) {
3419 GetTarget().SetPlatform(platform_sp);
3420 GetTarget().SetArchitecture(platform_arch);
3421 LLDB_LOG(log,
3422 "switching platform to {0} and architecture to {1} based on "
3423 "info from attach",
3424 platform_sp->GetName(), platform_arch.GetTriple().getTriple());
3425 }
3426 } else if (!process_arch.IsValid()) {
3427 ProcessInstanceInfo process_info;
3428 GetProcessInfo(process_info);
3429 const ArchSpec &process_arch = process_info.GetArchitecture();
3430 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3431 if (process_arch.IsValid() &&
3432 target_arch.IsCompatibleMatch(process_arch) &&
3433 !target_arch.IsExactMatch(process_arch)) {
3434 GetTarget().SetArchitecture(process_arch);
3435 LLDB_LOGF(log,
3436 "Process::%s switching architecture to %s based on info "
3437 "the platform retrieved for pid %" PRIu64,
3438 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3439 GetID());
3440 }
3441 }
3442 }
3443 // Now that we know the process type, update its signal responses from the
3444 // ones stored in the Target:
3447 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());
3448
3449 // We have completed the attach, now it is time to find the dynamic loader
3450 // plug-in
3452 if (dyld) {
3453 dyld->DidAttach();
3454 if (log) {
3455 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3456 LLDB_LOG(log,
3457 "after DynamicLoader::DidAttach(), target "
3458 "executable is {0} (using {1} plugin)",
3459 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3460 dyld->GetPluginName());
3461 }
3462 }
3463
3465
3466 SystemRuntime *system_runtime = GetSystemRuntime();
3467 if (system_runtime) {
3468 system_runtime->DidAttach();
3469 if (log) {
3470 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3471 LLDB_LOG(log,
3472 "after SystemRuntime::DidAttach(), target "
3473 "executable is {0} (using {1} plugin)",
3474 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3475 system_runtime->GetPluginName());
3476 }
3477 }
3478
3479 // If we don't have an operating system plugin loaded yet, see if
3480 // LoadOperatingSystemPlugin can find one (and stuff it in m_os_up).
3481 if (!m_os_up)
3483
3484 if (m_os_up) {
3485 // Somebody might have gotten threads before we loaded the OS Plugin above,
3486 // so we need to force the update now or the newly loaded plugin won't get
3487 // a chance to process the threads.
3488 m_thread_list.Clear();
3490 }
3491
3492 // Figure out which one is the executable, and set that in our target:
3493 ModuleSP new_executable_module_sp;
3494 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
3495 if (module_sp && module_sp->IsExecutable()) {
3496 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3497 new_executable_module_sp = module_sp;
3498 break;
3499 }
3500 }
3501 if (new_executable_module_sp) {
3502 // Replacing an executable clears the images, which would drop the
3503 // modules the loader already found.
3504 if (GetTarget().GetExecutableModulePointer())
3505 GetTarget().RebuildModuleListWithExecutable(new_executable_module_sp,
3507 else
3508 GetTarget().MarkExecutableModule(new_executable_module_sp);
3509 if (log) {
3510 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3511 LLDB_LOGF(
3512 log,
3513 "Process::%s after looping through modules, target executable is %s",
3514 __FUNCTION__,
3515 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3516 : "<none>");
3517 }
3518 }
3519 // Since we hijacked the event stream, we will have we won't have run the
3520 // stop hooks. Make sure we do that here:
3521 GetTarget().RunStopHooks(/* at_initial_stop= */ true);
3522}
3523
3524Status Process::ConnectRemote(llvm::StringRef remote_url) {
3525 m_abi_sp.reset();
3526 {
3527 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3528 m_process_input_reader.reset();
3529 }
3530
3531 // Find the process and its architecture. Make sure it matches the
3532 // architecture of the current Target, and if not adjust it.
3533
3534 Status error(DoConnectRemote(remote_url));
3535 if (error.Success()) {
3536 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3537 EventSP event_sp;
3538 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
3539
3540 if (state == eStateStopped || state == eStateCrashed) {
3541 // If we attached and actually have a process on the other end, then
3542 // this ended up being the equivalent of an attach.
3543 SetShouldDetach(true);
3545
3546 // This delays passing the stopped event to listeners till
3547 // CompleteAttach gets a chance to complete...
3548 HandlePrivateEvent(event_sp);
3549 }
3550 }
3551
3554 else {
3556 /*RunLock is stopped */ false);
3558 // We are not going to get any further here. The only way this
3559 // could fail is if we can't start a host thread, so we're pretty much
3560 // toast at that point.
3561 return Status::FromErrorString("could not start private state thread.");
3562 }
3563 }
3564 }
3565 return error;
3566}
3567
3569 if (m_base_direction == direction)
3570 return;
3571 m_thread_list.DiscardThreadPlans();
3572 m_base_direction = direction;
3573}
3574
3577 LLDB_LOGF(log,
3578 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3579 "private state: %s",
3580 m_mod_id.GetStopID(), StateAsCString(GetPublicState()),
3582
3583 // If signals handing status changed we might want to update our signal
3584 // filters before resuming.
3586 // Clear any crash info we accumulated for this stop, but don't do so if we
3587 // are running functions; we don't want to wipe out the real stop's info.
3588 if (!GetModID().IsLastResumeForUserExpression())
3590
3592 // Tell the process it is about to resume before the thread list
3593 if (error.Success()) {
3594 // Now let the thread list know we are about to resume so it can let all of
3595 // our threads know that they are about to be resumed. Threads will each be
3596 // called with Thread::WillResume(StateType) where StateType contains the
3597 // state that they are supposed to have when the process is resumed
3598 // (suspended/running/stepping). Threads should also check their resume
3599 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3600 // start back up with a signal.
3601 RunDirection direction;
3602 if (m_thread_list.WillResume(direction)) {
3603 LLDB_LOGF(log, "Process::PrivateResume WillResume direction=%d",
3604 direction);
3605 // Last thing, do the PreResumeActions.
3606 if (!RunPreResumeActions()) {
3608 "Process::PrivateResume PreResumeActions failed, not resuming.");
3609 LLDB_LOGF(
3610 log,
3611 "Process::PrivateResume PreResumeActions failed, not resuming.");
3612 } else {
3613 m_mod_id.BumpResumeID();
3614 if (auto E = FlushDelayedBreakpoints())
3615 LLDB_LOG_ERROR(log, std::move(E),
3616 "Failed to update some delayed breakpoints: {0}");
3617 error = DoResume(direction);
3618 if (error.Success()) {
3619 DidResume();
3620 m_thread_list.DidResume();
3621 LLDB_LOGF(log,
3622 "Process::PrivateResume thinks the process has resumed.");
3623 } else {
3624 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3625 return error;
3626 }
3627 }
3628 } else {
3629 // Somebody wanted to run without running (e.g. we were faking a step
3630 // from one frame of a set of inlined frames that share the same PC to
3631 // another.) So generate a continue & a stopped event, and let the world
3632 // handle them.
3633 LLDB_LOGF(log,
3634 "Process::PrivateResume() asked to simulate a start & stop.");
3635
3638 }
3639 } else
3640 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3641 error.AsCString("<unknown error>"));
3642 return error;
3643}
3644
3645Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3647 return Status::FromErrorString("Process is not running.");
3648
3649 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3650 // case it was already set and some thread plan logic calls halt on its own.
3651 m_clear_thread_plans_on_stop |= clear_thread_plans;
3652
3653 ListenerSP halt_listener_sp(
3654 Listener::MakeListener("lldb.process.halt_listener"));
3655 HijackProcessEvents(halt_listener_sp);
3656
3657 EventSP event_sp;
3658
3660
3662 // Don't hijack and eat the eStateExited as the code that was doing the
3663 // attach will be waiting for this event...
3665 Destroy(false);
3666 SetExitStatus(SIGKILL, "Cancelled async attach.");
3667 return Status();
3668 }
3669
3670 // Wait for the process halt timeout seconds for the process to stop.
3671 // If we are going to use the run lock, that means we're stopping out to the
3672 // user, so we should also select the most relevant frame.
3673 SelectMostRelevant select_most_relevant =
3675 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3676 halt_listener_sp, nullptr,
3677 use_run_lock, select_most_relevant);
3679
3680 if (state == eStateInvalid || !event_sp) {
3681 // We timed out and didn't get a stop event...
3682 return Status::FromErrorStringWithFormat("Halt timed out. State = %s",
3684 }
3685
3686 BroadcastEvent(event_sp);
3687
3688 return Status();
3689}
3690
3692 const uint8_t *buf, size_t size) {
3693 const size_t region_size = high - low;
3694
3695 if (region_size < size)
3696 return LLDB_INVALID_ADDRESS;
3697
3698 // See "Boyer-Moore string search algorithm".
3699 std::vector<size_t> bad_char_heuristic(256, size);
3700 for (size_t idx = 0; idx < size - 1; idx++) {
3701 decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];
3702 bad_char_heuristic[bcu_idx] = size - idx - 1;
3703 }
3704
3705 // Memory we're currently searching through.
3706 llvm::SmallVector<uint8_t, 0> mem;
3707 // Position of the memory buffer.
3708 addr_t mem_pos = low;
3709 // Maximum number of bytes read (and buffered). We need to read at least
3710 // `size` bytes for a successful match.
3711 const size_t max_read_size = std::max<size_t>(size, 0x10000);
3712
3713 for (addr_t cur_addr = low; cur_addr <= (high - size);) {
3714 if (cur_addr + size > mem_pos + mem.size()) {
3715 // We need to read more data. We don't attempt to reuse the data we've
3716 // already read (up to `size-1` bytes from `cur_addr` to
3717 // `mem_pos+mem.size()`). This is fine for patterns much smaller than
3718 // max_read_size. For very
3719 // long patterns we may need to do something more elaborate.
3720 mem.resize_for_overwrite(max_read_size);
3721 Status error;
3722 mem.resize(ReadMemory(cur_addr, mem.data(),
3723 std::min<addr_t>(mem.size(), high - cur_addr),
3724 error));
3725 mem_pos = cur_addr;
3726 if (size > mem.size()) {
3727 // We didn't read enough data. Skip to the next memory region.
3728 MemoryRegionInfo info;
3729 error = GetMemoryRegionInfo(mem_pos + mem.size(), info);
3730 if (error.Fail())
3731 break;
3732 cur_addr = info.GetRange().GetRangeEnd();
3733 continue;
3734 }
3735 }
3736 int64_t j = size - 1;
3737 while (j >= 0 && buf[j] == mem[cur_addr + j - mem_pos])
3738 j--;
3739 if (j < 0)
3740 return cur_addr; // We have a match.
3741 cur_addr += bad_char_heuristic[mem[cur_addr + size - 1 - mem_pos]];
3742 }
3743
3744 return LLDB_INVALID_ADDRESS;
3745}
3746
3748 Status error;
3749
3750 // Check both the public & private states here. If we're hung evaluating an
3751 // expression, for instance, then the public state will be stopped, but we
3752 // still need to interrupt.
3754 Log *log = GetLog(LLDBLog::Process);
3755 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3756
3757 ListenerSP listener_sp(
3758 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3759 HijackProcessEvents(listener_sp);
3760
3762
3763 // Consume the interrupt event.
3765 &exit_event_sp, true, listener_sp);
3766
3768
3769 // If the process exited while we were waiting for it to stop, put the
3770 // exited event into the shared pointer passed in and return. Our caller
3771 // doesn't need to do anything else, since they don't have a process
3772 // anymore...
3773
3774 if (state == eStateExited || GetPrivateState() == eStateExited) {
3775 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3776 __FUNCTION__);
3777 return error;
3778 } else
3779 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3780
3781 if (state != eStateStopped) {
3782 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3783 StateAsCString(state));
3784 // If we really couldn't stop the process then we should just error out
3785 // here, but if the lower levels just bobbled sending the event and we
3786 // really are stopped, then continue on.
3787 StateType private_state = GetPrivateState();
3788 if (private_state != eStateStopped) {
3790 "Attempt to stop the target in order to detach timed out. "
3791 "State = %s",
3793 }
3794 }
3795 }
3796 return error;
3797}
3798
3799Status Process::Detach(bool keep_stopped) {
3800 EventSP exit_event_sp;
3801 Status error;
3802 m_destroy_in_process = true;
3803
3804 error = WillDetach();
3805
3806 if (error.Success()) {
3807 if (DetachRequiresHalt()) {
3808 error = StopForDestroyOrDetach(exit_event_sp);
3809 if (!error.Success()) {
3810 m_destroy_in_process = false;
3811 return error;
3812 } else if (exit_event_sp) {
3813 // We shouldn't need to do anything else here. There's no process left
3814 // to detach from...
3816 m_destroy_in_process = false;
3817 return error;
3818 }
3819 }
3820
3821 m_thread_list.DiscardThreadPlans();
3823 if (auto error = FlushDelayedBreakpoints())
3825 GetLog(LLDBLog::Process), std::move(error),
3826 "Failed to update some delayed breakpoints during detach: {0}");
3827
3828 error = DoDetach(keep_stopped);
3829 if (error.Success()) {
3830 DidDetach();
3832 } else {
3833 return error;
3834 }
3835 }
3836 m_destroy_in_process = false;
3837
3838 // If we exited when we were waiting for a process to stop, then forward the
3839 // event here so we don't lose the event
3840 if (exit_event_sp) {
3841 // Directly broadcast our exited event because we shut down our private
3842 // state thread above
3843 BroadcastEvent(exit_event_sp);
3844 }
3845
3846 // If we have been interrupted (to kill us) in the middle of running, we may
3847 // not end up propagating the last events through the event system, in which
3848 // case we might strand the write lock. Unlock it here so when we do to tear
3849 // down the process we don't get an error destroying the lock.
3850
3852 return error;
3853}
3854
3855Status Process::Destroy(bool force_kill) {
3856 // If we've already called Process::Finalize then there's nothing useful to
3857 // be done here. Finalize has actually called Destroy already.
3858 if (m_finalizing)
3859 return {};
3860 return DestroyImpl(force_kill);
3861}
3862
3864 // Tell ourselves we are in the process of destroying the process, so that we
3865 // don't do any unnecessary work that might hinder the destruction. Remember
3866 // to set this back to false when we are done. That way if the attempt
3867 // failed and the process stays around for some reason it won't be in a
3868 // confused state.
3869
3870 if (force_kill)
3871 m_should_detach = false;
3872
3873 if (GetShouldDetach()) {
3874 // FIXME: This will have to be a process setting:
3875 bool keep_stopped = false;
3876 Detach(keep_stopped);
3877 }
3878
3879 m_destroy_in_process = true;
3880
3882 if (error.Success()) {
3883 EventSP exit_event_sp;
3884 if (DestroyRequiresHalt()) {
3885 error = StopForDestroyOrDetach(exit_event_sp);
3886 }
3887
3888 if (GetPublicState() == eStateStopped) {
3889 // Ditch all thread plans, and remove all our breakpoints: in case we
3890 // have to restart the target to kill it, we don't want it hitting a
3891 // breakpoint... Only do this if we've stopped, however, since if we
3892 // didn't manage to halt it above, then we're not going to have much luck
3893 // doing this now.
3894 m_thread_list.DiscardThreadPlans();
3896 if (auto error = FlushDelayedBreakpoints())
3898 GetLog(LLDBLog::Process), std::move(error),
3899 "Failed to update some delayed breakpoints during destroy: {0}");
3900 }
3901
3902 error = DoDestroy();
3903 if (error.Success()) {
3904 DidDestroy();
3906 }
3907 // Not draining: We are tearing the process down, so we don't care about its
3908 // remaining output as no one could read it.
3909 StopSTDIOMonitoring(/*drain=*/false);
3910
3911 {
3912 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3914 m_process_input_reader->SetIsDone(true);
3915 m_process_input_reader->Cancel();
3916 m_process_input_reader.reset();
3917 }
3918 }
3919
3920 // If we exited when we were waiting for a process to stop, then forward
3921 // the event here so we don't lose the event
3922 if (exit_event_sp) {
3923 // Directly broadcast our exited event because we shut down our private
3924 // state thread above
3925 BroadcastEvent(exit_event_sp);
3926 }
3927
3928 // If we have been interrupted (to kill us) in the middle of running, we
3929 // may not end up propagating the last events through the event system, in
3930 // which case we might strand the write lock. Unlock it here so when we do
3931 // to tear down the process we don't get an error destroying the lock.
3933 }
3934
3935 m_destroy_in_process = false;
3936
3937 return error;
3938}
3939
3942 if (error.Success()) {
3943 error = DoSignal(signal);
3944 if (error.Success())
3945 DidSignal();
3946 }
3947 return error;
3948}
3949
3951 assert(signals_sp && "null signals_sp");
3952 m_unix_signals_sp = std::move(signals_sp);
3953}
3954
3956 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3957 return m_unix_signals_sp;
3958}
3959
3963
3967
3969 const StateType state =
3971 bool return_value = true;
3973
3974 switch (state) {
3975 case eStateDetached:
3976 case eStateExited:
3977 case eStateUnloaded:
3978 // The inferior is gone, so this is our last chance to pick up whatever it
3979 // wrote before it went away.
3980 StopSTDIOMonitoring(/*drain=*/true);
3981
3982 [[fallthrough]];
3983 case eStateConnected:
3984 case eStateAttaching:
3985 case eStateLaunching:
3986 // These events indicate changes in the state of the debugging session,
3987 // always report them.
3988 return_value = true;
3989 break;
3990 case eStateInvalid:
3991 // We stopped for no apparent reason, don't report it.
3992 return_value = false;
3993 break;
3994 case eStateRunning:
3995 case eStateStepping:
3996 // If we've started the target running, we handle the cases where we are
3997 // already running and where there is a transition from stopped to running
3998 // differently. running -> running: Automatically suppress extra running
3999 // events stopped -> running: Report except when there is one or more no
4000 // votes
4001 // and no yes votes.
4004 return_value = true;
4005 else {
4006 switch (m_last_broadcast_state) {
4007 case eStateRunning:
4008 case eStateStepping:
4009 // We always suppress multiple runnings with no PUBLIC stop in between.
4010 return_value = false;
4011 break;
4012 default:
4013 // TODO: make this work correctly. For now always report
4014 // run if we aren't running so we don't miss any running events. If I
4015 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
4016 // and hit the breakpoints on multiple threads, then somehow during the
4017 // stepping over of all breakpoints no run gets reported.
4018
4019 // This is a transition from stop to run.
4020 switch (m_thread_list.ShouldReportRun(event_ptr)) {
4021 case eVoteYes:
4022 case eVoteNoOpinion:
4023 return_value = true;
4024 break;
4025 case eVoteNo:
4026 return_value = false;
4027 break;
4028 }
4029 break;
4030 }
4031 }
4032 break;
4033 case eStateStopped:
4034 case eStateCrashed:
4035 case eStateSuspended:
4036 // We've stopped. First see if we're going to restart the target. If we
4037 // are going to stop, then we always broadcast the event. If we aren't
4038 // going to stop, let the thread plans decide if we're going to report this
4039 // event. If no thread has an opinion, we don't report it.
4040
4041 m_stdio_communication.SynchronizeWithReadThread();
4044 LLDB_LOGF(log,
4045 "Process::ShouldBroadcastEvent (%p) stopped due to an "
4046 "interrupt, state: %s",
4047 static_cast<void *>(event_ptr), StateAsCString(state));
4048 // Even though we know we are going to stop, we should let the threads
4049 // have a look at the stop, so they can properly set their state.
4050 m_thread_list.ShouldStop(event_ptr);
4051 return_value = true;
4052 } else {
4053 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
4054 bool should_resume = false;
4055
4056 // It makes no sense to ask "ShouldStop" if we've already been
4057 // restarted... Asking the thread list is also not likely to go well,
4058 // since we are running again. So in that case just report the event.
4059
4060 if (!was_restarted)
4061 should_resume = !m_thread_list.ShouldStop(event_ptr);
4062
4063 if (was_restarted || should_resume || m_resume_requested) {
4064 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
4065 LLDB_LOGF(log,
4066 "Process::ShouldBroadcastEvent: should_resume: %i state: "
4067 "%s was_restarted: %i report_stop_vote: %d.",
4068 should_resume, StateAsCString(state), was_restarted,
4069 report_stop_vote);
4070
4071 switch (report_stop_vote) {
4072 case eVoteYes:
4073 return_value = true;
4074 break;
4075 case eVoteNoOpinion:
4076 case eVoteNo:
4077 return_value = false;
4078 break;
4079 }
4080
4081 if (!was_restarted) {
4082 LLDB_LOGF(log,
4083 "Process::ShouldBroadcastEvent (%p) Restarting process "
4084 "from state: %s",
4085 static_cast<void *>(event_ptr), StateAsCString(state));
4087 PrivateResume();
4088 }
4089 } else {
4090 return_value = true;
4092 }
4093 }
4094 break;
4095 }
4096
4097 // Forcing the next event delivery is a one shot deal. So reset it here.
4099
4100 // We do some coalescing of events (for instance two consecutive running
4101 // events get coalesced.) But we only coalesce against events we actually
4102 // broadcast. So we use m_last_broadcast_state to track that. NB - you
4103 // can't use "m_public_state.GetValue()" for that purpose, as was originally
4104 // done, because the PublicState reflects the last event pulled off the
4105 // queue, and there may be several events stacked up on the queue unserviced.
4106 // So the PublicState may not reflect the last broadcasted event yet.
4107 // m_last_broadcast_state gets updated here.
4108
4109 if (return_value)
4110 m_last_broadcast_state = state;
4111
4112 LLDB_LOGF(log,
4113 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
4114 "broadcast state: %s - %s",
4115 static_cast<void *>(event_ptr), StateAsCString(state),
4117 return_value ? "YES" : "NO");
4118 return return_value;
4119}
4120
4122 llvm::Expected<HostThread> private_state_thread =
4125 [this] { return m_process.RunPrivateStateThread(m_purpose); },
4126 8 * 1024 * 1024);
4127 if (!private_state_thread) {
4128 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
4129 "failed to launch host thread: {0}");
4130 return false;
4131 }
4132
4133 assert(private_state_thread->IsJoinable());
4134 m_private_state_thread = *private_state_thread;
4135 m_is_running = true;
4136 m_process.ResumePrivateStateThread();
4137 return true;
4138}
4139
4141 return m_private_state_thread.EqualsThread(thread);
4142}
4143
4150
4152 lldb::StateType state, bool run_lock_is_running,
4153 std::shared_ptr<PrivateStateThread> *backup_ptr) {
4154 Log *log = GetLog(LLDBLog::Events);
4155
4156 bool already_running = PrivateStateThreadIsRunning();
4157 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
4158 already_running ? " already running"
4159 : " starting private state thread");
4160
4161 if (backup_ptr == nullptr && already_running)
4162 return true;
4163
4164 // Create a thread that watches our internal state and controls which events
4165 // make it to clients (into the DCProcess event queue).
4166 char thread_name[1024];
4167 uint32_t max_len = llvm::get_max_thread_name_length();
4168 if (max_len > 0 && max_len <= 30) {
4169 // On platforms with abbreviated thread name lengths, choose thread names
4170 // that fit within the limit.
4171 if (already_running)
4172 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4173 else
4174 snprintf(thread_name, sizeof(thread_name), "intern-state");
4175 } else {
4176 if (already_running)
4177 snprintf(thread_name, sizeof(thread_name),
4178 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
4179 GetID());
4180 else
4181 snprintf(thread_name, sizeof(thread_name),
4182 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
4183 }
4184
4185 if (backup_ptr) {
4186 // StartupThread expects the m_current_private_state_thread_sp to be in
4187 // place already, so do that first:
4190 *this, GetPublicState(), GetPrivateState(), thread_name,
4191 PrivateStateThread::Purpose::RunningExpression));
4192 } else
4193 m_current_private_state_thread_sp->SetThreadName(thread_name);
4194
4195 SetPublicState(state, /*restarted=*/false);
4196 if (run_lock_is_running)
4198 else
4200
4201 return m_current_private_state_thread_sp->StartupThread();
4202}
4203
4207
4211
4214 return;
4215
4216 if (m_current_private_state_thread_sp->IsJoinable())
4218 else {
4219 Log *log = GetLog(LLDBLog::Process);
4220 LLDB_LOGF(
4221 log,
4222 "Went to stop the private state thread, but it was already invalid.");
4223 }
4224}
4225
4227 Log *log = GetLog(LLDBLog::Process);
4228
4229 assert(signal == eBroadcastInternalStateControlStop ||
4232
4233 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
4234
4235 // Signal the private state thread
4236 if (m_current_private_state_thread_sp->IsJoinable()) {
4237 // Broadcast the event.
4238 // It is important to do this outside of the if below, because it's
4239 // possible that the thread state is invalid but that the thread is waiting
4240 // on a control event instead of simply being on its way out (this should
4241 // not happen, but it apparently can).
4242 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
4243 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
4244 m_private_state_control_broadcaster.BroadcastEvent(signal,
4245 event_receipt_sp);
4246
4247 // Wait for the event receipt or for the private state thread to exit
4248 bool receipt_received = false;
4250 while (!receipt_received) {
4251 // Check for a receipt for n seconds and then check if the private
4252 // state thread is still around.
4253 receipt_received =
4254 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
4255 if (!receipt_received) {
4256 // Check if the private state thread is still around. If it isn't
4257 // then we are done waiting
4259 break; // Private state thread exited or is exiting, we are done
4260 }
4261 }
4262 }
4263
4265 m_current_private_state_thread_sp->JoinAndReset();
4266
4267 } else {
4268 LLDB_LOGF(
4269 log,
4270 "Private state thread already dead, no need to signal it to stop.");
4271 }
4272}
4273
4275 if (thread != nullptr)
4276 m_interrupt_tid = thread->GetProtocolID();
4277 else
4281 nullptr);
4282 else
4284}
4285
4287 Log *log = GetLog(LLDBLog::Process);
4288 m_resume_requested = false;
4289
4290 const StateType new_state =
4292
4293#ifdef LLDB_SIMULATE_SLOW_STOPS
4294 // Simulate a slow machine that takes a long time to process an internal
4295 // stop, so that ThreadPlanSingleThreadTimeout's 10ms timer fires while we
4296 // are still in here. This is helpful for diagnosing problems in
4297 // the thread plans - particular the interaction with the
4298 // ThreadPlanSingleThreadTimeout.
4299 if (StateIsStoppedState(new_state, /*must_exist=*/true))
4300 std::this_thread::sleep_for(std::chrono::milliseconds(10));
4301#endif
4302
4303 // First check to see if anybody wants a shot at this event:
4306 m_next_event_action_up->PerformAction(event_sp);
4307 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
4308
4309 switch (action_result) {
4311 SetNextEventAction(nullptr);
4312 break;
4313
4315 break;
4316
4318 // Handle Exiting Here. If we already got an exited event, we should
4319 // just propagate it. Otherwise, swallow this event, and set our state
4320 // to exit so the next event will kill us.
4321 if (new_state != eStateExited) {
4322 // FIXME: should cons up an exited event, and discard this one.
4323 SetExitStatus(0, m_next_event_action_up->GetExitString());
4324 SetNextEventAction(nullptr);
4325 return;
4326 }
4327 SetNextEventAction(nullptr);
4328 break;
4329 }
4330 }
4331
4332 // See if we should broadcast this state to external clients?
4333 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
4334
4335 if (should_broadcast) {
4336 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
4337 LLDB_LOGF(log,
4338 "Process::%s (pid = %" PRIu64
4339 ") broadcasting new state %s (old state %s) to %s",
4340 __FUNCTION__, GetID(), StateAsCString(new_state),
4341 StateAsCString(GetState()), is_hijacked ? "hijacked" : "public");
4343 if (StateIsRunningState(new_state)) {
4344 // Only push the input handler if we aren't fowarding events, as this
4345 // means the curses GUI is in use... Or don't push it if we are launching
4346 // since it will come up stopped.
4347 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
4348 new_state != eStateLaunching && new_state != eStateAttaching) {
4350 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
4352 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
4353 __FUNCTION__, m_iohandler_sync.GetValue());
4354 }
4355 } else if (StateIsStoppedState(new_state, false)) {
4357 // If the lldb_private::Debugger is handling the events, we don't want
4358 // to pop the process IOHandler here, we want to do it when we receive
4359 // the stopped event so we can carefully control when the process
4360 // IOHandler is popped because when we stop we want to display some
4361 // text stating how and why we stopped, then maybe some
4362 // process/thread/frame info, and then we want the "(lldb) " prompt to
4363 // show up. If we pop the process IOHandler here, then we will cause
4364 // the command interpreter to become the top IOHandler after the
4365 // process pops off and it will update its prompt right away... See the
4366 // Debugger.cpp file where it calls the function as
4367 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4368 // Otherwise we end up getting overlapping "(lldb) " prompts and
4369 // garbled output.
4370 //
4371 // If we aren't handling the events in the debugger (which is indicated
4372 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
4373 // we are hijacked, then we always pop the process IO handler manually.
4374 // Hijacking happens when the internal process state thread is running
4375 // thread plans, or when commands want to run in synchronous mode and
4376 // they call "process->WaitForProcessToStop()". An example of something
4377 // that will hijack the events is a simple expression:
4378 //
4379 // (lldb) expr (int)puts("hello")
4380 //
4381 // This will cause the internal process state thread to resume and halt
4382 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4383 // events) and we do need the IO handler to be pushed and popped
4384 // correctly.
4385
4386 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
4388 }
4389 }
4390
4391 BroadcastEvent(event_sp);
4392 } else {
4393 LLDB_LOGF(
4394 log,
4395 "Process::%s (pid = %" PRIu64
4396 ") suppressing state %s (old state %s): should_broadcast == false",
4397 __FUNCTION__, GetID(), StateAsCString(new_state),
4399 }
4400}
4401
4403 EventSP event_sp;
4405 if (error.Fail())
4406 return error;
4407
4408 // Ask the process subclass to actually halt our process
4409 bool caused_stop;
4410 error = DoHalt(caused_stop);
4411
4412 DidHalt();
4413 return error;
4414}
4415
4418 // All PSTs see the private reality (private state, private run lock).
4419 // A PST created to run an expression additionally skips frame providers
4420 // and recognizers, since that's the only reason RunThreadPlan spins up a
4421 // second, temporary PST while the primary one is backed up.
4422 PolicyStack::Guard policy_guard =
4424
4425 bool control_only = true;
4426
4427 Log *log = GetLog(LLDBLog::Process);
4428 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4429 __FUNCTION__, static_cast<void *>(this), GetID());
4430
4431 bool exit_now = false;
4432 bool interrupt_requested = false;
4433 while (!exit_now) {
4434 EventSP event_sp;
4435 GetEventsPrivate(event_sp, std::nullopt, control_only);
4436 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4437 LLDB_LOGF(log,
4438 "Process::%s (arg = %p, pid = %" PRIu64
4439 ") got a control event: %d",
4440 __FUNCTION__, static_cast<void *>(this), GetID(),
4441 event_sp->GetType());
4442
4443 switch (event_sp->GetType()) {
4445 exit_now = true;
4446 break; // doing any internal state management below
4447
4449 control_only = true;
4450 break;
4451
4453 control_only = false;
4454 break;
4455 }
4456
4457 continue;
4458 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4460 LLDB_LOGF(log,
4461 "Process::%s (arg = %p, pid = %" PRIu64
4462 ") woke up with an interrupt while attaching - "
4463 "forwarding interrupt.",
4464 __FUNCTION__, static_cast<void *>(this), GetID());
4465 // The server may be spinning waiting for a process to appear, in which
4466 // case we should tell it to stop doing that. Normally, we don't NEED
4467 // to do that because we will next close the communication to the stub
4468 // and that will get it to shut down. But there are remote debugging
4469 // cases where relying on that side-effect causes the shutdown to be
4470 // flakey, so we should send a positive signal to interrupt the wait.
4474 LLDB_LOGF(log,
4475 "Process::%s (arg = %p, pid = %" PRIu64
4476 ") woke up with an interrupt - Halting.",
4477 __FUNCTION__, static_cast<void *>(this), GetID());
4479 if (error.Fail() && log)
4480 LLDB_LOGF(log,
4481 "Process::%s (arg = %p, pid = %" PRIu64
4482 ") failed to halt the process: %s",
4483 __FUNCTION__, static_cast<void *>(this), GetID(),
4484 error.AsCString());
4485 // Halt should generate a stopped event. Make a note of the fact that
4486 // we were doing the interrupt, so we can set the interrupted flag
4487 // after we receive the event. We deliberately set this to true even if
4488 // HaltPrivate failed, so that we can interrupt on the next natural
4489 // stop.
4490 interrupt_requested = true;
4491 } else {
4492 // This can happen when someone (e.g. Process::Halt) sees that we are
4493 // running and sends an interrupt request, but the process actually
4494 // stops before we receive it. In that case, we can just ignore the
4495 // request. We use m_last_broadcast_state, because the Stopped event
4496 // may not have been popped of the event queue yet, which is when the
4497 // public state gets updated.
4498 LLDB_LOGF(log,
4499 "Process::%s ignoring interrupt as we have already stopped.",
4500 __FUNCTION__);
4501 }
4502 continue;
4503 }
4504
4505 const StateType internal_state =
4507
4508 if (internal_state != eStateInvalid) {
4510 StateIsStoppedState(internal_state, true)) {
4512 m_thread_list.DiscardThreadPlans();
4513 }
4514
4515 if (interrupt_requested) {
4516 if (StateIsStoppedState(internal_state, true)) {
4517 // Only mark interrupt event if it is not thread specific async
4518 // interrupt.
4520 // We requested the interrupt, so mark this as such in the stop
4521 // event so clients can tell an interrupted process from a natural
4522 // stop
4523 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4524 }
4525 interrupt_requested = false;
4526 } else {
4527 LLDB_LOGF(log,
4528 "Process::%s interrupt_requested, but a non-stopped "
4529 "state '%s' received.",
4530 __FUNCTION__, StateAsCString(internal_state));
4531 }
4532 }
4533
4534 HandlePrivateEvent(event_sp);
4535 }
4536
4537 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4538 internal_state == eStateDetached) {
4539 LLDB_LOGF(log,
4540 "Process::%s (arg = %p, pid = %" PRIu64
4541 ") about to exit with internal state %s...",
4542 __FUNCTION__, static_cast<void *>(this), GetID(),
4543 StateAsCString(internal_state));
4544
4545 break;
4546 }
4547 }
4548
4549 // Verify log is still enabled before attempting to write to it...
4550 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4551 __FUNCTION__, static_cast<void *>(this), GetID());
4552
4554 return {};
4555}
4556
4557// Process Event Data
4558
4560
4562 StateType state)
4563 : EventData(), m_process_wp(), m_state(state) {
4564 if (process_sp)
4565 m_process_wp = process_sp;
4566}
4567
4569
4571 return "Process::ProcessEventData";
4572}
4573
4577
4579 bool &found_valid_stopinfo) {
4580 found_valid_stopinfo = false;
4581
4582 ProcessSP process_sp(m_process_wp.lock());
4583 if (!process_sp)
4584 return false;
4585
4586 ThreadList &curr_thread_list = process_sp->GetThreadList();
4587 uint32_t num_threads = curr_thread_list.GetSize();
4588
4589 // The actions might change one of the thread's stop_info's opinions about
4590 // whether we should stop the process, so we need to query that as we go.
4591
4592 // One other complication here, is that we try to catch any case where the
4593 // target has run (except for expressions) and immediately exit, but if we
4594 // get that wrong (which is possible) then the thread list might have
4595 // changed, and that would cause our iteration here to crash. We could
4596 // make a copy of the thread list, but we'd really like to also know if it
4597 // has changed at all, so we store the original thread ID's of all threads and
4598 // check what we get back against this list & bag out if anything differs.
4599 std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;
4600 for (uint32_t idx = 0; idx < num_threads; ++idx) {
4601 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4602
4603 /*
4604 Filter out all suspended threads, they could not be the reason
4605 of stop and no need to perform any actions on them.
4606 */
4607 if (thread_sp->GetResumeState() != eStateSuspended)
4608 not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());
4609 }
4610
4611 // Use this to track whether we should continue from here. We will only
4612 // continue the target running if no thread says we should stop. Of course
4613 // if some thread's PerformAction actually sets the target running, then it
4614 // doesn't matter what the other threads say...
4615
4616 bool still_should_stop = false;
4617
4618 // Sometimes - for instance if we have a bug in the stub we are talking to,
4619 // we stop but no thread has a valid stop reason. In that case we should
4620 // just stop, because we have no way of telling what the right thing to do
4621 // is, and it's better to let the user decide than continue behind their
4622 // backs.
4623
4624 for (auto [thread_sp, thread_index] : not_suspended_threads) {
4625 if (curr_thread_list.GetSize() != num_threads) {
4627 LLDB_LOGF(
4628 log,
4629 "Number of threads changed from %u to %u while processing event.",
4630 num_threads, curr_thread_list.GetSize());
4631 break;
4632 }
4633
4634 if (thread_sp->GetIndexID() != thread_index) {
4636 LLDB_LOG(log,
4637 "The thread {0} changed from {1} to {2} while processing event.",
4638 thread_sp.get(), thread_index, thread_sp->GetIndexID());
4639 break;
4640 }
4641
4642 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4643 if (stop_info_sp && stop_info_sp->IsValid()) {
4644 found_valid_stopinfo = true;
4645 bool this_thread_wants_to_stop;
4646 if (stop_info_sp->GetOverrideShouldStop()) {
4647 this_thread_wants_to_stop =
4648 stop_info_sp->GetOverriddenShouldStopValue();
4649 } else {
4650 stop_info_sp->PerformAction(event_ptr);
4651 // The stop action might restart the target. If it does, then we
4652 // want to mark that in the event so that whoever is receiving it
4653 // will know to wait for the running event and reflect that state
4654 // appropriately. We also need to stop processing actions, since they
4655 // aren't expecting the target to be running.
4656
4657 // Clear the selected frame which may have been set as part of utility
4658 // expressions that have been run as part of this stop. If we didn't
4659 // clear this, then StopInfo::GetSuggestedStackFrameIndex would not
4660 // take affect when we next called SelectMostRelevantFrame.
4661 // PerformAction should not be the one setting a selected frame, instead
4662 // this should be done via GetSuggestedStackFrameIndex.
4663 thread_sp->ClearSelectedFrameIndex();
4664
4665 // FIXME: we might have run.
4666 if (stop_info_sp->HasTargetRunSinceMe()) {
4667 SetRestarted(true);
4668 break;
4669 }
4670
4671 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4672 }
4673
4674 if (!still_should_stop)
4675 still_should_stop = this_thread_wants_to_stop;
4676 }
4677 }
4678
4679 return still_should_stop;
4680}
4681
4683 Event *event_ptr) {
4684 // STDIO and the other async event notifications should always be forwarded.
4685 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4686 return true;
4687
4688 // For state changed events, if the update state is zero, we are handling
4689 // this on the private state thread. We should wait for the public event.
4690 // After the primary listener processes it in DoOnRemoval, m_update_state
4691 // is incremented from 1 to 2, which is when we forward to pending
4692 // (secondary) listeners.
4693 return m_update_state > 1;
4694}
4695
4697 // We only have work to do for state changed events:
4698 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4699 return;
4700
4701 ProcessSP process_sp(m_process_wp.lock());
4702
4703 if (!process_sp)
4704 return;
4705
4706 // This function gets called twice for each event, once when the event gets
4707 // pulled off of the private process event queue, and then any number of
4708 // times, first when it gets pulled off of the public event queue, then other
4709 // times when we're pretending that this is where we stopped at the end of
4710 // expression evaluation. m_update_state is used to distinguish these
4711 // cases; it is 0 when we're just pulling it off for private handling, 1
4712 // when the primary public listener consumes it, and > 1 after that (e.g.
4713 // secondary listeners or expression evaluation) where we don't want to
4714 // redo the breakpoint command handling or stop hooks.
4715 if (m_update_state != 1)
4716 return;
4718
4719 process_sp->SetPublicState(
4721
4722 if (m_state == eStateStopped && !m_restarted) {
4723 // Let process subclasses know we are about to do a public stop and do
4724 // anything they might need to in order to speed up register and memory
4725 // accesses.
4726 process_sp->WillPublicStop();
4727 }
4728
4729 // If this is a halt event, even if the halt stopped with some reason other
4730 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4731 // the halt request came through) don't do the StopInfo actions, as they may
4732 // end up restarting the process.
4733 if (m_interrupted)
4734 return;
4735
4736 // If we're not stopped or have restarted, then skip the StopInfo actions:
4737 if (m_state != eStateStopped || m_restarted) {
4738 return;
4739 }
4740
4741 bool does_anybody_have_an_opinion = false;
4742 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4743
4744 if (GetRestarted()) {
4745 return;
4746 }
4747
4748 if (!still_should_stop && does_anybody_have_an_opinion) {
4749 // We've been asked to continue, so do that here.
4750 SetRestarted(true);
4751 // Use the private resume method here, since we aren't changing the run
4752 // lock state.
4753 process_sp->PrivateResume();
4754 } else {
4755 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4756 !process_sp->StateChangedIsHijackedForSynchronousResume();
4757
4758 if (!hijacked) {
4759 // If we didn't restart, run the Stop Hooks here.
4760 // Don't do that if state changed events aren't hooked up to the
4761 // public (or SyncResume) broadcasters. StopHooks are just for
4762 // real public stops. They might also restart the target,
4763 // so watch for that.
4764 if (process_sp->GetTarget().RunStopHooks())
4765 SetRestarted(true);
4766 }
4767 }
4768}
4769
4771 ProcessSP process_sp(m_process_wp.lock());
4772
4773 if (process_sp)
4774 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4775 static_cast<void *>(process_sp.get()), process_sp->GetID());
4776 else
4777 s->PutCString(" process = NULL, ");
4778
4779 s->Printf("state = %s", StateAsCString(GetState()));
4780}
4781
4784 if (event_ptr) {
4785 const EventData *event_data = event_ptr->GetData();
4786 if (event_data &&
4788 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4789 }
4790 return nullptr;
4791}
4792
4795 ProcessSP process_sp;
4796 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4797 if (data)
4798 process_sp = data->GetProcessSP();
4799 return process_sp;
4800}
4801
4803 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4804 if (data == nullptr)
4805 return eStateInvalid;
4806 else
4807 return data->GetState();
4808}
4809
4811 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4812 if (data == nullptr)
4813 return false;
4814 else
4815 return data->GetRestarted();
4816}
4817
4819 bool new_value) {
4820 ProcessEventData *data =
4821 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4822 if (data != nullptr)
4823 data->SetRestarted(new_value);
4824}
4825
4826size_t
4828 ProcessEventData *data =
4829 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4830 if (data != nullptr)
4831 return data->GetNumRestartedReasons();
4832 else
4833 return 0;
4834}
4835
4836const char *
4838 size_t idx) {
4839 ProcessEventData *data =
4840 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4841 if (data != nullptr)
4842 return data->GetRestartedReasonAtIndex(idx);
4843 else
4844 return nullptr;
4845}
4846
4848 const char *reason) {
4849 ProcessEventData *data =
4850 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4851 if (data != nullptr)
4852 data->AddRestartedReason(reason);
4853}
4854
4856 const Event *event_ptr) {
4857 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4858 if (data == nullptr)
4859 return false;
4860 else
4861 return data->GetInterrupted();
4862}
4863
4865 bool new_value) {
4866 ProcessEventData *data =
4867 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4868 if (data != nullptr)
4869 data->SetInterrupted(new_value);
4870}
4871
4873 ProcessEventData *data =
4874 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4875 if (data) {
4877 return true;
4878 }
4879 return false;
4880}
4881
4883
4885 exe_ctx.SetTargetPtr(&GetTarget());
4886 exe_ctx.SetProcessPtr(this);
4887 exe_ctx.SetThreadPtr(nullptr);
4888 exe_ctx.SetFramePtr(nullptr);
4889}
4890
4891// uint32_t
4892// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4893// std::vector<lldb::pid_t> &pids)
4894//{
4895// return 0;
4896//}
4897//
4898// ArchSpec
4899// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4900//{
4901// return Host::GetArchSpecForExistingProcess (pid);
4902//}
4903//
4904// ArchSpec
4905// Process::GetArchSpecForExistingProcess (const char *process_name)
4906//{
4907// return Host::GetArchSpecForExistingProcess (process_name);
4908//}
4909
4911 auto event_data_sp =
4912 std::make_shared<ProcessEventData>(shared_from_this(), GetState());
4913 return std::make_shared<Event>(event_type, event_data_sp);
4914}
4915
4916void Process::AppendSTDOUT(const char *s, size_t len) {
4917 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4918 m_stdout_data.append(s, len);
4920 BroadcastEventIfUnique(event_sp);
4921}
4922
4923void Process::AppendSTDERR(const char *s, size_t len) {
4924 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4925 m_stderr_data.append(s, len);
4927 BroadcastEventIfUnique(event_sp);
4928}
4929
4930void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4931 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4932 m_profile_data.push_back(one_profile_data);
4934 BroadcastEventIfUnique(event_sp);
4935}
4936
4938 const StructuredDataPluginSP &plugin_sp) {
4939 auto data_sp = std::make_shared<EventDataStructuredData>(
4940 shared_from_this(), object_sp, plugin_sp);
4942}
4943
4945Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4946 auto find_it = m_structured_data_plugin_map.find(type_name);
4947 if (find_it != m_structured_data_plugin_map.end())
4948 return find_it->second;
4949 else
4950 return StructuredDataPluginSP();
4951}
4952
4953size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4954 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4955 if (m_profile_data.empty())
4956 return 0;
4957
4958 std::string &one_profile_data = m_profile_data.front();
4959 size_t bytes_available = one_profile_data.size();
4960 if (bytes_available > 0) {
4961 Log *log = GetLog(LLDBLog::Process);
4962 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4963 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4964 if (bytes_available > buf_size) {
4965 memcpy(buf, one_profile_data.c_str(), buf_size);
4966 one_profile_data.erase(0, buf_size);
4967 bytes_available = buf_size;
4968 } else {
4969 memcpy(buf, one_profile_data.c_str(), bytes_available);
4970 m_profile_data.erase(m_profile_data.begin());
4971 }
4972 }
4973 return bytes_available;
4974}
4975
4976// Process STDIO
4977
4978size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4979 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4980 size_t bytes_available = m_stdout_data.size();
4981 if (bytes_available > 0) {
4982 Log *log = GetLog(LLDBLog::Process);
4983 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4984 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4985 if (bytes_available > buf_size) {
4986 memcpy(buf, m_stdout_data.c_str(), buf_size);
4987 m_stdout_data.erase(0, buf_size);
4988 bytes_available = buf_size;
4989 } else {
4990 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4991 m_stdout_data.clear();
4992 }
4993 }
4994 return bytes_available;
4995}
4996
4997size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4998 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4999 size_t bytes_available = m_stderr_data.size();
5000 if (bytes_available > 0) {
5001 Log *log = GetLog(LLDBLog::Process);
5002 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
5003 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
5004 if (bytes_available > buf_size) {
5005 memcpy(buf, m_stderr_data.c_str(), buf_size);
5006 m_stderr_data.erase(0, buf_size);
5007 bytes_available = buf_size;
5008 } else {
5009 memcpy(buf, m_stderr_data.c_str(), bytes_available);
5010 m_stderr_data.clear();
5011 }
5012 }
5013 return bytes_available;
5014}
5015
5016void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
5017 size_t src_len) {
5018 Process *process = (Process *)baton;
5019 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
5020}
5021
5022void Process::SetSTDIOFileDescriptor(int fd, std::optional<int> secondary_fd) {
5023 {
5024 auto stdio_secondary_fd = m_stdio_secondary_fd.Lock();
5025 assert(!*stdio_secondary_fd && "process stdio is already set up");
5026 *stdio_secondary_fd = secondary_fd;
5027 }
5028
5029 // First set up the Read Thread for reading/handling process I/O
5030 m_stdio_communication.SetConnection(
5031 std::make_unique<ConnectionFileDescriptor>(fd, true));
5032 if (m_stdio_communication.IsConnected()) {
5033 m_stdio_communication.SetReadThreadBytesReceivedCallback(
5035 m_stdio_communication.StartReadThread();
5036
5037 // Now read thread is set up, set up input reader.
5038 {
5039 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5042 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
5043 }
5044 } else {
5045 // Nobody is going to read the primary side, so there is no point in keeping
5046 // the terminal alive.
5048 }
5049}
5050
5051#if !defined(_WIN32)
5053 // Take a descriptor for the secondary side so it is kept alive.
5054 if (llvm::Error err = pty.OpenSecondary(O_RDWR | O_NOCTTY | O_CLOEXEC))
5055 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), std::move(err),
5056 "failed to open the secondary side of the inferior's "
5057 "terminal: {0}");
5058
5059 std::optional<int> secondary_fd;
5060 if (int fd = pty.ReleaseSecondaryFileDescriptor();
5062 secondary_fd = fd;
5064}
5065#endif
5066
5068 if (drain) {
5069 // Collect everything the inferior has written.
5070 m_stdio_communication.SynchronizeWithReadThread();
5071 }
5072
5073 // Nothing is left to read, so let go of the terminal.
5075
5076 m_stdio_communication.StopReadThread();
5077 m_stdio_communication.Disconnect();
5078 m_stdin_forward = false;
5079}
5080
5082 if (std::optional<int> fd = std::exchange(*m_stdio_secondary_fd.Lock(), {}))
5083 llvm::sys::Process::SafelyCloseFileDescriptor(*fd);
5084}
5085
5087 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5088 IOHandlerSP io_handler_sp(m_process_input_reader);
5089 if (io_handler_sp)
5090 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
5091 return false;
5092}
5093
5095 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5096 IOHandlerSP io_handler_sp(m_process_input_reader);
5097 if (io_handler_sp) {
5098 Log *log = GetLog(LLDBLog::Process);
5099 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
5100
5101 io_handler_sp->SetIsDone(false);
5102 // If we evaluate an utility function, then we don't cancel the current
5103 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
5104 // existing IOHandler that potentially provides the user interface (e.g.
5105 // the IOHandler for Editline).
5106 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
5107 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
5108 cancel_top_handler);
5109 return true;
5110 }
5111 return false;
5112}
5113
5115 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5116 IOHandlerSP io_handler_sp(m_process_input_reader);
5117 if (io_handler_sp)
5118 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
5119 return false;
5120}
5121
5122// The process needs to know about installed plug-ins
5124
5126
5127namespace {
5128// RestorePlanState is used to record the "is private", "is controlling" and
5129// "okay
5130// to discard" fields of the plan we are running, and reset it on Clean or on
5131// destruction. It will only reset the state once, so you can call Clean and
5132// then monkey with the state and it won't get reset on you again.
5133
5134class RestorePlanState {
5135public:
5136 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
5137 : m_thread_plan_sp(thread_plan_sp) {
5138 if (m_thread_plan_sp) {
5139 m_private = m_thread_plan_sp->GetPrivate();
5140 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
5141 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5142 }
5143 }
5144
5145 ~RestorePlanState() { Clean(); }
5146
5147 void Clean() {
5148 if (!m_already_reset && m_thread_plan_sp) {
5149 m_already_reset = true;
5150 m_thread_plan_sp->SetPrivate(m_private);
5151 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
5152 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5153 }
5154 }
5155
5156private:
5157 lldb::ThreadPlanSP m_thread_plan_sp;
5158 bool m_already_reset = false;
5159 bool m_private = false;
5160 bool m_is_controlling = false;
5161 bool m_okay_to_discard = false;
5162};
5163} // anonymous namespace
5164
5165static microseconds
5167 const milliseconds default_one_thread_timeout(250);
5168
5169 // If the overall wait is forever, then we don't need to worry about it.
5170 if (!options.GetTimeout()) {
5171 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
5172 : default_one_thread_timeout;
5173 }
5174
5175 // If the one thread timeout is set, use it.
5176 if (options.GetOneThreadTimeout())
5177 return *options.GetOneThreadTimeout();
5178
5179 // Otherwise use half the total timeout, bounded by the
5180 // default_one_thread_timeout.
5181 return std::min<microseconds>(default_one_thread_timeout,
5182 *options.GetTimeout() / 2);
5183}
5184
5185static Timeout<std::micro>
5187 bool before_first_timeout) {
5188 // If we are going to run all threads the whole time, or if we are only going
5189 // to run one thread, we can just return the overall timeout.
5190 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5191 return options.GetTimeout();
5192
5193 if (before_first_timeout)
5194 return GetOneThreadExpressionTimeout(options);
5195
5196 if (!options.GetTimeout())
5197 return std::nullopt;
5198 else
5199 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
5200}
5201
5202static std::optional<ExpressionResults>
5203HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
5204 RestorePlanState &restorer, const EventSP &event_sp,
5205 EventSP &event_to_broadcast_sp,
5206 const EvaluateExpressionOptions &options,
5207 bool handle_interrupts) {
5209
5210 ThreadSP thread_sp = thread_plan_sp->GetTarget()
5211 .GetProcessSP()
5212 ->GetThreadList()
5213 .FindThreadByID(thread_id);
5214 if (!thread_sp) {
5215 LLDB_LOG(log,
5216 "The thread on which we were running the "
5217 "expression: tid = {0}, exited while "
5218 "the expression was running.",
5219 thread_id);
5221 }
5222
5223 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
5224 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
5225 LLDB_LOG(log, "execution completed successfully");
5226
5227 // Restore the plan state so it will get reported as intended when we are
5228 // done.
5229 restorer.Clean();
5230 return eExpressionCompleted;
5231 }
5232
5233 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5234 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
5235 stop_info_sp->ShouldNotify(event_sp.get())) {
5236 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
5237 if (!options.DoesIgnoreBreakpoints()) {
5238 // Restore the plan state and then force Private to false. We are going
5239 // to stop because of this plan so we need it to become a public plan or
5240 // it won't report correctly when we continue to its termination later
5241 // on.
5242 restorer.Clean();
5243 thread_plan_sp->SetPrivate(false);
5244 event_to_broadcast_sp = event_sp;
5245 }
5247 }
5248
5249 if (!handle_interrupts &&
5251 return std::nullopt;
5252
5253 LLDB_LOG(log, "thread plan did not successfully complete");
5254 if (!options.DoesUnwindOnError())
5255 event_to_broadcast_sp = event_sp;
5257}
5258
5261 lldb::ThreadPlanSP &thread_plan_sp,
5262 const EvaluateExpressionOptions &requested_options,
5263 DiagnosticManager &diagnostic_manager) {
5265
5266 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
5267
5268 if (!thread_plan_sp) {
5269 diagnostic_manager.PutString(
5270 lldb::eSeverityError, "RunThreadPlan called with empty thread plan.");
5271 return eExpressionSetupError;
5272 }
5273
5274 if (!thread_plan_sp->ValidatePlan(nullptr)) {
5275 diagnostic_manager.PutString(
5277 "RunThreadPlan called with an invalid thread plan.");
5278 return eExpressionSetupError;
5279 }
5280
5281 if (exe_ctx.GetProcessPtr() != this) {
5282 diagnostic_manager.PutString(lldb::eSeverityError,
5283 "RunThreadPlan called on wrong process.");
5284 return eExpressionSetupError;
5285 }
5286
5287 Thread *thread = exe_ctx.GetThreadPtr();
5288 if (thread == nullptr) {
5289 diagnostic_manager.PutString(lldb::eSeverityError,
5290 "RunThreadPlan called with invalid thread.");
5291 return eExpressionSetupError;
5292 }
5293
5294 // Record the thread's id so we can tell when a thread we were using
5295 // to run the expression exits during the expression evaluation.
5296 lldb::tid_t expr_thread_id = thread->GetID();
5297
5298 // Clearing stop-others is a request to run the inferior's other threads, and
5299 // it is not the default, so refuse it outright rather than quietly running
5300 // single-threaded. Asking for the all-threads retry is refused the same way,
5301 // since it resumes those same threads a moment later.
5302 EvaluateExpressionOptions options = requested_options;
5303 const Policy policy = PolicyStack::Get().Current();
5304 if (!policy.capabilities.can_run_all_threads) {
5305 if (!options.GetStopOthers()) {
5306 diagnostic_manager.PutString(
5308 "cannot run the process's other threads to evaluate this "
5309 "expression: the current context does not allow resuming them");
5310 return eExpressionSetupError;
5311 }
5312 options.SetTryAllThreads(false);
5313 } else if (!policy.capabilities.can_try_all_threads) {
5314 if (options.GetTryAllThreads()) {
5315 diagnostic_manager.PutString(
5317 "cannot retry this expression with the process's other threads "
5318 "running: the current context does not allow that fallback");
5319 return eExpressionSetupError;
5320 }
5321 }
5322
5323 // We need to change some of the thread plan attributes for the thread plan
5324 // runner. This will restore them when we are done:
5325
5326 RestorePlanState thread_plan_restorer(thread_plan_sp);
5327
5328 // We rely on the thread plan we are running returning "PlanCompleted" if
5329 // when it successfully completes. For that to be true the plan can't be
5330 // private - since private plans suppress themselves in the GetCompletedPlan
5331 // call.
5332
5333 thread_plan_sp->SetPrivate(false);
5334
5335 // The plans run with RunThreadPlan also need to be terminal controlling plans
5336 // or when they are done we will end up asking the plan above us whether we
5337 // should stop, which may give the wrong answer.
5338
5339 thread_plan_sp->SetIsControllingPlan(true);
5340 thread_plan_sp->SetOkayToDiscard(false);
5341
5342 // If we are running some utility expression for LLDB, we now have to mark
5343 // this in the ProcesModID of this process. This RAII takes care of marking
5344 // and reverting the mark it once we are done running the expression.
5345 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
5346
5347 if (GetPrivateState() != eStateStopped) {
5348 diagnostic_manager.PutString(
5350 "RunThreadPlan called while the private state was not stopped.");
5351 return eExpressionSetupError;
5352 }
5353
5354 // Save the thread & frame from the exe_ctx for restoration after we run
5355 const uint32_t thread_idx_id = thread->GetIndexID();
5356 StackFrameSP selected_frame_sp =
5357 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5358 if (!selected_frame_sp) {
5359 thread->SetSelectedFrame(nullptr);
5360 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5361 if (!selected_frame_sp) {
5362 diagnostic_manager.Printf(
5364 "RunThreadPlan called without a selected frame on thread %d",
5365 thread_idx_id);
5366 return eExpressionSetupError;
5367 }
5368 }
5369
5370 // Make sure the timeout values make sense. The one thread timeout needs to
5371 // be smaller than the overall timeout.
5372 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
5373 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
5374 diagnostic_manager.PutString(lldb::eSeverityError,
5375 "RunThreadPlan called with one thread "
5376 "timeout greater than total timeout");
5377 return eExpressionSetupError;
5378 }
5379
5380 // If the ExecutionContext has a frame, we want to make sure to save/restore
5381 // that frame into exe_ctx. This can happen when we run expressions from a
5382 // non-selected SBFrame, in which case we don't want some thread-plan
5383 // to overwrite the ExecutionContext frame.
5384 StackID ctx_frame_id = exe_ctx.HasFrameScope()
5385 ? exe_ctx.GetFrameRef().GetStackID()
5386 : selected_frame_sp->GetStackID();
5387
5388 // N.B. Running the target may unset the currently selected thread and frame.
5389 // We don't want to do that either, so we should arrange to reset them as
5390 // well.
5391
5392 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
5393
5394 uint32_t selected_tid;
5395 StackID selected_stack_id;
5396 if (selected_thread_sp) {
5397 selected_tid = selected_thread_sp->GetIndexID();
5398 selected_stack_id =
5399 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
5400 ->GetStackID();
5401 } else {
5402 selected_tid = LLDB_INVALID_THREAD_ID;
5403 }
5404
5405 std::shared_ptr<PrivateStateThread> backup_private_state_thread;
5406 lldb::StateType old_state = eStateInvalid;
5407 lldb::ThreadPlanSP stopper_base_plan_sp;
5408
5411 // Yikes, we are running on the private state thread! So we can't wait for
5412 // public events on this thread, since we are the thread that is generating
5413 // public events. The simplest thing to do is to spin up a temporary thread
5414 // to handle private state thread events while we are fielding public
5415 // events here.
5416 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
5417 "another state thread to handle the events.");
5418
5419 // One other bit of business: we want to run just this thread plan and
5420 // anything it pushes, and then stop, returning control here. But in the
5421 // normal course of things, the plan above us on the stack would be given a
5422 // shot at the stop event before deciding to stop, and we don't want that.
5423 // So we insert a "stopper" base plan on the stack before the plan we want
5424 // to run. Since base plans always stop and return control to the user,
5425 // that will do just what we want.
5426 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
5427 thread->QueueThreadPlan(stopper_base_plan_sp, false);
5428 // Have to make sure our public state is stopped, since otherwise the
5429 // reporting logic below doesn't work correctly.
5430 old_state = GetPublicState();
5431 m_current_private_state_thread_sp->SetPublicStateNoLock(eStateStopped);
5432
5433 // Now spin up the private state thread:
5434 StartPrivateStateThread(lldb::eStateStopped, /* RunLock is stopped*/ false,
5435 &backup_private_state_thread);
5437 // If we can't spin up a thread here we can't run this expression. But
5438 // presumably the old private state thread is still good, so just put it
5439 // back and return an error.
5440 diagnostic_manager.Printf(
5442 "could not spin up a thread to handle events for an expression"
5443 " run on the private state thread.");
5444 m_current_private_state_thread_sp = backup_private_state_thread;
5445 return eExpressionSetupError;
5446 }
5447 }
5448
5449 thread->QueueThreadPlan(
5450 thread_plan_sp, false); // This used to pass "true" does that make sense?
5451
5452 if (options.GetDebug()) {
5453 // In this case, we aren't actually going to run, we just want to stop
5454 // right away. Flush this thread so we will refetch the stacks and show the
5455 // correct backtrace.
5456 // FIXME: To make this prettier we should invent some stop reason for this,
5457 // but that
5458 // is only cosmetic, and this functionality is only of use to lldb
5459 // developers who can live with not pretty...
5460 thread->Flush();
5462 }
5463
5464 ListenerSP listener_sp(
5465 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5466
5467 lldb::EventSP event_to_broadcast_sp;
5468
5469 {
5470 // This process event hijacker Hijacks the Public events and its destructor
5471 // makes sure that the process events get restored on exit to the function.
5472 //
5473 // If the event needs to propagate beyond the hijacker (e.g., the process
5474 // exits during execution), then the event is put into
5475 // event_to_broadcast_sp for rebroadcasting.
5476
5477 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5478
5479 if (log) {
5480 StreamString s;
5481 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5482 LLDB_LOGF(log,
5483 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5484 " to run thread plan \"%s\".",
5485 thread_idx_id, expr_thread_id, s.GetData());
5486 }
5487
5488 bool got_event;
5489 lldb::EventSP event_sp;
5491
5492 bool before_first_timeout = true; // This is set to false the first time
5493 // that we have to halt the target.
5494 bool do_resume = true;
5495 bool handle_running_event = true;
5496
5497 // This is just for accounting:
5498 uint32_t num_resumes = 0;
5499
5500 // If we are going to run all threads the whole time, or if we are only
5501 // going to run one thread, then we don't need the first timeout. So we
5502 // pretend we are after the first timeout already.
5503 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5504 before_first_timeout = false;
5505
5506 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
5507 options.GetStopOthers(), options.GetTryAllThreads(),
5508 before_first_timeout);
5509
5510 // This isn't going to work if there are unfetched events on the queue. Are
5511 // there cases where we might want to run the remaining events here, and
5512 // then try to call the function? That's probably being too tricky for our
5513 // own good.
5514
5515 Event *other_events = listener_sp->PeekAtNextEvent();
5516 if (other_events != nullptr) {
5517 diagnostic_manager.PutString(
5519 "RunThreadPlan called with pending events on the queue.");
5520 return eExpressionSetupError;
5521 }
5522
5523 // We also need to make sure that the next event is delivered. We might be
5524 // calling a function as part of a thread plan, in which case the last
5525 // delivered event could be the running event, and we don't want event
5526 // coalescing to cause us to lose OUR running event...
5528
5529// This while loop must exit out the bottom, there's cleanup that we need to do
5530// when we are done. So don't call return anywhere within it.
5531
5532#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5533 // It's pretty much impossible to write test cases for things like: One
5534 // thread timeout expires, I go to halt, but the process already stopped on
5535 // the function call stop breakpoint. Turning on this define will make us
5536 // not fetch the first event till after the halt. So if you run a quick
5537 // function, it will have completed, and the completion event will be
5538 // waiting, when you interrupt for halt. The expression evaluation should
5539 // still succeed.
5540 bool miss_first_event = true;
5541#endif
5542 bool pending_stop_on_vfork_done = false;
5543
5544 // If we spawned an override PST, mark the current (original) PST so
5545 // GetStackFrameList returns parent frames during event processing.
5546 std::optional<PolicyStack::Guard> policy_guard;
5547 if (backup_private_state_thread)
5548 policy_guard = PolicyStack::Get().PushPrivateState(
5550
5551 while (true) {
5552 // We usually want to resume the process if we get to the top of the
5553 // loop. The only exception is if we get two running events with no
5554 // intervening stop, which can happen, we will just wait for then next
5555 // stop event.
5556 LLDB_LOGF(log,
5557 "Top of while loop: do_resume: %i handle_running_event: %i "
5558 "before_first_timeout: %i.",
5559 do_resume, handle_running_event, before_first_timeout);
5560
5561 if (do_resume || handle_running_event) {
5562 // Do the initial resume and wait for the running event before going
5563 // further.
5564
5565 if (do_resume) {
5566 num_resumes++;
5567 Status resume_error = PrivateResume();
5568 if (!resume_error.Success()) {
5569 diagnostic_manager.Printf(
5571 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5572 resume_error.AsCString());
5573 return_value = eExpressionSetupError;
5574 break;
5575 }
5576 }
5577
5578 got_event =
5579 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5580 if (!got_event) {
5581 LLDB_LOGF(log,
5582 "Process::RunThreadPlan(): didn't get any event after "
5583 "resume %" PRIu32 ", exiting.",
5584 num_resumes);
5585
5586 diagnostic_manager.Printf(lldb::eSeverityError,
5587 "didn't get any event after resume %" PRIu32
5588 ", exiting.",
5589 num_resumes);
5590 return_value = eExpressionSetupError;
5591 break;
5592 }
5593
5594 stop_state =
5596
5597 if (stop_state != eStateRunning) {
5598 bool restarted = false;
5599
5600 if (stop_state == eStateStopped) {
5602 event_sp.get());
5603 LLDB_LOGF(
5604 log,
5605 "Process::RunThreadPlan(): didn't get running event after "
5606 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5607 "handle_running_event: %i).",
5608 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5609 handle_running_event);
5610 }
5611
5612 if (restarted) {
5613 // This is probably an overabundance of caution, I don't think I
5614 // should ever get a stopped & restarted event here. But if I do,
5615 // the best thing is to Halt and then get out of here.
5616 const bool clear_thread_plans = false;
5617 const bool use_run_lock = false;
5618 Halt(clear_thread_plans, use_run_lock);
5619 }
5620
5621 diagnostic_manager.Printf(lldb::eSeverityError,
5622 "didn't get running event after initial "
5623 "resume, got %s instead.",
5624 StateAsCString(stop_state));
5625 return_value = eExpressionSetupError;
5626 break;
5627 }
5628
5629 if (log)
5630 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5631 // We need to call the function synchronously, so spin waiting for it
5632 // to return. If we get interrupted while executing, we're going to
5633 // lose our context, and won't be able to gather the result at this
5634 // point. We set the timeout AFTER the resume, since the resume takes
5635 // some time and we don't want to charge that to the timeout.
5636 } else {
5637 if (log)
5638 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5639 }
5640
5641 do_resume = true;
5642 handle_running_event = true;
5643
5644 // Now wait for the process to stop again:
5645 event_sp.reset();
5646
5647 Timeout<std::micro> timeout =
5648 GetExpressionTimeout(options, before_first_timeout);
5649 if (log) {
5650 if (timeout) {
5651 auto now = system_clock::now();
5652 LLDB_LOGF(log,
5653 "Process::RunThreadPlan(): about to wait - now is %s - "
5654 "endpoint is %s",
5655 llvm::to_string(now).c_str(),
5656 llvm::to_string(now + *timeout).c_str());
5657 } else {
5658 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
5659 }
5660 }
5661
5662#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5663 // See comment above...
5664 if (miss_first_event) {
5665 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5666 miss_first_event = false;
5667 got_event = false;
5668 } else
5669#endif
5670 got_event = listener_sp->GetEvent(event_sp, timeout);
5671
5672 if (got_event) {
5673 if (event_sp) {
5674 bool keep_going = false;
5675 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5676 const bool clear_thread_plans = false;
5677 const bool use_run_lock = false;
5678 Halt(clear_thread_plans, use_run_lock);
5679 return_value = eExpressionInterrupted;
5680 diagnostic_manager.PutString(lldb::eSeverityInfo,
5681 "execution halted by user interrupt.");
5682 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5683 "eBroadcastBitInterrupted, exiting.");
5684 break;
5685 } else {
5686 stop_state =
5688 LLDB_LOGF(log,
5689 "Process::RunThreadPlan(): in while loop, got event: %s.",
5690 StateAsCString(stop_state));
5691
5692 switch (stop_state) {
5693 case lldb::eStateStopped: {
5695 event_sp.get())) {
5696 // If we were restarted, we just need to go back up to fetch
5697 // another event.
5698 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5699 "restart, so we'll continue waiting.");
5700 keep_going = true;
5701 do_resume = false;
5702 handle_running_event = true;
5703 } else {
5704 // Check for fork/vfork/vforkdone stop reasons. DidFork /
5705 // DidVFork / DidVForkDone have already been called by
5706 // PerformAction (via DoOnRemoval).
5707 bool handled_fork = false;
5708 if (ThreadSP fork_thread_sp =
5709 GetThreadList().FindThreadByID(expr_thread_id)) {
5710 if (StopInfoSP stop_info_sp = fork_thread_sp->GetStopInfo()) {
5711 StopReason reason = stop_info_sp->GetStopReason();
5712 if (reason == eStopReasonFork ||
5713 reason == eStopReasonVFork ||
5714 reason == eStopReasonVForkDone) {
5715 handled_fork = true;
5716 if (reason == eStopReasonFork &&
5717 options.GetStopOnFork()) {
5718 // Fork + stop-on-fork: DidFork already ran via
5719 // PerformAction. Parent breakpoints are unaffected.
5720 LLDB_LOGF(log, "Process::RunThreadPlan(): stopped for "
5721 "fork, stop-on-fork is set.");
5722 return_value = eExpressionInterrupted;
5723 } else if (reason == eStopReasonVFork &&
5724 options.GetStopOnFork()) {
5725 // VFork + stop-on-fork: DidVFork already disabled
5726 // software breakpoints (parent and child share
5727 // address space). Interrupting now would leave the
5728 // user with non-functional breakpoints. Defer the
5729 // stop until vforkdone, when DidVForkDone restores
5730 // breakpoint state.
5731 LLDB_LOGF(log,
5732 "Process::RunThreadPlan(): got vfork with "
5733 "stop-on-fork, deferring stop to "
5734 "vforkdone.");
5735 pending_stop_on_vfork_done = true;
5736 keep_going = true;
5737 do_resume = true;
5738 handle_running_event = true;
5739 } else if (reason == eStopReasonVForkDone &&
5740 pending_stop_on_vfork_done) {
5741 // Deferred vfork stop: the vfork cycle has
5742 // completed. DidVForkDone has re-enabled software
5743 // breakpoints and decremented
5744 // m_vfork_in_progress_count.
5745 LLDB_LOGF(log, "Process::RunThreadPlan(): vfork cycle "
5746 "complete, stop-on-fork is set.");
5747 pending_stop_on_vfork_done = false;
5748 return_value = eExpressionInterrupted;
5749 } else {
5750 LLDB_LOGF(log, "Process::RunThreadPlan(): got fork "
5751 "event, continuing.");
5752 keep_going = true;
5753 do_resume = true;
5754 handle_running_event = true;
5755 }
5756 }
5757 }
5758 }
5759
5760 if (!handled_fork) {
5761 const bool handle_interrupts = true;
5762 return_value = *HandleStoppedEvent(
5763 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5764 event_sp, event_to_broadcast_sp, options,
5765 handle_interrupts);
5766 if (return_value == eExpressionThreadVanished)
5767 keep_going = false;
5768 }
5769 }
5770 } break;
5771
5773 // This shouldn't really happen, but sometimes we do get two
5774 // running events without an intervening stop, and in that case
5775 // we should just go back to waiting for the stop.
5776 do_resume = false;
5777 keep_going = true;
5778 handle_running_event = false;
5779 break;
5780
5781 default:
5782 LLDB_LOGF(log,
5783 "Process::RunThreadPlan(): execution stopped with "
5784 "unexpected state: %s.",
5785 StateAsCString(stop_state));
5786
5787 if (stop_state == eStateExited)
5788 event_to_broadcast_sp = event_sp;
5789
5790 diagnostic_manager.PutString(
5792 "execution stopped with unexpected state.");
5793 return_value = eExpressionInterrupted;
5794 break;
5795 }
5796 }
5797
5798 if (keep_going)
5799 continue;
5800 else
5801 break;
5802 } else {
5803 if (log)
5804 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5805 "the event pointer was null. How odd...");
5806 return_value = eExpressionInterrupted;
5807 break;
5808 }
5809 } else {
5810 // If we didn't get an event that means we've timed out... We will
5811 // interrupt the process here. Depending on what we were asked to do
5812 // we will either exit, or try with all threads running for the same
5813 // timeout.
5814
5815 if (log) {
5816 if (options.GetTryAllThreads()) {
5817 if (before_first_timeout) {
5818 LLDB_LOG(log,
5819 "Running function with one thread timeout timed out.");
5820 } else
5821 LLDB_LOG(log, "Restarting function with all threads enabled and "
5822 "timeout: {0} timed out, abandoning execution.",
5823 timeout);
5824 } else
5825 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5826 "abandoning execution.",
5827 timeout);
5828 }
5829
5830 // It is possible that between the time we issued the Halt, and we get
5831 // around to calling Halt the target could have stopped. That's fine,
5832 // Halt will figure that out and send the appropriate Stopped event.
5833 // BUT it is also possible that we stopped & restarted (e.g. hit a
5834 // signal with "stop" set to false.) In
5835 // that case, we'll get the stopped & restarted event, and we should go
5836 // back to waiting for the Halt's stopped event. That's what this
5837 // while loop does.
5838
5839 bool back_to_top = true;
5840 uint32_t try_halt_again = 0;
5841 bool do_halt = true;
5842 const uint32_t num_retries = 5;
5843 while (try_halt_again < num_retries) {
5844 Status halt_error;
5845 if (do_halt) {
5846 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5847 const bool clear_thread_plans = false;
5848 const bool use_run_lock = false;
5849 Halt(clear_thread_plans, use_run_lock);
5850 }
5851 if (halt_error.Success()) {
5852 if (log)
5853 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5854
5855 got_event =
5856 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5857
5858 if (got_event) {
5859 stop_state =
5861 if (log) {
5862 LLDB_LOGF(log,
5863 "Process::RunThreadPlan(): Stopped with event: %s",
5864 StateAsCString(stop_state));
5865 if (stop_state == lldb::eStateStopped &&
5867 event_sp.get()))
5868 log->PutCString(" Event was the Halt interruption event.");
5869 }
5870
5871 if (stop_state == lldb::eStateStopped) {
5873 event_sp.get())) {
5874 if (log)
5875 log->PutCString("Process::RunThreadPlan(): Went to halt "
5876 "but got a restarted event, there must be "
5877 "an un-restarted stopped event so try "
5878 "again... "
5879 "Exiting wait loop.");
5880 try_halt_again++;
5881 do_halt = false;
5882 continue;
5883 }
5884
5885 // Between the time we initiated the Halt and the time we
5886 // delivered it, the process could have already finished its
5887 // job. Check that here:
5888 const bool handle_interrupts = false;
5889 if (auto result = HandleStoppedEvent(
5890 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5891 event_sp, event_to_broadcast_sp, options,
5892 handle_interrupts)) {
5893 return_value = *result;
5894 back_to_top = false;
5895 break;
5896 }
5897
5898 if (!options.GetTryAllThreads()) {
5899 if (log)
5900 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5901 "was false, we stopped so now we're "
5902 "quitting.");
5903 return_value = eExpressionInterrupted;
5904 back_to_top = false;
5905 break;
5906 }
5907
5908 if (before_first_timeout) {
5909 // Set all the other threads to run, and return to the top of
5910 // the loop, which will continue;
5911 before_first_timeout = false;
5912 thread_plan_sp->SetStopOthers(false);
5913 if (log)
5914 log->PutCString(
5915 "Process::RunThreadPlan(): about to resume.");
5916
5917 back_to_top = true;
5918 break;
5919 } else {
5920 // Running all threads failed, so return Interrupted.
5921 if (log)
5922 log->PutCString("Process::RunThreadPlan(): running all "
5923 "threads timed out.");
5924 return_value = eExpressionInterrupted;
5925 back_to_top = false;
5926 break;
5927 }
5928 }
5929 } else {
5930 if (log)
5931 log->PutCString("Process::RunThreadPlan(): halt said it "
5932 "succeeded, but I got no event. "
5933 "I'm getting out of here passing Interrupted.");
5934 return_value = eExpressionInterrupted;
5935 back_to_top = false;
5936 break;
5937 }
5938 } else {
5939 try_halt_again++;
5940 continue;
5941 }
5942 }
5943
5944 if (!back_to_top || try_halt_again > num_retries)
5945 break;
5946 else
5947 continue;
5948 }
5949 } // END WAIT LOOP
5950
5951 policy_guard.reset();
5952
5953 // If we had to start up a temporary private state thread to run this
5954 // thread plan, shut it down now.
5955 if (backup_private_state_thread &&
5956 backup_private_state_thread->IsJoinable()) {
5958 Status error;
5959 m_current_private_state_thread_sp = backup_private_state_thread;
5960 if (stopper_base_plan_sp) {
5961 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5962 }
5963 if (old_state != eStateInvalid)
5964 m_current_private_state_thread_sp->SetPublicStateNoLock(old_state);
5965 }
5966
5967 // If our thread went away on us, we need to get out of here without
5968 // doing any more work. We don't have to clean up the thread plan, that
5969 // will have happened when the Thread was destroyed.
5970 if (return_value == eExpressionThreadVanished) {
5971 return return_value;
5972 }
5973
5974 if (return_value != eExpressionCompleted && log) {
5975 // Print a backtrace into the log so we can figure out where we are:
5976 StreamString s;
5977 s.PutCString("Thread state after unsuccessful completion: \n");
5978 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX,
5979 /*show_hidden*/ true);
5980 log->PutString(s.GetString());
5981 }
5982 // Restore the thread state if we are going to discard the plan execution.
5983 // There are three cases where this could happen: 1) The execution
5984 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5985 // was true 3) We got some other error, and discard_on_error was true
5986 bool should_unwind = (return_value == eExpressionInterrupted &&
5987 options.DoesUnwindOnError()) ||
5988 (return_value == eExpressionHitBreakpoint &&
5989 options.DoesIgnoreBreakpoints());
5990
5991 if (return_value == eExpressionCompleted || should_unwind) {
5992 thread_plan_sp->RestoreThreadState();
5993 }
5994
5995 // Now do some processing on the results of the run:
5996 if (return_value == eExpressionInterrupted ||
5997 return_value == eExpressionHitBreakpoint) {
5998 if (log) {
5999 StreamString s;
6000 if (event_sp)
6001 event_sp->Dump(&s);
6002 else {
6003 log->PutCString("Process::RunThreadPlan(): Stop event that "
6004 "interrupted us is NULL.");
6005 }
6006
6007 StreamString ts;
6008
6009 const char *event_explanation = nullptr;
6010
6011 do {
6012 if (!event_sp) {
6013 event_explanation = "<no event>";
6014 break;
6015 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
6016 event_explanation = "<user interrupt>";
6017 break;
6018 } else {
6019 const Process::ProcessEventData *event_data =
6021 event_sp.get());
6022
6023 if (!event_data) {
6024 event_explanation = "<no event data>";
6025 break;
6026 }
6027
6028 Process *process = event_data->GetProcessSP().get();
6029
6030 if (!process) {
6031 event_explanation = "<no process>";
6032 break;
6033 }
6034
6035 ThreadList &thread_list = process->GetThreadList();
6036
6037 uint32_t num_threads = thread_list.GetSize();
6038 uint32_t thread_index;
6039
6040 ts.Printf("<%u threads> ", num_threads);
6041
6042 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
6043 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
6044
6045 if (!thread) {
6046 ts.PutCString("<?> ");
6047 continue;
6048 }
6049
6050 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
6051 RegisterContext *register_context =
6052 thread->GetRegisterContext().get();
6053
6054 if (register_context)
6055 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
6056 else
6057 ts.PutCString("[ip unknown] ");
6058
6059 // Show the private stop info here, the public stop info will be
6060 // from the last natural stop.
6061 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
6062 if (stop_info_sp) {
6063 const char *stop_desc = stop_info_sp->GetDescription();
6064 if (stop_desc)
6065 ts.PutCString(stop_desc);
6066 }
6067 ts.PutCString(">");
6068 }
6069
6070 event_explanation = ts.GetData();
6071 }
6072 } while (false);
6073
6074 if (event_explanation)
6075 LLDB_LOGF(log,
6076 "Process::RunThreadPlan(): execution interrupted: %s %s",
6077 s.GetData(), event_explanation);
6078 else
6079 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
6080 s.GetData());
6081 }
6082
6083 if (should_unwind) {
6084 LLDB_LOGF(log,
6085 "Process::RunThreadPlan: ExecutionInterrupted - "
6086 "discarding thread plans up to %p.",
6087 static_cast<void *>(thread_plan_sp.get()));
6088 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6089 } else {
6090 LLDB_LOGF(log,
6091 "Process::RunThreadPlan: ExecutionInterrupted - for "
6092 "plan: %p not discarding.",
6093 static_cast<void *>(thread_plan_sp.get()));
6094 }
6095 } else if (return_value == eExpressionSetupError) {
6096 if (log)
6097 log->PutCString("Process::RunThreadPlan(): execution set up error.");
6098
6099 if (options.DoesUnwindOnError()) {
6100 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6101 }
6102 } else {
6103 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
6104 if (log)
6105 log->PutCString("Process::RunThreadPlan(): thread plan is done");
6106 return_value = eExpressionCompleted;
6107 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
6108 if (log)
6109 log->PutCString(
6110 "Process::RunThreadPlan(): thread plan was discarded");
6111 return_value = eExpressionDiscarded;
6112 } else {
6113 if (log)
6114 log->PutCString(
6115 "Process::RunThreadPlan(): thread plan stopped in mid course");
6116 if (options.DoesUnwindOnError() && thread_plan_sp) {
6117 if (log)
6118 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
6119 "'cause unwind_on_error is set.");
6120 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6121 }
6122 }
6123 }
6124
6125 // Thread we ran the function in may have gone away because we ran the
6126 // target Check that it's still there, and if it is put it back in the
6127 // context. Also restore the frame in the context if it is still present.
6128 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6129 if (thread) {
6130 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
6131 }
6132
6133 // Also restore the current process'es selected frame & thread, since this
6134 // function calling may be done behind the user's back.
6135
6136 if (selected_tid != LLDB_INVALID_THREAD_ID) {
6137 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
6138 selected_stack_id.IsValid()) {
6139 // We were able to restore the selected thread, now restore the frame:
6140 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6141 StackFrameSP old_frame_sp =
6142 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
6143 selected_stack_id);
6144 if (old_frame_sp)
6145 GetThreadList().GetSelectedThread()->SetSelectedFrame(
6146 old_frame_sp.get());
6147 }
6148 }
6149 }
6150
6151 // If the process exited during the run of the thread plan, notify everyone.
6152
6153 if (event_to_broadcast_sp) {
6154 if (log)
6155 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6156 BroadcastEvent(event_to_broadcast_sp);
6157 }
6158
6159 return return_value;
6160}
6161
6162void Process::GetStatus(Stream &strm, bool is_verbose) {
6163 const StateType state = GetState();
6164 if (StateIsStoppedState(state, false)) {
6165 if (state == eStateExited) {
6166 int exit_status = GetExitStatus();
6167 const char *exit_description = GetExitDescription();
6168 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
6169 GetID(), exit_status, exit_status,
6170 exit_description ? exit_description : "");
6171 } else {
6172 if (state == eStateConnected)
6173 strm.PutCString("Connected to remote target.\n");
6174 else {
6175 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
6176 if (auto core_args = GetCoreFileArgs(); core_args && is_verbose)
6177 core_args->Format(strm);
6178 }
6179 }
6180 } else {
6181 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
6182 }
6183}
6184
6186 bool only_threads_with_stop_reason,
6187 uint32_t start_frame, uint32_t num_frames,
6188 uint32_t num_frames_with_source,
6189 bool stop_format) {
6190 size_t num_thread_infos_dumped = 0;
6191
6192 // You can't hold the thread list lock while calling Thread::GetStatus. That
6193 // very well might run code (e.g. if we need it to get return values or
6194 // arguments.) For that to work the process has to be able to acquire it.
6195 // So instead copy the thread ID's, and look them up one by one:
6196
6197 uint32_t num_threads;
6198 std::vector<lldb::tid_t> thread_id_array;
6199 // Scope for thread list locker;
6200 {
6201 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6202 ThreadList &curr_thread_list = GetThreadList();
6203 num_threads = curr_thread_list.GetSize();
6204 uint32_t idx;
6205 thread_id_array.resize(num_threads);
6206 for (idx = 0; idx < num_threads; ++idx)
6207 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
6208 }
6209
6210 for (uint32_t i = 0; i < num_threads; i++) {
6211 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
6212 if (thread_sp) {
6213 if (only_threads_with_stop_reason) {
6214 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
6215 if (!stop_info_sp || !stop_info_sp->ShouldShow())
6216 continue;
6217 }
6218 thread_sp->GetStatus(strm, start_frame, num_frames,
6219 num_frames_with_source, stop_format,
6220 /*show_hidden*/ num_frames <= 1);
6221 ++num_thread_infos_dumped;
6222 } else {
6223 Log *log = GetLog(LLDBLog::Process);
6224 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
6225 " vanished while running Thread::GetStatus.");
6226 }
6227 }
6228 return num_thread_infos_dumped;
6229}
6230
6232 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6233}
6234
6236 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
6237 region.GetByteSize());
6238}
6239
6241 void *baton) {
6242 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
6243}
6244
6246 bool result = true;
6247 while (!m_pre_resume_actions.empty()) {
6248 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6249 m_pre_resume_actions.pop_back();
6250 bool this_result = action.callback(action.baton);
6251 if (result)
6252 result = this_result;
6253 }
6254 return result;
6255}
6256
6258
6260{
6261 PreResumeCallbackAndBaton element(callback, baton);
6262 auto found_iter = llvm::find(m_pre_resume_actions, element);
6263 if (found_iter != m_pre_resume_actions.end())
6264 {
6265 m_pre_resume_actions.erase(found_iter);
6266 }
6267}
6268
6272
6274 m_thread_list.Flush();
6275 m_extended_thread_list.Flush();
6277 m_queue_list.Clear();
6280}
6281
6283 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6284 return AddressableBits::AddressableBitToMask(num_bits_setting);
6285
6286 return m_code_address_mask;
6287}
6288
6290 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6291 return AddressableBits::AddressableBitToMask(num_bits_setting);
6292
6293 return m_data_address_mask;
6294}
6295
6304
6313
6316 "Setting Process code address mask to {0:x}", code_address_mask);
6317 m_code_address_mask = code_address_mask;
6318}
6319
6322 "Setting Process data address mask to {0:x}", data_address_mask);
6323 m_data_address_mask = data_address_mask;
6324}
6325
6328 "Setting Process highmem code address mask to {0:x}",
6329 code_address_mask);
6330 m_highmem_code_address_mask = code_address_mask;
6331}
6332
6335 "Setting Process highmem data address mask to {0:x}",
6336 data_address_mask);
6337 m_highmem_data_address_mask = data_address_mask;
6338}
6339
6341 if (ABISP abi_sp = GetABI())
6342 addr = abi_sp->FixCodeAddress(addr);
6343 return addr;
6344}
6345
6347 if (ABISP abi_sp = GetABI())
6348 addr = abi_sp->FixDataAddress(addr);
6349 return addr;
6350}
6351
6353 if (ABISP abi_sp = GetABI())
6354 addr = abi_sp->FixAnyAddress(addr);
6355 return addr;
6356}
6357
6359 Log *log = GetLog(LLDBLog::Process);
6360 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
6361
6362 Target &target = GetTarget();
6363 target.CleanupProcess();
6364 target.ClearModules(false);
6365 m_dynamic_checkers_up.reset();
6366 m_abi_sp.reset();
6367 m_system_runtime_up.reset();
6368 m_os_up.reset();
6369 m_dyld_up.reset();
6370 m_jit_loaders_up.reset();
6371 m_image_tokens.clear();
6372 // After an exec, the inferior is a new process and these memory regions are
6373 // no longer allocated.
6374 m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);
6375 {
6376 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
6377 m_language_runtimes.clear();
6378 }
6380 m_thread_list.DiscardThreadPlans();
6381 m_memory_cache.Clear(true);
6383 DoDidExec();
6385 // Flush the process (threads and all stack frames) after running
6386 // CompleteAttach() in case the dynamic loader loaded things in new
6387 // locations.
6388 Flush();
6389
6390 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
6391 // let the target know so it can do any cleanup it needs to.
6392 target.DidExec();
6393}
6394
6396 if (address == nullptr) {
6397 error = Status::FromErrorString("Invalid address argument");
6398 return LLDB_INVALID_ADDRESS;
6399 }
6400
6401 addr_t function_addr = LLDB_INVALID_ADDRESS;
6402
6403 addr_t addr = address->GetLoadAddress(&GetTarget());
6404 std::map<addr_t, addr_t>::const_iterator iter =
6406 if (iter != m_resolved_indirect_addresses.end()) {
6407 function_addr = (*iter).second;
6408 } else {
6409 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
6410 const Symbol *symbol = address->CalculateSymbolContextSymbol();
6412 "Unable to call resolver for indirect function %s",
6413 symbol ? symbol->GetName().AsCString(nullptr) : "<UNKNOWN>");
6414 function_addr = LLDB_INVALID_ADDRESS;
6415 } else {
6416 if (ABISP abi_sp = GetABI())
6417 function_addr = abi_sp->FixCodeAddress(function_addr);
6419 std::pair<addr_t, addr_t>(addr, function_addr));
6420 }
6421 }
6422 return function_addr;
6423}
6424
6426 // Inform the system runtime of the modified modules.
6427 SystemRuntime *sys_runtime = GetSystemRuntime();
6428 if (sys_runtime)
6429 sys_runtime->ModulesDidLoad(module_list);
6430
6431 GetJITLoaders().ModulesDidLoad(module_list);
6432
6433 // Give the instrumentation runtimes a chance to be created before informing
6434 // them of the modified modules.
6437 for (auto &runtime : m_instrumentation_runtimes)
6438 runtime.second->ModulesDidLoad(module_list);
6439
6440 // Give the language runtimes a chance to be created before informing them of
6441 // the modified modules.
6442 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
6443 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
6444 runtime->ModulesDidLoad(module_list);
6445 }
6446
6447 // If we don't have an operating system plug-in, try to load one since
6448 // loading shared libraries might cause a new one to try and load
6449 if (!m_os_up)
6451
6452 // Inform the structured-data plugins of the modified modules.
6453 for (auto &pair : m_structured_data_plugin_map) {
6454 if (pair.second)
6455 pair.second->ModulesDidLoad(*this, module_list);
6456 }
6457}
6458
6461 return;
6462 if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())
6463 return;
6464 sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
6465}
6466
6469 return;
6470 if (!sc.module_sp)
6471 return;
6472 LanguageType language = sc.GetLanguage();
6473 if (language == eLanguageTypeUnknown ||
6474 language == lldb::eLanguageTypeAssembly ||
6476 return;
6477 LanguageSet plugins =
6479 if (plugins[language])
6480 return;
6481 sc.module_sp->ReportWarningUnsupportedLanguage(
6482 language, GetTarget().GetDebugger().GetID());
6483}
6484
6486 info.Clear();
6487
6488 PlatformSP platform_sp = GetTarget().GetPlatform();
6489 if (!platform_sp)
6490 return false;
6491
6492 return platform_sp->GetProcessInfo(GetID(), info);
6493}
6494
6496 return spec.GetUUID().IsValid();
6497}
6498
6500 ThreadCollectionSP threads;
6501
6502 const MemoryHistorySP &memory_history =
6503 MemoryHistory::FindPlugin(shared_from_this());
6504
6505 if (!memory_history) {
6506 return threads;
6507 }
6508
6509 threads = std::make_shared<ThreadCollection>(
6510 memory_history->GetHistoryThreads(addr));
6511
6512 return threads;
6513}
6514
6517 InstrumentationRuntimeCollection::iterator pos;
6518 pos = m_instrumentation_runtimes.find(type);
6519 if (pos == m_instrumentation_runtimes.end()) {
6520 return InstrumentationRuntimeSP();
6521 } else
6522 return (*pos).second;
6523}
6524
6525bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6526 const ArchSpec &arch, ModuleSpec &module_spec) {
6527 module_spec.Clear();
6528 return false;
6529}
6530
6532 m_image_tokens.push_back(image_ptr);
6533 return m_image_tokens.size() - 1;
6534}
6535
6537 if (token < m_image_tokens.size())
6538 return m_image_tokens[token];
6539 return LLDB_INVALID_ADDRESS;
6540}
6541
6542void Process::ResetImageToken(size_t token) {
6543 if (token < m_image_tokens.size())
6545}
6546
6547Address
6549 AddressRange range_bounds) {
6550 Target &target = GetTarget();
6551 DisassemblerSP disassembler_sp;
6552 InstructionList *insn_list = nullptr;
6553
6554 Address retval = default_stop_addr;
6555
6556 if (!target.GetUseFastStepping())
6557 return retval;
6558 if (!default_stop_addr.IsValid())
6559 return retval;
6560
6561 const char *plugin_name = nullptr;
6562 const char *flavor = nullptr;
6563 const char *cpu = nullptr;
6564 const char *features = nullptr;
6565 disassembler_sp = Disassembler::DisassembleRange(
6566 target.GetArchitecture(), plugin_name, flavor, cpu, features, GetTarget(),
6567 range_bounds);
6568 if (disassembler_sp)
6569 insn_list = &disassembler_sp->GetInstructionList();
6570
6571 if (insn_list == nullptr) {
6572 return retval;
6573 }
6574
6575 size_t insn_offset =
6576 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6577 if (insn_offset == UINT32_MAX) {
6578 return retval;
6579 }
6580
6581 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
6582 insn_offset, false /* ignore_calls*/, nullptr);
6583 if (branch_index == UINT32_MAX) {
6584 return retval;
6585 }
6586
6587 if (branch_index > insn_offset) {
6588 Address next_branch_insn_address =
6589 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6590 if (next_branch_insn_address.IsValid() &&
6591 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6592 retval = next_branch_insn_address;
6593 }
6594 }
6595
6596 return retval;
6597}
6598
6600 MemoryRegionInfo &range_info) {
6601 if (const lldb::ABISP &abi = GetABI())
6602 load_addr = abi->FixAnyAddress(load_addr);
6603
6604 std::optional<MemoryRegionInfo> cached_region =
6605 m_memory_region_infos_cache.GetMemoryRegion(load_addr);
6606 if (cached_region) {
6607 range_info = *cached_region;
6608 return Status();
6609 }
6610
6611 Status error = DoGetMemoryRegionInfo(load_addr, range_info);
6612 if (error.Success()) {
6613 // Reject a region that does not contain the requested address.
6614 if (!range_info.GetRange().Contains(load_addr))
6615 error = Status::FromErrorString("Invalid memory region");
6616 else
6617 m_memory_region_infos_cache.AddRegion(range_info);
6618 }
6619
6620 return error;
6621}
6622
6624 Status error;
6625
6626 lldb::addr_t range_end = 0;
6627 const lldb::ABISP &abi = GetABI();
6628
6629 region_list.clear();
6630 do {
6632 error = GetMemoryRegionInfo(range_end, region_info);
6633 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6634 if (error.Fail()) {
6635 region_list.clear();
6636 break;
6637 }
6638
6639 // We only check the end address, not start and end, because we assume that
6640 // the start will not have non-address bits until the first unmappable
6641 // region. We will have exited the loop by that point because the previous
6642 // region, the last mappable region, will have non-address bits in its end
6643 // address.
6644 range_end = region_info.GetRange().GetRangeEnd();
6645 if (region_info.GetMapped() == eLazyBoolYes) {
6646 region_list.push_back(std::move(region_info));
6647 }
6648 } while (
6649 // For a process with no non-address bits, all address bits
6650 // set means the end of memory.
6651 range_end != LLDB_INVALID_ADDRESS &&
6652 // If we have non-address bits and some are set then the end
6653 // is at or beyond the end of mappable memory.
6654 !(abi && (abi->FixAnyAddress(range_end) != range_end)));
6655
6656 return error;
6657}
6658
6659Status
6660Process::ConfigureStructuredData(llvm::StringRef type_name,
6661 const StructuredData::ObjectSP &config_sp) {
6662 // If you get this, the Process-derived class needs to implement a method to
6663 // enable an already-reported asynchronous structured data feature. See
6664 // ProcessGDBRemote for an example implementation over gdb-remote.
6665 return Status::FromErrorString("unimplemented");
6666}
6667
6669 const StructuredData::Array &supported_type_names) {
6670 Log *log = GetLog(LLDBLog::Process);
6671
6672 // Bail out early if there are no type names to map.
6673 if (supported_type_names.GetSize() == 0) {
6674 LLDB_LOG(log, "no structured data types supported");
6675 return;
6676 }
6677
6678 // These StringRefs are backed by the input parameter.
6679 std::set<llvm::StringRef> type_names;
6680
6681 LLDB_LOG(log,
6682 "the process supports the following async structured data types:");
6683
6684 supported_type_names.ForEach(
6685 [&type_names, &log](StructuredData::Object *object) {
6686 // There shouldn't be null objects in the array.
6687 if (!object)
6688 return false;
6689
6690 // All type names should be strings.
6691 const llvm::StringRef type_name = object->GetStringValue();
6692 if (type_name.empty())
6693 return false;
6694
6695 type_names.insert(type_name);
6696 LLDB_LOG(log, "- {0}", type_name);
6697 return true;
6698 });
6699
6700 // For each StructuredDataPlugin, if the plugin handles any of the types in
6701 // the supported_type_names, map that type name to that plugin. Stop when
6702 // we've consumed all the type names.
6703 // FIXME: should we return an error if there are type names nobody
6704 // supports?
6706 if (type_names.empty())
6707 break;
6708
6709 // Create the plugin.
6710 StructuredDataPluginSP plugin_sp = (*cbs.create_callback)(*this);
6711 if (!plugin_sp) {
6712 // This plugin doesn't think it can work with the process. Move on to the
6713 // next.
6714 continue;
6715 }
6716
6717 // For any of the remaining type names, map any that this plugin supports.
6718 std::vector<llvm::StringRef> names_to_remove;
6719 for (llvm::StringRef type_name : type_names) {
6720 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6722 std::make_pair(type_name, plugin_sp));
6723 names_to_remove.push_back(type_name);
6724 LLDB_LOG(log, "using plugin {0} for type name {1}",
6725 plugin_sp->GetPluginName(), type_name);
6726 }
6727 }
6728
6729 // Remove the type names that were consumed by this plugin.
6730 for (llvm::StringRef type_name : names_to_remove)
6731 type_names.erase(type_name);
6732 }
6733}
6734
6736 const StructuredData::ObjectSP object_sp) {
6737 // Nothing to do if there's no data.
6738 if (!object_sp)
6739 return false;
6740
6741 // The contract is this must be a dictionary, so we can look up the routing
6742 // key via the top-level 'type' string value within the dictionary.
6743 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6744 if (!dictionary)
6745 return false;
6746
6747 // Grab the async structured type name (i.e. the feature/plugin name).
6748 llvm::StringRef type_name;
6749 if (!dictionary->GetValueForKeyAsString("type", type_name))
6750 return false;
6751
6752 // Check if there's a plugin registered for this type name.
6753 auto find_it = m_structured_data_plugin_map.find(type_name);
6754 if (find_it == m_structured_data_plugin_map.end()) {
6755 // We don't have a mapping for this structured data type.
6756 return false;
6757 }
6758
6759 // Route the structured data to the plugin.
6760 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6761 return true;
6762}
6763
6765 // Default implementation does nothign.
6766 // No automatic signal filtering to speak of.
6767 return Status();
6768}
6769
6770llvm::Expected<UtilityFunction &> Process::GetLoadImageUtilityFunction(
6771 Platform *platform,
6772 llvm::function_ref<llvm::Expected<std::unique_ptr<UtilityFunction>>()>
6773 factory) {
6774 if (platform != GetTarget().GetPlatform().get())
6775 return llvm::createStringError(
6776 "the platform requesting the load-image utility function is not "
6777 "the target's platform");
6778 llvm::call_once(m_dlopen_utility_func_flag_once, [&] {
6779 llvm::Expected<std::unique_ptr<UtilityFunction>> factory_result = factory();
6780 if (factory_result)
6781 m_dlopen_utility_func_up = std::move(*factory_result);
6782 else
6784 Status::FromError(factory_result.takeError());
6785 });
6788 return m_dlopen_utility_func_error.ToError();
6789}
6790
6791llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6792 if (!IsLiveDebugSession())
6793 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6794 "Can't trace a non-live process.");
6795 return llvm::make_error<UnimplementedError>();
6796}
6797
6799 addr_t &returned_func,
6800 bool trap_exceptions) {
6802 if (thread == nullptr || address == nullptr)
6803 return false;
6804
6806 options.SetStopOthers(true);
6807 options.SetUnwindOnError(true);
6808 options.SetIgnoreBreakpoints(true);
6809 options.SetTryAllThreads(true);
6810 options.SetDebug(false);
6812 options.SetTrapExceptions(trap_exceptions);
6813
6814 auto type_system_or_err =
6816 if (!type_system_or_err) {
6817 llvm::consumeError(type_system_or_err.takeError());
6818 return false;
6819 }
6820 auto ts = *type_system_or_err;
6821 if (!ts)
6822 return false;
6823 CompilerType void_ptr_type =
6826 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6827 if (call_plan_sp) {
6828 DiagnosticManager diagnostics;
6829
6830 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6831 if (frame) {
6832 ExecutionContext exe_ctx;
6833 frame->CalculateExecutionContext(exe_ctx);
6834 ExpressionResults result =
6835 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6836 if (result == eExpressionCompleted) {
6837 returned_func =
6838 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6840
6841 if (GetAddressByteSize() == 4) {
6842 if (returned_func == UINT32_MAX)
6843 return false;
6844 } else if (GetAddressByteSize() == 8) {
6845 if (returned_func == UINT64_MAX)
6846 return false;
6847 }
6848 return true;
6849 }
6850 }
6851 }
6852
6853 return false;
6854}
6855
6856llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6858 const MemoryTagManager *tag_manager =
6859 arch ? arch->GetMemoryTagManager() : nullptr;
6860 if (!arch || !tag_manager) {
6861 return llvm::createStringError(
6862 llvm::inconvertibleErrorCode(),
6863 "This architecture does not support memory tagging");
6864 }
6865
6866 if (!SupportsMemoryTagging()) {
6867 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6868 "Process does not support memory tagging");
6869 }
6870
6871 return tag_manager;
6872}
6873
6874llvm::Expected<std::vector<lldb::addr_t>>
6876 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6878 if (!tag_manager_or_err)
6879 return tag_manager_or_err.takeError();
6880
6881 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6882 llvm::Expected<std::vector<uint8_t>> tag_data =
6883 DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6884 if (!tag_data)
6885 return tag_data.takeError();
6886
6887 return tag_manager->UnpackTagsData(*tag_data,
6888 len / tag_manager->GetGranuleSize());
6889}
6890
6892 const std::vector<lldb::addr_t> &tags) {
6893 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6895 if (!tag_manager_or_err)
6896 return Status::FromError(tag_manager_or_err.takeError());
6897
6898 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6899 llvm::Expected<std::vector<uint8_t>> packed_tags =
6900 tag_manager->PackTags(tags);
6901 if (!packed_tags) {
6902 return Status::FromError(packed_tags.takeError());
6903 }
6904
6905 return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6906 *packed_tags);
6907}
6908
6909// Create a CoreFileMemoryRange from a MemoryRegionInfo
6912 const addr_t addr = region.GetRange().GetRangeBase();
6913 llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());
6914 return {range, region.GetLLDBPermissions()};
6915}
6916
6917// Add dirty pages to the core file ranges and return true if dirty pages
6918// were added. Return false if the dirty page information is not valid or in
6919// the region.
6921 CoreFileMemoryRanges &ranges) {
6922 const auto &dirty_page_list = region.GetDirtyPageList();
6923 if (!dirty_page_list)
6924 return false;
6925 const uint32_t lldb_permissions = region.GetLLDBPermissions();
6926 const addr_t page_size = region.GetPageSize();
6927 if (page_size == 0)
6928 return false;
6929 llvm::AddressRange range(0, 0);
6930 for (addr_t page_addr : *dirty_page_list) {
6931 if (range.empty()) {
6932 // No range yet, initialize the range with the current dirty page.
6933 range = llvm::AddressRange(page_addr, page_addr + page_size);
6934 } else {
6935 if (range.end() == page_addr) {
6936 // Combine consective ranges.
6937 range = llvm::AddressRange(range.start(), page_addr + page_size);
6938 } else {
6939 // Add previous contiguous range and init the new range with the
6940 // current dirty page.
6941 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6942 range = llvm::AddressRange(page_addr, page_addr + page_size);
6943 }
6944 }
6945 }
6946 // The last range
6947 if (!range.empty())
6948 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6949 return true;
6950}
6951
6952// Given a region, add the region to \a ranges.
6953//
6954// Only add the region if it isn't empty and if it has some permissions.
6955// If \a try_dirty_pages is true, then try to add only the dirty pages for a
6956// given region. If the region has dirty page information, only dirty pages
6957// will be added to \a ranges, else the entire range will be added to \a
6958// ranges.
6960 bool try_dirty_pages, CoreFileMemoryRanges &ranges) {
6961 // Don't add empty ranges.
6962 if (region.GetRange().GetByteSize() == 0)
6963 return;
6964 // Don't add ranges with no read permissions.
6965 if ((region.GetLLDBPermissions() & lldb::ePermissionsReadable) == 0)
6966 return;
6967 if (try_dirty_pages && AddDirtyPages(region, ranges))
6968 return;
6969
6970 ranges.Append(region.GetRange().GetRangeBase(),
6971 region.GetRange().GetByteSize(),
6973}
6974
6976 const SaveCoreOptions &options,
6977 CoreFileMemoryRanges &ranges,
6978 std::set<addr_t> &stack_ends) {
6979 DynamicLoader *dyld = process.GetDynamicLoader();
6980 if (!dyld)
6981 return;
6982
6983 std::vector<lldb_private::MemoryRegionInfo> dynamic_loader_mem_regions;
6984 std::function<bool(const lldb_private::Thread &)> save_thread_predicate =
6985 [&](const lldb_private::Thread &t) -> bool {
6986 return options.ShouldThreadBeSaved(t.GetID());
6987 };
6988 dyld->CalculateDynamicSaveCoreRanges(process, dynamic_loader_mem_regions,
6989 save_thread_predicate);
6990 for (const auto &region : dynamic_loader_mem_regions) {
6991 // The Dynamic Loader can give us regions that could include a truncated
6992 // stack
6993 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
6994 AddRegion(region, true, ranges);
6995 }
6996}
6997
6999 const SaveCoreOptions &core_options,
7000 const MemoryRegionInfos &regions,
7001 CoreFileMemoryRanges &ranges,
7002 std::set<addr_t> &stack_ends) {
7003 const bool try_dirty_pages = true;
7004
7005 // Before we take any dump, we want to save off the used portions of the
7006 // stacks and mark those memory regions as saved. This prevents us from saving
7007 // the unused portion of the stack below the stack pointer. Saving space on
7008 // the dump.
7009 for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {
7010 if (!thread_sp)
7011 continue;
7012 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
7013 if (!frame_sp)
7014 continue;
7015 RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();
7016 if (!reg_ctx_sp)
7017 continue;
7018 const addr_t sp = reg_ctx_sp->GetSP();
7019 const size_t red_zone = process.GetABI()->GetRedZoneSize();
7021 if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {
7022 const size_t stack_head = (sp - red_zone);
7023 const size_t stack_size = sp_region.GetRange().GetRangeEnd() - stack_head;
7024 // Even if the SaveCoreOption doesn't want us to save the stack
7025 // we still need to populate the stack_ends set so it doesn't get saved
7026 // off in other calls
7027 sp_region.GetRange().SetRangeBase(stack_head);
7028 sp_region.GetRange().SetByteSize(stack_size);
7029 const addr_t range_end = sp_region.GetRange().GetRangeEnd();
7030 stack_ends.insert(range_end);
7031 // This will return true if the threadlist the user specified is empty,
7032 // or contains the thread id from thread_sp.
7033 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
7034 AddRegion(sp_region, try_dirty_pages, ranges);
7035 }
7036 }
7037 }
7038}
7039
7040// Save all memory regions that are not empty or have at least some permissions
7041// for a full core file style.
7043 const MemoryRegionInfos &regions,
7044 CoreFileMemoryRanges &ranges,
7045 std::set<addr_t> &stack_ends) {
7046
7047 // Don't add only dirty pages, add full regions.
7048 const bool try_dirty_pages = false;
7049 for (const auto &region : regions)
7050 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
7051 AddRegion(region, try_dirty_pages, ranges);
7052}
7053
7054// Save only the dirty pages to the core file. Make sure the process has at
7055// least some dirty pages, as some OS versions don't support reporting what
7056// pages are dirty within an memory region. If no memory regions have dirty
7057// page information fall back to saving out all ranges with write permissions.
7059 const MemoryRegionInfos &regions,
7060 CoreFileMemoryRanges &ranges,
7061 std::set<addr_t> &stack_ends) {
7062
7063 // Iterate over the regions and find all dirty pages.
7064 bool have_dirty_page_info = false;
7065 for (const auto &region : regions) {
7066 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7067 AddDirtyPages(region, ranges))
7068 have_dirty_page_info = true;
7069 }
7070
7071 if (!have_dirty_page_info) {
7072 // We didn't find support for reporting dirty pages from the process
7073 // plug-in so fall back to any region with write access permissions.
7074 const bool try_dirty_pages = false;
7075 for (const auto &region : regions)
7076 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7077 region.GetWritable() == eLazyBoolYes)
7078 AddRegion(region, try_dirty_pages, ranges);
7079 }
7080}
7081
7082// Save all thread stacks to the core file. Some OS versions support reporting
7083// when a memory region is stack related. We check on this information, but we
7084// also use the stack pointers of each thread and add those in case the OS
7085// doesn't support reporting stack memory. This function also attempts to only
7086// emit dirty pages from the stack if the memory regions support reporting
7087// dirty regions as this will make the core file smaller. If the process
7088// doesn't support dirty regions, then it will fall back to adding the full
7089// stack region.
7091 const MemoryRegionInfos &regions,
7092 CoreFileMemoryRanges &ranges,
7093 std::set<addr_t> &stack_ends) {
7094 const bool try_dirty_pages = true;
7095 // Some platforms support annotating the region information that tell us that
7096 // it comes from a thread stack. So look for those regions first.
7097
7098 for (const auto &region : regions) {
7099 // Save all the stack memory ranges not associated with a stack pointer.
7100 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7101 region.IsStackMemory() == eLazyBoolYes)
7102 AddRegion(region, try_dirty_pages, ranges);
7103 }
7104}
7105
7106// TODO: We should refactor CoreFileMemoryRanges to use the lldb range type, and
7107// then add an intersect method on it, or MemoryRegionInfo.
7108static lldb_private::MemoryRegionInfo
7111
7113 region_info.SetLLDBPermissions(lhs.GetLLDBPermissions());
7114 region_info.GetRange() = lhs.GetRange().Intersect(rhs);
7115
7116 return region_info;
7117}
7118
7120 const MemoryRegionInfos &regions,
7121 const SaveCoreOptions &options,
7122 CoreFileMemoryRanges &ranges) {
7123 const auto &option_ranges = options.GetCoreFileMemoryRanges();
7124 if (option_ranges.IsEmpty())
7125 return;
7126
7127 for (const auto &range : regions) {
7128 auto *entry = option_ranges.FindEntryThatIntersects(range.GetRange());
7129 if (entry) {
7130 if (*entry != range.GetRange()) {
7131 AddRegion(Intersect(range, *entry), true, ranges);
7132 } else {
7133 // If they match, add the range directly.
7134 AddRegion(range, true, ranges);
7135 }
7136 }
7137 }
7138}
7139
7141 CoreFileMemoryRanges &ranges) {
7143 Status err = GetMemoryRegions(regions);
7144 SaveCoreStyle core_style = options.GetStyle();
7145 if (err.Fail())
7146 return err;
7147 if (regions.empty())
7149 "failed to get any valid memory regions from the process");
7150 if (core_style == eSaveCoreUnspecified)
7152 "callers must set the core_style to something other than "
7153 "eSaveCoreUnspecified");
7154
7155 GetUserSpecifiedCoreFileSaveRanges(*this, regions, options, ranges);
7156
7157 std::set<addr_t> stack_ends;
7158 // For fully custom set ups, we don't want to even look at threads if there
7159 // are no threads specified.
7160 if (core_style != lldb::eSaveCoreCustomOnly ||
7161 options.HasSpecifiedThreads()) {
7162 SaveOffRegionsWithStackPointers(*this, options, regions, ranges,
7163 stack_ends);
7164 // Save off the dynamic loader sections, so if we are on an architecture
7165 // that supports Thread Locals, that we include those as well.
7166 SaveDynamicLoaderSections(*this, options, ranges, stack_ends);
7167 }
7168
7169 switch (core_style) {
7172 break;
7173
7174 case eSaveCoreFull:
7175 GetCoreFileSaveRangesFull(*this, regions, ranges, stack_ends);
7176 break;
7177
7178 case eSaveCoreDirtyOnly:
7179 GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges, stack_ends);
7180 break;
7181
7182 case eSaveCoreStackOnly:
7183 GetCoreFileSaveRangesStackOnly(*this, regions, ranges, stack_ends);
7184 break;
7185 }
7186
7187 if (err.Fail())
7188 return err;
7189
7190 if (ranges.IsEmpty())
7192 "no valid address ranges found for core style");
7193
7194 return ranges.FinalizeCoreFileSaveRanges();
7195}
7196
7197std::vector<ThreadSP>
7199 std::vector<ThreadSP> thread_list;
7200 for (const lldb::ThreadSP &thread_sp : m_thread_list.Threads()) {
7201 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
7202 thread_list.push_back(thread_sp);
7203 }
7204 }
7205
7206 return thread_list;
7207}
7208
7210 uint32_t low_memory_addr_bits = bit_masks.GetLowmemAddressableBits();
7211 uint32_t high_memory_addr_bits = bit_masks.GetHighmemAddressableBits();
7212
7213 if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)
7214 return;
7215
7216 if (low_memory_addr_bits != 0) {
7217 addr_t low_addr_mask =
7218 AddressableBits::AddressableBitToMask(low_memory_addr_bits);
7219 SetCodeAddressMask(low_addr_mask);
7220 SetDataAddressMask(low_addr_mask);
7221 }
7222
7223 if (high_memory_addr_bits != 0) {
7224 addr_t high_addr_mask =
7225 AddressableBits::AddressableBitToMask(high_memory_addr_bits);
7226 SetHighmemCodeAddressMask(high_addr_mask);
7227 SetHighmemDataAddressMask(high_addr_mask);
7228 }
7229}
7230
7231llvm::Expected<AddressSpaceInfo>
7232Process::GetAddressSpaceInfo(llvm::StringRef address_space_name) {
7233 if (m_address_spaces.empty())
7234 return llvm::createStringError("process doesn't support address spaces");
7235
7236 for (const AddressSpaceInfo &info : m_address_spaces) {
7237 if (address_space_name == info.name)
7238 return info;
7239 }
7240
7241 std::string names = llvm::join(
7242 llvm::map_range(m_address_spaces,
7243 [](const AddressSpaceInfo &info) { return info.name; }),
7244 ", ");
7245 return llvm::createStringError(
7246 "invalid address space \"%s\", expected one of: %s",
7247 address_space_name.str().c_str(), names.c_str());
7248}
7249
7250llvm::Expected<AddressSpaceInfo>
7252 if (m_address_spaces.empty())
7253 return llvm::createStringError("process doesn't support address spaces");
7254
7255 for (const AddressSpaceInfo &info : m_address_spaces) {
7256 if (info.space_id == address_space_id)
7257 return info;
7258 }
7259
7260 std::string ids =
7261 llvm::join(llvm::map_range(m_address_spaces,
7262 [](const AddressSpaceInfo &info) {
7263 return std::to_string(info.space_id);
7264 }),
7265 ", ");
7266 return llvm::createStringError("invalid address space id %" PRIu64
7267 ", expected one of: %s",
7268 address_space_id, ids.c_str());
7269}
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:7042
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:5203
static void SaveDynamicLoaderSections(Process &process, const SaveCoreOptions &options, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6975
static CoreFileMemoryRange CreateCoreFileMemoryRange(const lldb_private::MemoryRegionInfo &region)
Definition Process.cpp:6911
static constexpr unsigned g_string_read_width
Definition Process.cpp:137
static bool AddDirtyPages(const lldb_private::MemoryRegionInfo &region, CoreFileMemoryRanges &ranges)
Definition Process.cpp:6920
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:7119
static void GetCoreFileSaveRangesDirtyOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:7058
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:6959
static Timeout< std::micro > GetExpressionTimeout(const EvaluateExpressionOptions &options, bool before_first_timeout)
Definition Process.cpp:5186
static microseconds GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options)
Definition Process.cpp:5166
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:7109
static void SaveOffRegionsWithStackPointers(Process &process, const SaveCoreOptions &core_options, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6998
static void GetCoreFileSaveRangesStackOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:7090
#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:103
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:223
bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp)
bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp)
Remove the given IO handler if it's currently active.
void FlushStatusLine()
Discard the statusline's cached frame at its next redraw.
void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, bool cancel_top_handler=true)
Run the given IO handler and return immediately.
PlatformList & GetPlatformList()
Definition Debugger.h:227
lldb::ListenerSP GetListener()
Definition Debugger.h:194
size_t void PutString(lldb::Severity severity, llvm::StringRef str)
size_t Printf(lldb::Severity severity, const char *format,...) __attribute__((format(printf
static lldb::DisassemblerSP DisassembleRange(const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, Target &target, llvm::ArrayRef< AddressRange > disasm_ranges, bool force_live_memory=false)
Encapsulates dynamic check functions used by expressions.
A plug-in interface definition class for dynamic loaders.
virtual void DidAttach()=0
Called after attaching a process.
virtual void CalculateDynamicSaveCoreRanges(lldb_private::Process &process, std::vector< lldb_private::MemoryRegionInfo > &ranges, llvm::function_ref< bool(const lldb_private::Thread &)> save_thread_predicate)
Returns a list of memory ranges that should be saved in the core file, specific for this dynamic load...
virtual void DidLaunch()=0
Called after launching a process.
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
void SetUnwindOnError(bool unwind=false)
Definition Target.h:410
void SetTryAllThreads(bool try_others=true)
Definition Target.h:443
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:431
void SetStopOthers(bool stop_others=true)
Definition Target.h:447
const Timeout< std::micro > & GetTimeout() const
Definition Target.h:429
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:414
const Timeout< std::micro > & GetOneThreadTimeout() const
Definition Target.h:433
friend class Event
Definition Event.h:36
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition Event.h:199
uint32_t GetType() const
Definition Event.h:205
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void SetFrameSP(const lldb::StackFrameSP &frame_sp)
Set accessor to set only the frame shared pointer.
void SetProcessPtr(Process *process)
Set accessor to set only the process shared pointer from a process pointer.
void SetThreadPtr(Thread *thread)
Set accessor to set only the thread shared pointer from a thread pointer.
void SetTargetPtr(Target *target)
Set accessor to set only the target shared pointer from a target pointer.
StackFrame & GetFrameRef() const
Returns a reference to the thread object.
bool HasFrameScope() const
Returns true the ExecutionContext object contains a valid target, process, thread and frame.
void SetFramePtr(StackFrame *frame)
Set accessor to set only the frame shared pointer from a frame pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
static FileSystem & Instance()
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
bool GetIsOptimized()
Get whether compiler optimizations were enabled for this function.
Definition Function.cpp:526
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
uint32_t GetIndexOfInstructionAtAddress(const Address &addr)
lldb::InstructionSP GetInstructionAtIndex(size_t idx) const
uint32_t GetIndexOfNextBranchInstruction(uint32_t start, bool ignore_calls, bool *found_calls) const
Get the index of the next branch instruction.
static void ModulesDidLoad(lldb_private::ModuleList &module_list, Process *process, InstrumentationRuntimeCollection &runtimes)
Class used by the Process to hold a list of its JITLoaders.
void ModulesDidLoad(ModuleList &module_list)
static void LoadPlugins(Process *process, lldb_private::JITLoaderList &list)
Find a JIT loader plugin for a given process.
Definition JITLoader.cpp:18
virtual lldb::LanguageType GetLanguageType() const =0
static LanguageRuntime * FindPlugin(Process *process, lldb::LanguageType language)
virtual bool CouldHaveDynamicValue(ValueObject &in_value)=0
static lldb::LanguageType GetPrimaryLanguage(lldb::LanguageType language)
Definition Language.cpp:451
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition Language.cpp:501
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:4810
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
Definition Process.cpp:4578
static void AddRestartedReason(Event *event_ptr, const char *reason)
Definition Process.cpp:4847
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:4818
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4794
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4864
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:4682
llvm::StringRef GetFlavor() const override
Definition Process.cpp:4574
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition Process.cpp:4855
const char * GetRestartedReasonAtIndex(size_t idx)
Definition Process.h:459
static bool SetUpdateStateOnRemoval(Event *event_ptr)
Definition Process.cpp:4872
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4802
lldb::StateType GetState() const
Definition Process.h:454
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Process.cpp:4783
static llvm::StringRef GetFlavorString()
Definition Process.cpp:4570
void DoOnRemoval(Event *event_ptr) override
Definition Process.cpp:4696
void Dump(Stream *s) const override
Definition Process.cpp:4770
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:6791
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:6542
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:3855
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:4226
ThreadList & GetThreadList()
Definition Process.h:2370
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7209
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:6467
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:3950
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:6235
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:3575
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:5022
void SendAsyncInterrupt(Thread *thread=nullptr)
Send an async interrupt request.
Definition Process.cpp:4274
void AddInvalidMemoryRegion(const LoadRange &region)
Definition Process.cpp:6231
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6425
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:5260
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:6548
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:4953
void CloseSTDIOSecondaryFileDescriptor()
Close m_stdio_secondary_fd if it is still open.
Definition Process.cpp:5081
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6346
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:6333
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:5123
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:4937
void Flush()
Flush all data in the process.
Definition Process.cpp:6273
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:4208
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:6668
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:6259
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:4945
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:6525
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:6856
~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:6516
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:6352
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:3524
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4916
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:6185
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Process.cpp:4884
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:6531
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:4910
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:7140
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4882
bool SetPublicRunLockToStopped()
Definition Process.h:3426
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6326
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3960
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.cpp:3799
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:6875
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:6358
void SetCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6314
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:3940
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:6660
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:4286
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4930
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:6269
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:6623
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:3691
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:6320
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:6764
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:4923
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:6735
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:6296
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:6395
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:6495
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:6459
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:5067
lldb::addr_t m_highmem_code_address_mask
Definition Process.h:3599
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6536
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:4151
MemoryCache m_memory_cache
Definition Process.h:3557
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:5016
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
Definition Process.cpp:6485
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:6340
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:3964
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:7232
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:3747
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:4997
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:5086
Status DestroyImpl(bool force_kill)
Definition Process.cpp:3863
bool m_force_next_event_delivery
Definition Process.h:3604
void GetStatus(Stream &ostrm, bool is_verbose=false)
Definition Process.cpp:6162
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:3968
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:6289
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:5052
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:3955
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:6770
void SetBaseDirection(lldb::RunDirection direction)
Set the base run direction for the process.
Definition Process.cpp:3568
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:6891
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:6282
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:6599
friend class DynamicLoader
Definition Process.h:372
static void SettingsTerminate()
Definition Process.cpp:5125
lldb::addr_t GetHighmemDataAddressMask()
Definition Process.cpp:6305
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:6798
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6240
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:3645
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:7198
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:4978
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
Definition Process.cpp:6499
bool PrivateStateThreadIsRunning() const
Definition Process.h:3175
lldb::thread_result_t RunPrivateStateThread(PrivateStateThread::Purpose purpose)
Definition Process.cpp:4417
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:5329
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:5322
Module * GetExecutableModulePointer()
Definition Target.cpp:1664
void MarkExecutableModule(const lldb::ModuleSP &module_sp)
Make module_sp the main executable without clearing the other images, unlike RebuildModuleListWithExe...
Definition Target.cpp:1668
Debugger & GetDebugger() const
Definition Target.h:1365
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:4151
void ClearAllLoadedSections()
Definition Target.cpp:3603
void ClearModules(bool delete_locations)
Definition Target.cpp:1673
Architecture * GetArchitecturePlugin() const
Definition Target.h:1363
TargetStats & GetStatistics()
Definition Target.h:2249
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1821
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2751
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1644
void DidExec()
Called as the last function in Process::DidExec().
Definition Target.cpp:1681
bool RunStopHooks(bool at_initial_stop=false)
Definition Target.cpp:3270
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3493
lldb::PlatformSP GetPlatform()
Definition Target.h:2007
const ArchSpec & GetArchitecture() const
Definition Target.h:1324
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:1687
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:2009
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).
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:4140
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