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