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