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