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