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