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/Policy.h"
56#include "lldb/Target/Process.h"
61#include "lldb/Target/Target.h"
63#include "lldb/Target/Thread.h"
70#include "lldb/Utility/Event.h"
72#include "lldb/Utility/Log.h"
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 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(
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))
1593 } else {
1595 "invalid breakpoint site ID: %" PRIu64, break_id);
1596 }
1597
1598 return error;
1599}
1600
1602 BreakpointAction action) {
1603 auto site_sp = site.shared_from_this();
1604 std::unique_lock<std::recursive_mutex> guard(m_delayed_breakpoints_mutex);
1605
1606 // Ignore requests that won't change the Site status.
1607 if (IsBreakpointSiteEnabled(*site_sp) == (action == BreakpointAction::Enable))
1608 return llvm::Error::success();
1609
1611 m_delayed_breakpoints.Enqueue(site_sp, action);
1612 return llvm::Error::success();
1613 }
1614
1615 m_delayed_breakpoints.RemoveSite(site_sp);
1616 guard.unlock();
1617
1618 switch (action) {
1620 return EnableBreakpointSite(site_sp.get()).takeError();
1622 return DisableBreakpointSite(site_sp.get()).takeError();
1623 }
1624
1625 llvm_unreachable("Unhandled BreakpointAction");
1626}
1627
1629 Status error;
1630 BreakpointSiteSP bp_site_sp = m_breakpoint_site_list.FindByID(break_id);
1631 if (bp_site_sp) {
1632 if (!IsBreakpointSiteEnabled(*bp_site_sp))
1635 } else {
1637 "invalid breakpoint site ID: %" PRIu64, break_id);
1638 }
1639 return error;
1640}
1641
1643 std::lock_guard<std::recursive_mutex> guard(m_delayed_breakpoints_mutex);
1644
1645 // `site` won't be mutated, but the cache stores mutable pointers.
1646 auto it = m_delayed_breakpoints.m_site_to_action.find(
1647 const_cast<BreakpointSite &>(site).shared_from_this());
1648
1649 // If no actions are delayed, use the current state of the site.
1650 if (it == m_delayed_breakpoints.m_site_to_action.end())
1651 return site.m_enabled;
1652
1653 return it->second == BreakpointAction::Enable;
1654}
1655
1657 return site.m_enabled;
1658}
1659
1660static bool ShouldShowError(Process &process) {
1661 switch (process.GetState()) {
1662 case eStateInvalid:
1663 case eStateUnloaded:
1664 case eStateConnected:
1665 case eStateAttaching:
1666 case eStateLaunching:
1667 case eStateDetached:
1668 case eStateExited:
1669 return false;
1670 case eStateStopped:
1671 case eStateRunning:
1672 case eStateStepping:
1673 case eStateCrashed:
1674 case eStateSuspended:
1675 return process.IsAlive();
1676 }
1677 llvm_unreachable("unhandled process state");
1678}
1679
1681 Process &proc) {
1682 // Reset the IsIndirect flag here, in case the location changes from pointing
1683 // from an indirect symbol to a regular symbol.
1684 constituent.SetIsIndirect(false);
1685
1686 Target &target = proc.GetTarget();
1687
1688 if (!constituent.ShouldResolveIndirectFunctions())
1689 return constituent.GetAddress().GetOpcodeLoadAddress(&target);
1690
1691 const Symbol *symbol =
1693 if (!symbol || !symbol->IsIndirect())
1694 return constituent.GetAddress().GetOpcodeLoadAddress(&target);
1695
1696 // An indirect symbol is involved.
1697 Status error;
1698 Address symbol_address = symbol->GetAddress();
1699 addr_t load_addr = proc.ResolveIndirectFunction(&symbol_address, error);
1700
1701 if (!error.Success() && ShouldShowError(proc)) {
1702 target.GetDebugger().GetAsyncErrorStream()->Printf(
1703 "warning: failed to resolve indirect function at 0x%" PRIx64
1704 " for breakpoint %i.%i: %s\n",
1705 symbol->GetLoadAddress(&target), constituent.GetBreakpoint().GetID(),
1706 constituent.GetID(),
1707 error.AsCString() ? error.AsCString() : "unknown error");
1708 // FIXME: ShouldShowError must only guard the error message.
1709 // FIXME: Use diagnostics instead of printing "warning" to the async output.
1710 return LLDB_INVALID_ADDRESS;
1711 }
1712
1713 Address resolved_address(load_addr);
1714 constituent.SetIsIndirect(true);
1715 return resolved_address.GetOpcodeLoadAddress(&target);
1716}
1717
1719 std::unique_lock<std::recursive_mutex> guard(m_delayed_breakpoints_mutex);
1720
1721 // Clear the cache in m_delayed_breakpoints so it can't affect the actual
1722 // enabling of breakpoints. For example, if `EnableSoftwareBreakpoint` is
1723 // called outside of FlushDelayedBreakpoints, it needs to check the delayed
1724 // breakpoints and possibly early return. However, when called from
1725 // FlushDelayedBreakpoints, the queue better be empty so that no early returns
1726 // take place.
1727 auto site_to_action = std::move(m_delayed_breakpoints.m_site_to_action);
1728 m_delayed_breakpoints.m_site_to_action.clear();
1729
1730 guard.unlock();
1731 // Use a copy of the cache so that iteration is safe.
1732 return UpdateBreakpointSites(site_to_action);
1733}
1734
1736 const BreakpointSiteToActionMap &site_to_action) {
1737 llvm::Error error = llvm::Error::success();
1738 for (auto [site, action] : site_to_action) {
1739 Status new_error = action == BreakpointAction::Enable
1740 ? EnableBreakpointSite(site.get())
1741 : DisableBreakpointSite(site.get());
1742 error = llvm::joinErrors(std::move(error), new_error.takeError());
1743 }
1744 return error;
1745}
1746
1749 bool use_hardware) {
1750 addr_t load_addr = ComputeConstituentLoadAddress(*constituent, *this);
1751
1752 if (load_addr == LLDB_INVALID_ADDRESS)
1753 return LLDB_INVALID_BREAK_ID;
1754
1755 // Look up this breakpoint site. If it exists, then add this new
1756 // constituent, otherwise create a new breakpoint site and add it.
1757 if (BreakpointSiteSP bp_site_sp =
1758 m_breakpoint_site_list.FindByAddress(load_addr)) {
1759 bp_site_sp->AddConstituent(constituent);
1760 constituent->SetBreakpointSite(bp_site_sp);
1761 return bp_site_sp->GetID();
1762 }
1763
1764 BreakpointSiteSP bp_site_sp(
1765 new BreakpointSite(constituent, load_addr, use_hardware));
1766
1767 bool bp_from_address =
1768 constituent->GetBreakpoint().GetResolver()->GetResolverTy() ==
1770 bool should_be_eager = use_hardware || bp_from_address;
1771
1772 // If this breakpoint must be eager, flush the breakpoint queue in case there
1773 // is an interaction between the sites in the queue and this new site.
1774 if (should_be_eager)
1775 if (llvm::Error E = FlushDelayedBreakpoints())
1777 GetLog(LLDBLog::Breakpoints), std::move(E),
1778 "eager breakpoint requested, but failed to flush breakpoints: {0}");
1779
1780 auto error = should_be_eager ? EnableBreakpointSite(bp_site_sp.get())
1782 *bp_site_sp, BreakpointAction::Enable));
1783 if (error.Success()) {
1784 constituent->SetBreakpointSite(bp_site_sp);
1785 return m_breakpoint_site_list.Add(bp_site_sp);
1786 }
1787
1788 if (ShouldShowError(*this) || use_hardware) {
1789 // Report error for setting breakpoint...
1791 "warning: failed to set breakpoint site at 0x%" PRIx64
1792 " for breakpoint %i.%i: %s\n",
1793 load_addr, constituent->GetBreakpoint().GetID(), constituent->GetID(),
1794 error.AsCString() ? error.AsCString() : "unknown error");
1795 }
1796 return LLDB_INVALID_BREAK_ID;
1797}
1798
1800 lldb::user_id_t constituent_id, lldb::user_id_t constituent_loc_id,
1801 BreakpointSiteSP &bp_site_sp) {
1802 uint32_t num_constituents =
1803 bp_site_sp->RemoveConstituent(constituent_id, constituent_loc_id);
1804 if (num_constituents == 0) {
1805 // Don't try to disable the site if we don't have a live process anymore.
1806 if (IsAlive())
1807 llvm::consumeError(
1809 m_breakpoint_site_list.RemoveByAddress(bp_site_sp->GetLoadAddress());
1810 }
1811}
1812
1814 uint8_t *buf) const {
1815 size_t bytes_removed = 0;
1816 StopPointSiteList<BreakpointSite> bp_sites_in_range;
1817
1818 if (m_breakpoint_site_list.FindInRange(bp_addr, bp_addr + size,
1819 bp_sites_in_range)) {
1820 bp_sites_in_range.ForEach([bp_addr, size,
1821 buf](BreakpointSite *bp_site) -> void {
1822 if (bp_site->GetType() == BreakpointSite::eSoftware) {
1823 addr_t intersect_addr;
1824 size_t intersect_size;
1825 size_t opcode_offset;
1826 if (bp_site->IntersectsRange(bp_addr, size, &intersect_addr,
1827 &intersect_size, &opcode_offset)) {
1828 assert(bp_addr <= intersect_addr && intersect_addr < bp_addr + size);
1829 assert(bp_addr < intersect_addr + intersect_size &&
1830 intersect_addr + intersect_size <= bp_addr + size);
1831 assert(opcode_offset + intersect_size <= bp_site->GetByteSize());
1832 size_t buf_offset = intersect_addr - bp_addr;
1833 ::memcpy(buf + buf_offset,
1834 bp_site->GetSavedOpcodeBytes() + opcode_offset,
1835 intersect_size);
1836 }
1837 }
1838 });
1839 }
1840 return bytes_removed;
1841}
1842
1844 PlatformSP platform_sp(GetTarget().GetPlatform());
1845 if (platform_sp)
1846 return platform_sp->GetSoftwareBreakpointTrapOpcode(GetTarget(), bp_site);
1847 return 0;
1848}
1849
1851 Status error;
1852 assert(bp_site != nullptr);
1854 const addr_t bp_addr = bp_site->GetLoadAddress();
1855 LLDB_LOGF(
1856 log, "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64,
1857 bp_site->GetID(), (uint64_t)bp_addr);
1858 if (IsBreakpointSiteEnabled(*bp_site)) {
1859 LLDB_LOGF(
1860 log,
1861 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1862 " -- already enabled",
1863 bp_site->GetID(), (uint64_t)bp_addr);
1864 return error;
1865 }
1866
1867 if (bp_addr == LLDB_INVALID_ADDRESS) {
1869 "BreakpointSite contains an invalid load address.");
1870 return error;
1871 }
1872 // Ask the lldb::Process subclass to fill in the correct software breakpoint
1873 // trap for the breakpoint site
1874 const size_t bp_opcode_size = GetSoftwareBreakpointTrapOpcode(bp_site);
1875
1876 if (bp_opcode_size == 0) {
1878 "Process::GetSoftwareBreakpointTrapOpcode() "
1879 "returned zero, unable to get breakpoint "
1880 "trap for address 0x%" PRIx64,
1881 bp_addr);
1882 } else {
1883 const uint8_t *const bp_opcode_bytes = bp_site->GetTrapOpcodeBytes();
1884
1885 if (bp_opcode_bytes == nullptr) {
1887 "BreakpointSite doesn't contain a valid breakpoint trap opcode.");
1888 return error;
1889 }
1890
1891 // Save the original opcode by reading it
1892 if (DoReadMemory(bp_addr, bp_site->GetSavedOpcodeBytes(), bp_opcode_size,
1893 error) == bp_opcode_size) {
1894 // Write a software breakpoint in place of the original opcode
1895 if (DoWriteMemory(bp_addr, bp_opcode_bytes, bp_opcode_size, error) ==
1896 bp_opcode_size) {
1897 uint8_t verify_bp_opcode_bytes[64];
1898 if (DoReadMemory(bp_addr, verify_bp_opcode_bytes, bp_opcode_size,
1899 error) == bp_opcode_size) {
1900 if (::memcmp(bp_opcode_bytes, verify_bp_opcode_bytes,
1901 bp_opcode_size) == 0) {
1902 SetBreakpointSiteEnabled(*bp_site);
1904 LLDB_LOGF(log,
1905 "Process::EnableSoftwareBreakpoint (site_id = %d) "
1906 "addr = 0x%" PRIx64 " -- SUCCESS",
1907 bp_site->GetID(), (uint64_t)bp_addr);
1908 } else
1910 "failed to verify the breakpoint trap in memory.");
1911 } else
1913 "Unable to read memory to verify breakpoint trap.");
1914 } else
1916 "Unable to write breakpoint trap to memory.");
1917 } else
1919 "Unable to read memory at breakpoint address.");
1920 }
1921 if (log && error.Fail())
1922 LLDB_LOGF(
1923 log,
1924 "Process::EnableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
1925 " -- FAILED: %s",
1926 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
1927 return error;
1928}
1929
1931 Status error;
1932 assert(bp_site != nullptr);
1934 addr_t bp_addr = bp_site->GetLoadAddress();
1935 lldb::user_id_t breakID = bp_site->GetID();
1936 LLDB_LOGF(log,
1937 "Process::DisableSoftwareBreakpoint (breakID = %" PRIu64
1938 ") addr = 0x%" PRIx64,
1939 breakID, (uint64_t)bp_addr);
1940
1941 if (bp_site->IsHardware()) {
1942 error =
1943 Status::FromErrorString("Breakpoint site is a hardware breakpoint.");
1944 } else if (IsBreakpointSiteEnabled(*bp_site)) {
1945 const size_t break_op_size = bp_site->GetByteSize();
1946 const uint8_t *const break_op = bp_site->GetTrapOpcodeBytes();
1947 if (break_op_size > 0) {
1948 // Clear a software breakpoint instruction
1949 uint8_t curr_break_op[8];
1950 assert(break_op_size <= sizeof(curr_break_op));
1951 bool break_op_found = false;
1952
1953 // Read the breakpoint opcode
1954 if (DoReadMemory(bp_addr, curr_break_op, break_op_size, error) ==
1955 break_op_size) {
1956 bool verify = false;
1957 // Make sure the breakpoint opcode exists at this address
1958 if (::memcmp(curr_break_op, break_op, break_op_size) == 0) {
1959 break_op_found = true;
1960 // We found a valid breakpoint opcode at this address, now restore
1961 // the saved opcode.
1962 if (DoWriteMemory(bp_addr, bp_site->GetSavedOpcodeBytes(),
1963 break_op_size, error) == break_op_size) {
1964 verify = true;
1965 } else
1967 "Memory write failed when restoring original opcode.");
1968 } else {
1970 "Original breakpoint trap is no longer in memory.");
1971 // Set verify to true and so we can check if the original opcode has
1972 // already been restored
1973 verify = true;
1974 }
1975
1976 if (verify) {
1977 uint8_t verify_opcode[8];
1978 assert(break_op_size < sizeof(verify_opcode));
1979 // Verify that our original opcode made it back to the inferior
1980 if (DoReadMemory(bp_addr, verify_opcode, break_op_size, error) ==
1981 break_op_size) {
1982 // compare the memory we just read with the original opcode
1983 if (::memcmp(bp_site->GetSavedOpcodeBytes(), verify_opcode,
1984 break_op_size) == 0) {
1985 // SUCCESS
1986 SetBreakpointSiteEnabled(*bp_site, false);
1987 LLDB_LOGF(log,
1988 "Process::DisableSoftwareBreakpoint (site_id = %d) "
1989 "addr = 0x%" PRIx64 " -- SUCCESS",
1990 bp_site->GetID(), (uint64_t)bp_addr);
1991 return error;
1992 } else {
1993 if (break_op_found)
1995 "Failed to restore original opcode.");
1996 }
1997 } else
1998 error =
1999 Status::FromErrorString("Failed to read memory to verify that "
2000 "breakpoint trap was restored.");
2001 }
2002 } else
2004 "Unable to read memory that should contain the breakpoint trap.");
2005 }
2006 } else {
2007 LLDB_LOGF(
2008 log,
2009 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2010 " -- already disabled",
2011 bp_site->GetID(), (uint64_t)bp_addr);
2012 return error;
2013 }
2014
2015 LLDB_LOGF(
2016 log,
2017 "Process::DisableSoftwareBreakpoint (site_id = %d) addr = 0x%" PRIx64
2018 " -- FAILED: %s",
2019 bp_site->GetID(), (uint64_t)bp_addr, error.AsCString());
2020 return error;
2021}
2022
2023// Uncomment to verify memory caching works after making changes to caching
2024// code
2025//#define VERIFY_MEMORY_READS
2026
2027size_t Process::ReadMemory(addr_t addr, void *buf, size_t size, Status &error) {
2028 if (ABISP abi_sp = GetABI())
2029 addr = abi_sp->FixAnyAddress(addr);
2030
2031 error.Clear();
2032 if (!GetDisableMemoryCache()) {
2033#if defined(VERIFY_MEMORY_READS)
2034 // Memory caching is enabled, with debug verification
2035
2036 if (buf && size) {
2037 // Uncomment the line below to make sure memory caching is working.
2038 // I ran this through the test suite and got no assertions, so I am
2039 // pretty confident this is working well. If any changes are made to
2040 // memory caching, uncomment the line below and test your changes!
2041
2042 // Verify all memory reads by using the cache first, then redundantly
2043 // reading the same memory from the inferior and comparing to make sure
2044 // everything is exactly the same.
2045 std::string verify_buf(size, '\0');
2046 assert(verify_buf.size() == size);
2047 const size_t cache_bytes_read =
2048 m_memory_cache.Read(this, addr, buf, size, error);
2049 Status verify_error;
2050 const size_t verify_bytes_read =
2051 ReadMemoryFromInferior(addr, const_cast<char *>(verify_buf.data()),
2052 verify_buf.size(), verify_error);
2053 assert(cache_bytes_read == verify_bytes_read);
2054 assert(memcmp(buf, verify_buf.data(), verify_buf.size()) == 0);
2055 assert(verify_error.Success() == error.Success());
2056 return cache_bytes_read;
2057 }
2058 return 0;
2059#else // !defined(VERIFY_MEMORY_READS)
2060 // Memory caching is enabled, without debug verification
2061
2062 return m_memory_cache.Read(addr, buf, size, error);
2063#endif // defined (VERIFY_MEMORY_READS)
2064 } else {
2065 // Memory caching is disabled
2066
2067 return ReadMemoryFromInferior(addr, buf, size, error);
2068 }
2069}
2070
2071llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2073 llvm::MutableArrayRef<uint8_t> buffer) {
2074 auto total_ranges_len = llvm::sum_of(
2075 llvm::map_range(ranges, [](auto range) { return range.size; }));
2076 // If the buffer is not large enough, this is a programmer error.
2077 // In production builds, gracefully fail by returning a length of 0 for all
2078 // ranges.
2079 assert(buffer.size() >= total_ranges_len && "provided buffer is too short");
2080 if (buffer.size() < total_ranges_len) {
2081 llvm::MutableArrayRef<uint8_t> empty;
2082 return {ranges.size(), empty};
2083 }
2084
2085 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> results;
2086
2087 // While `buffer` has space, take the next requested range and read
2088 // memory into a `buffer` piece, then slice it to remove the used memory.
2089 for (auto [addr, range_len] : ranges) {
2090 Status status;
2091 size_t num_bytes_read =
2092 ReadMemoryFromInferior(addr, buffer.data(), range_len, status);
2093 // FIXME: ReadMemoryFromInferior promises to return 0 in case of errors, but
2094 // it doesn't; it never checks for errors.
2095 if (status.Fail())
2096 num_bytes_read = 0;
2097
2098 assert(num_bytes_read <= range_len && "read more than requested bytes");
2099 if (num_bytes_read > range_len) {
2100 // In production builds, gracefully fail by returning length zero for this
2101 // range.
2102 results.emplace_back();
2103 continue;
2104 }
2105
2106 results.push_back(buffer.take_front(num_bytes_read));
2107 // Slice buffer to remove the used memory.
2108 buffer = buffer.drop_front(num_bytes_read);
2109 }
2110
2111 return results;
2112}
2113
2115 const uint8_t *buf, size_t size,
2116 AddressRanges &matches, size_t alignment,
2117 size_t max_matches) {
2118 // Inputs are already validated in FindInMemory() functions.
2119 assert(buf != nullptr);
2120 assert(size > 0);
2121 assert(alignment > 0);
2122 assert(max_matches > 0);
2123 assert(start_addr != LLDB_INVALID_ADDRESS);
2124 assert(end_addr != LLDB_INVALID_ADDRESS);
2125 assert(start_addr < end_addr);
2126
2127 lldb::addr_t start = llvm::alignTo(start_addr, alignment);
2128 while (matches.size() < max_matches && (start + size) < end_addr) {
2129 const lldb::addr_t found_addr = FindInMemory(start, end_addr, buf, size);
2130 if (found_addr == LLDB_INVALID_ADDRESS)
2131 break;
2132
2133 if (found_addr % alignment) {
2134 // We need to check the alignment because the FindInMemory uses a special
2135 // algorithm to efficiently search mememory but doesn't support alignment.
2136 start = llvm::alignTo(start + 1, alignment);
2137 continue;
2138 }
2139
2140 matches.emplace_back(found_addr, size);
2141 start = found_addr + alignment;
2142 }
2143}
2144
2145AddressRanges Process::FindRangesInMemory(const uint8_t *buf, uint64_t size,
2146 const AddressRanges &ranges,
2147 size_t alignment, size_t max_matches,
2148 Status &error) {
2149 AddressRanges matches;
2150 if (buf == nullptr) {
2151 error = Status::FromErrorString("buffer is null");
2152 return matches;
2153 }
2154 if (size == 0) {
2155 error = Status::FromErrorString("buffer size is zero");
2156 return matches;
2157 }
2158 if (ranges.empty()) {
2159 error = Status::FromErrorString("empty ranges");
2160 return matches;
2161 }
2162 if (alignment == 0) {
2163 error = Status::FromErrorString("alignment must be greater than zero");
2164 return matches;
2165 }
2166 if (max_matches == 0) {
2167 error = Status::FromErrorString("max_matches must be greater than zero");
2168 return matches;
2169 }
2170
2171 int resolved_ranges = 0;
2172 Target &target = GetTarget();
2173 for (size_t i = 0; i < ranges.size(); ++i) {
2174 if (matches.size() >= max_matches)
2175 break;
2176 const AddressRange &range = ranges[i];
2177 if (range.IsValid() == false)
2178 continue;
2179
2180 const lldb::addr_t start_addr =
2181 range.GetBaseAddress().GetLoadAddress(&target);
2182 if (start_addr == LLDB_INVALID_ADDRESS)
2183 continue;
2184
2185 ++resolved_ranges;
2186 const lldb::addr_t end_addr = start_addr + range.GetByteSize();
2187 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment,
2188 max_matches);
2189 }
2190
2191 if (resolved_ranges > 0)
2192 error.Clear();
2193 else
2194 error = Status::FromErrorString("unable to resolve any ranges");
2195
2196 return matches;
2197}
2198
2199lldb::addr_t Process::FindInMemory(const uint8_t *buf, uint64_t size,
2200 const AddressRange &range, size_t alignment,
2201 Status &error) {
2202 if (buf == nullptr) {
2203 error = Status::FromErrorString("buffer is null");
2204 return LLDB_INVALID_ADDRESS;
2205 }
2206 if (size == 0) {
2207 error = Status::FromErrorString("buffer size is zero");
2208 return LLDB_INVALID_ADDRESS;
2209 }
2210 if (!range.IsValid()) {
2211 error = Status::FromErrorString("range is invalid");
2212 return LLDB_INVALID_ADDRESS;
2213 }
2214 if (alignment == 0) {
2215 error = Status::FromErrorString("alignment must be greater than zero");
2216 return LLDB_INVALID_ADDRESS;
2217 }
2218
2219 Target &target = GetTarget();
2220 const lldb::addr_t start_addr =
2221 range.GetBaseAddress().GetLoadAddress(&target);
2222 if (start_addr == LLDB_INVALID_ADDRESS) {
2223 error = Status::FromErrorString("range load address is invalid");
2224 return LLDB_INVALID_ADDRESS;
2225 }
2226 const lldb::addr_t end_addr = start_addr + range.GetByteSize();
2227
2228 AddressRanges matches;
2229 DoFindInMemory(start_addr, end_addr, buf, size, matches, alignment, 1);
2230 if (matches.empty())
2231 return LLDB_INVALID_ADDRESS;
2232
2233 error.Clear();
2234 return matches[0].GetBaseAddress().GetLoadAddress(&target);
2235}
2236
2237llvm::SmallVector<std::optional<std::string>>
2238Process::ReadCStringsFromMemory(llvm::ArrayRef<lldb::addr_t> addresses) {
2239 llvm::SmallVector<std::optional<std::string>> output_strs(addresses.size(),
2240 "");
2241 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2242 llvm::map_range(addresses, [=](addr_t ptr) {
2244 })};
2245
2246 std::vector<uint8_t> buffer(g_string_read_width * addresses.size(), 0);
2247 uint64_t num_completed_strings = 0;
2248
2249 while (num_completed_strings != addresses.size()) {
2250 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> read_results =
2251 ReadMemoryRanges(ranges, buffer);
2252
2253 // Each iteration of this loop either increments num_completed_strings or
2254 // updates the base pointer of some range, guaranteeing forward progress of
2255 // the outer loop.
2256 for (auto [range, read_result, output_str] :
2257 llvm::zip(ranges, read_results, output_strs)) {
2258 // A previously completed string.
2259 if (range.GetByteSize() == 0)
2260 continue;
2261
2262 // The read failed, set the range to 0 to avoid reading it again.
2263 if (read_result.empty()) {
2264 output_str = std::nullopt;
2265 range.SetByteSize(0);
2266 num_completed_strings++;
2267 continue;
2268 }
2269
2270 // Convert ArrayRef to StringRef so the pointers work with std::string.
2271 auto read_result_str = llvm::toStringRef(read_result);
2272
2273 const char *null_terminator_pos = llvm::find(read_result_str, '\0');
2274 output_str->append(read_result_str.begin(), null_terminator_pos);
2275
2276 // If the terminator was found, this string is complete.
2277 if (null_terminator_pos != read_result_str.end()) {
2278 range.SetByteSize(0);
2279 num_completed_strings++;
2280 }
2281 // Otherwise increment the base pointer for the next read.
2282 else {
2283 range.SetRangeBase(range.GetRangeBase() + read_result.size());
2284 }
2285 }
2286 }
2287
2288 return output_strs;
2289}
2290
2291size_t Process::ReadCStringFromMemory(addr_t addr, std::string &out_str,
2292 Status &error) {
2293 char buf[g_string_read_width];
2294 out_str.clear();
2295 addr_t curr_addr = addr;
2296 while (true) {
2297 size_t length = ReadCStringFromMemory(curr_addr, buf, sizeof(buf), error);
2298 if (length == 0)
2299 break;
2300 out_str.append(buf, length);
2301 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2302 // to read some more characters
2303 if (length == sizeof(buf) - 1)
2304 curr_addr += length;
2305 else
2306 break;
2307 }
2308 return out_str.size();
2309}
2310
2311// Deprecated in favor of ReadStringFromMemory which has wchar support and
2312// correct code to find null terminators.
2314 size_t dst_max_len,
2315 Status &result_error) {
2316 size_t total_cstr_len = 0;
2317 if (dst && dst_max_len) {
2318 result_error.Clear();
2319 // NULL out everything just to be safe
2320 memset(dst, 0, dst_max_len);
2321 addr_t curr_addr = addr;
2322 const size_t cache_line_size = m_memory_cache.GetMemoryCacheLineSize();
2323 size_t bytes_left = dst_max_len - 1;
2324 char *curr_dst = dst;
2325
2326 while (bytes_left > 0) {
2327 addr_t cache_line_bytes_left =
2328 cache_line_size - (curr_addr % cache_line_size);
2329 addr_t bytes_to_read =
2330 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2331 Status error;
2332 size_t bytes_read = ReadMemory(curr_addr, curr_dst, bytes_to_read, error);
2333
2334 if (bytes_read == 0) {
2335 result_error = std::move(error);
2336 dst[total_cstr_len] = '\0';
2337 break;
2338 }
2339 const size_t len = strlen(curr_dst);
2340
2341 total_cstr_len += len;
2342
2343 if (len < bytes_to_read)
2344 break;
2345
2346 curr_dst += bytes_read;
2347 curr_addr += bytes_read;
2348 bytes_left -= bytes_read;
2349 }
2350 } else {
2351 if (dst == nullptr)
2352 result_error = Status::FromErrorString("invalid arguments");
2353 else
2354 result_error.Clear();
2355 }
2356 return total_cstr_len;
2357}
2358
2359size_t Process::ReadMemoryFromInferior(addr_t addr, void *buf, size_t size,
2360 Status &error) {
2362
2363 if (ABISP abi_sp = GetABI())
2364 addr = abi_sp->FixAnyAddress(addr);
2365
2366 if (buf == nullptr || size == 0)
2367 return 0;
2368
2369 size_t bytes_read = 0;
2370 uint8_t *bytes = (uint8_t *)buf;
2371
2372 while (bytes_read < size) {
2373 const size_t curr_size = size - bytes_read;
2374 const size_t curr_bytes_read =
2375 DoReadMemory(addr + bytes_read, bytes + bytes_read, curr_size, error);
2376 bytes_read += curr_bytes_read;
2377 if (curr_bytes_read == curr_size || curr_bytes_read == 0)
2378 break;
2379 }
2380
2381 // Replace any software breakpoint opcodes that fall into this range back
2382 // into "buf" before we return
2383 if (bytes_read > 0)
2384 RemoveBreakpointOpcodesFromBuffer(addr, bytes_read, (uint8_t *)buf);
2385 return bytes_read;
2386}
2387
2389 lldb::addr_t chunk_size,
2390 lldb::offset_t size,
2391 ReadMemoryChunkCallback callback) {
2392 // Safety check to prevent an infinite loop.
2393 if (chunk_size == 0)
2394 return 0;
2395
2396 // Buffer for when a NULL buf is provided, initialized
2397 // to 0 bytes, we set it to chunk_size and then replace buf
2398 // with the new buffer.
2399 DataBufferHeap data_buffer;
2400 if (!buf) {
2401 data_buffer.SetByteSize(chunk_size);
2402 buf = data_buffer.GetBytes();
2403 }
2404
2405 uint64_t bytes_remaining = size;
2406 uint64_t bytes_read = 0;
2407 Status error;
2408 while (bytes_remaining > 0) {
2409 // Get the next read chunk size as the minimum of the remaining bytes and
2410 // the write chunk max size.
2411 const lldb::addr_t bytes_to_read = std::min(bytes_remaining, chunk_size);
2412 const lldb::addr_t current_addr = vm_addr + bytes_read;
2413 const lldb::addr_t bytes_read_for_chunk =
2414 ReadMemoryFromInferior(current_addr, buf, bytes_to_read, error);
2415
2416 bytes_read += bytes_read_for_chunk;
2417 // If the bytes read in this chunk would cause us to overflow, something
2418 // went wrong and we should fail fast.
2419 if (bytes_read_for_chunk > bytes_remaining)
2420 return 0;
2421 else
2422 bytes_remaining -= bytes_read_for_chunk;
2423
2424 if (callback(error, current_addr, buf, bytes_read_for_chunk) ==
2426 break;
2427 }
2428
2429 return bytes_read;
2430}
2431
2433 size_t integer_byte_size,
2434 uint64_t fail_value,
2435 Status &error) {
2436 Scalar scalar;
2437 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, false, scalar,
2438 error))
2439 return scalar.ULongLong(fail_value);
2440 return fail_value;
2441}
2442
2443llvm::SmallVector<std::optional<uint64_t>>
2444Process::ReadUnsignedIntegersFromMemory(llvm::ArrayRef<addr_t> addresses,
2445 unsigned integer_byte_size) {
2446 if (addresses.empty())
2447 return {};
2448 // Like ReadUnsignedIntegerFromMemory, this only supports a handful
2449 // of widths.
2450 if (!llvm::is_contained({1u, 2u, 4u, 8u}, integer_byte_size))
2451 return llvm::SmallVector<std::optional<uint64_t>>(addresses.size(),
2452 std::nullopt);
2453
2454 llvm::SmallVector<Range<addr_t, size_t>> ranges{
2455 llvm::map_range(addresses, [=](addr_t ptr) {
2456 return Range<addr_t, size_t>(ptr, integer_byte_size);
2457 })};
2458
2459 std::vector<uint8_t> buffer(integer_byte_size * addresses.size(), 0);
2460 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory =
2461 ReadMemoryRanges(ranges, buffer);
2462
2463 llvm::SmallVector<std::optional<uint64_t>> result;
2464 result.reserve(addresses.size());
2465 const uint32_t addr_size = GetAddressByteSize();
2466 const ByteOrder byte_order = GetByteOrder();
2467
2468 for (llvm::MutableArrayRef<uint8_t> range : memory) {
2469 if (range.size() != integer_byte_size) {
2470 result.push_back(std::nullopt);
2471 continue;
2472 }
2473
2474 DataExtractor data(range.data(), integer_byte_size, byte_order, addr_size);
2475 offset_t offset = 0;
2476 result.push_back(data.GetMaxU64(&offset, integer_byte_size));
2477 assert(offset == integer_byte_size);
2478 }
2479 return result;
2480}
2481
2483 size_t integer_byte_size,
2484 int64_t fail_value,
2485 Status &error) {
2486 Scalar scalar;
2487 if (ReadScalarIntegerFromMemory(vm_addr, integer_byte_size, true, scalar,
2488 error))
2489 return scalar.SLongLong(fail_value);
2490 return fail_value;
2491}
2492
2494 Scalar scalar;
2495 if (ReadScalarIntegerFromMemory(vm_addr, GetAddressByteSize(), false, scalar,
2496 error))
2497 return scalar.ULongLong(LLDB_INVALID_ADDRESS);
2498 return LLDB_INVALID_ADDRESS;
2499}
2500
2501llvm::SmallVector<std::optional<addr_t>>
2502Process::ReadPointersFromMemory(llvm::ArrayRef<addr_t> ptr_locs) {
2503 const size_t ptr_size = GetAddressByteSize();
2504 return ReadUnsignedIntegersFromMemory(ptr_locs, ptr_size);
2505}
2506
2508 Status &error) {
2509 Scalar scalar;
2510 const uint32_t addr_byte_size = GetAddressByteSize();
2511 if (addr_byte_size <= 4)
2512 scalar = (uint32_t)ptr_value;
2513 else
2514 scalar = ptr_value;
2515 return WriteScalarToMemory(vm_addr, scalar, addr_byte_size, error) ==
2516 addr_byte_size;
2517}
2518
2519size_t Process::WriteMemoryPrivate(addr_t addr, const void *buf, size_t size,
2520 Status &error) {
2521 size_t bytes_written = 0;
2522 const uint8_t *bytes = (const uint8_t *)buf;
2523
2524 while (bytes_written < size) {
2525 const size_t curr_size = size - bytes_written;
2526 const size_t curr_bytes_written = DoWriteMemory(
2527 addr + bytes_written, bytes + bytes_written, curr_size, error);
2528 bytes_written += curr_bytes_written;
2529 if (curr_bytes_written == curr_size || curr_bytes_written == 0)
2530 break;
2531 }
2532 return bytes_written;
2533}
2534
2535size_t Process::WriteMemory(addr_t addr, const void *buf, size_t size,
2536 Status &error) {
2537 if (ABISP abi_sp = GetABI())
2538 addr = abi_sp->FixAnyAddress(addr);
2539
2540 m_memory_cache.Flush(addr, size);
2541
2542 if (buf == nullptr || size == 0)
2543 return 0;
2544
2545 if (TrackMemoryCacheChanges() || !m_allocated_memory_cache.IsInCache(addr))
2546 m_mod_id.BumpMemoryID();
2547
2548 // We need to write any data that would go where any current software traps
2549 // (enabled software breakpoints) any software traps (breakpoints) that we
2550 // may have placed in our tasks memory.
2551
2552 StopPointSiteList<BreakpointSite> bp_sites_in_range;
2553 if (!m_breakpoint_site_list.FindInRange(addr, addr + size, bp_sites_in_range))
2554 return WriteMemoryPrivate(addr, buf, size, error);
2555
2556 // No breakpoint sites overlap
2557 if (bp_sites_in_range.IsEmpty())
2558 return WriteMemoryPrivate(addr, buf, size, error);
2559
2560 const uint8_t *ubuf = (const uint8_t *)buf;
2561 uint64_t bytes_written = 0;
2562
2563 bp_sites_in_range.ForEach([this, addr, size, &bytes_written, &ubuf,
2564 &error](BreakpointSite *bp) -> void {
2565 if (error.Fail())
2566 return;
2567
2569 return;
2570
2571 addr_t intersect_addr;
2572 size_t intersect_size;
2573 size_t opcode_offset;
2574 const bool intersects = bp->IntersectsRange(
2575 addr, size, &intersect_addr, &intersect_size, &opcode_offset);
2576 UNUSED_IF_ASSERT_DISABLED(intersects);
2577 assert(intersects);
2578 assert(addr <= intersect_addr && intersect_addr < addr + size);
2579 assert(addr < intersect_addr + intersect_size &&
2580 intersect_addr + intersect_size <= addr + size);
2581 assert(opcode_offset + intersect_size <= bp->GetByteSize());
2582
2583 // Check for bytes before this breakpoint
2584 const addr_t curr_addr = addr + bytes_written;
2585 if (intersect_addr > curr_addr) {
2586 // There are some bytes before this breakpoint that we need to just
2587 // write to memory
2588 size_t curr_size = intersect_addr - curr_addr;
2589 size_t curr_bytes_written =
2590 WriteMemoryPrivate(curr_addr, ubuf + bytes_written, curr_size, error);
2591 bytes_written += curr_bytes_written;
2592 if (curr_bytes_written != curr_size) {
2593 // We weren't able to write all of the requested bytes, we are
2594 // done looping and will return the number of bytes that we have
2595 // written so far.
2596 if (error.Success())
2597 error = Status::FromErrorString("could not write all bytes");
2598 }
2599 }
2600 // Now write any bytes that would cover up any software breakpoints
2601 // directly into the breakpoint opcode buffer
2602 ::memcpy(bp->GetSavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,
2603 intersect_size);
2604 bytes_written += intersect_size;
2605 });
2606
2607 // Write any remaining bytes after the last breakpoint if we have any left
2608 if (bytes_written < size)
2609 bytes_written +=
2610 WriteMemoryPrivate(addr + bytes_written, ubuf + bytes_written,
2611 size - bytes_written, error);
2612
2613 return bytes_written;
2614}
2615
2616size_t Process::WriteScalarToMemory(addr_t addr, const Scalar &scalar,
2617 size_t byte_size, Status &error) {
2618 if (byte_size == UINT32_MAX)
2619 byte_size = scalar.GetByteSize();
2620 if (byte_size > 0) {
2621 uint8_t buf[32];
2622 const size_t mem_size =
2623 scalar.GetAsMemoryData(buf, byte_size, GetByteOrder(), error);
2624 if (mem_size > 0)
2625 return WriteMemory(addr, buf, mem_size, error);
2626 else
2627 error = Status::FromErrorString("failed to get scalar as memory data");
2628 } else {
2629 error = Status::FromErrorString("invalid scalar value");
2630 }
2631 return 0;
2632}
2633
2634size_t Process::ReadScalarIntegerFromMemory(addr_t addr, uint32_t byte_size,
2635 bool is_signed, Scalar &scalar,
2636 Status &error) {
2637 uint64_t uval = 0;
2638 if (byte_size == 0) {
2639 error = Status::FromErrorString("byte size is zero");
2640 } else if (byte_size & (byte_size - 1)) {
2642 "byte size %u is not a power of 2", byte_size);
2643 } else if (byte_size <= sizeof(uval)) {
2644 const size_t bytes_read = ReadMemory(addr, &uval, byte_size, error);
2645 if (bytes_read == byte_size) {
2646 DataExtractor data(&uval, sizeof(uval), GetByteOrder(),
2648 lldb::offset_t offset = 0;
2649 if (byte_size <= 4)
2650 scalar = data.GetMaxU32(&offset, byte_size);
2651 else
2652 scalar = data.GetMaxU64(&offset, byte_size);
2653 if (is_signed) {
2654 scalar.MakeSigned();
2655 scalar.SignExtend(byte_size * 8);
2656 }
2657 return bytes_read;
2658 }
2659 } else {
2661 "byte size of %u is too large for integer scalar type", byte_size);
2662 }
2663 return 0;
2664}
2665
2666Status Process::WriteObjectFile(std::vector<ObjectFile::LoadableData> entries) {
2667 Status error;
2668 for (const auto &Entry : entries) {
2669 WriteMemory(Entry.Dest, Entry.Contents.data(), Entry.Contents.size(),
2670 error);
2671 if (!error.Success())
2672 break;
2673 }
2674 return error;
2675}
2676
2677addr_t Process::AllocateMemory(size_t size, uint32_t permissions,
2678 Status &error) {
2679 if (GetPrivateState() != eStateStopped) {
2681 "cannot allocate memory while process is running");
2682 return LLDB_INVALID_ADDRESS;
2683 }
2684
2685 return m_allocated_memory_cache.AllocateMemory(size, permissions, error);
2686}
2687
2688addr_t Process::CallocateMemory(size_t size, uint32_t permissions,
2689 Status &error) {
2690 addr_t return_addr = AllocateMemory(size, permissions, error);
2691 if (error.Success()) {
2692 std::string buffer(size, 0);
2693 WriteMemory(return_addr, buffer.c_str(), size, error);
2694 }
2695 return return_addr;
2696}
2697
2699 if (m_can_jit == eCanJITDontKnow) {
2700 Log *log = GetLog(LLDBLog::Process);
2701 Status err;
2702
2703 uint64_t allocated_memory = AllocateMemory(
2704 8, ePermissionsReadable | ePermissionsWritable | ePermissionsExecutable,
2705 err);
2706
2707 if (err.Success()) {
2709 LLDB_LOGF(log,
2710 "Process::%s pid %" PRIu64
2711 " allocation test passed, CanJIT () is true",
2712 __FUNCTION__, GetID());
2713 } else {
2715 LLDB_LOGF(log,
2716 "Process::%s pid %" PRIu64
2717 " allocation test failed, CanJIT () is false: %s",
2718 __FUNCTION__, GetID(), err.AsCString());
2719 }
2720
2721 DeallocateMemory(allocated_memory);
2722 }
2723
2724 return m_can_jit == eCanJITYes;
2725}
2726
2727void Process::SetCanJIT(bool can_jit) {
2728 m_can_jit = (can_jit ? eCanJITYes : eCanJITNo);
2729}
2730
2731void Process::SetCanRunCode(bool can_run_code) {
2732 SetCanJIT(can_run_code);
2733 m_can_interpret_function_calls = can_run_code;
2734}
2735
2737 Status error;
2738 if (!m_allocated_memory_cache.DeallocateMemory(ptr)) {
2740 "deallocation of memory at 0x%" PRIx64 " failed.", (uint64_t)ptr);
2741 }
2742 return error;
2743}
2744
2746 if (std::optional<bool> subclass_override = DoGetWatchpointReportedAfter())
2747 return *subclass_override;
2748
2749 bool reported_after = true;
2750 const ArchSpec &arch = GetTarget().GetArchitecture();
2751 if (!arch.IsValid())
2752 return reported_after;
2753 llvm::Triple triple = arch.GetTriple();
2754
2755 if (triple.isMIPS() || triple.isPPC64() || triple.isRISCV() ||
2756 triple.isAArch64() || triple.isArmMClass() || triple.isARM() ||
2757 triple.isLoongArch())
2758 reported_after = false;
2759
2760 return reported_after;
2761}
2762
2763llvm::Expected<ModuleSP>
2765 lldb::addr_t header_addr, size_t size_to_read) {
2767 "Process::ReadModuleFromMemory reading %s binary from memory",
2768 file_spec.GetPath().c_str());
2769 ModuleSP module_sp = std::make_shared<Module>(file_spec, ArchSpec());
2770 if (!module_sp)
2771 return llvm::createStringError("failed to allocate module");
2772
2773 Status error;
2774 std::unique_ptr<Progress> progress_up;
2775 // Reading an ObjectFile from a local corefile is very fast,
2776 // only print a progress update if we're reading from a
2777 // live session which might go over gdb remote serial protocol.
2778 if (IsLiveDebugSession())
2779 progress_up = std::make_unique<Progress>(
2780 "Reading binary from memory", file_spec.GetFilename().GetString());
2781
2782 if (ObjectFile *_ = module_sp->GetMemoryObjectFile(
2783 shared_from_this(), header_addr, error, size_to_read))
2784 return module_sp;
2785
2786 return error.takeError();
2787}
2788
2790 uint32_t &permissions) {
2791 MemoryRegionInfo range_info;
2792 permissions = 0;
2793 Status error(GetMemoryRegionInfo(load_addr, range_info));
2794 if (!error.Success())
2795 return false;
2796 if (range_info.GetReadable() == eLazyBoolDontKnow ||
2797 range_info.GetWritable() == eLazyBoolDontKnow ||
2798 range_info.GetExecutable() == eLazyBoolDontKnow) {
2799 return false;
2800 }
2801 permissions = range_info.GetLLDBPermissions();
2802 return true;
2803}
2804
2806 Status error;
2807 error = Status::FromErrorString("watchpoints are not supported");
2808 return error;
2809}
2810
2812 Status error;
2813 error = Status::FromErrorString("watchpoints are not supported");
2814 return error;
2815}
2816
2819 const Timeout<std::micro> &timeout) {
2820 StateType state;
2821
2822 while (true) {
2823 event_sp.reset();
2824 state = GetStateChangedEventsPrivate(event_sp, timeout);
2825
2826 if (StateIsStoppedState(state, false))
2827 break;
2828
2829 // If state is invalid, then we timed out
2830 if (state == eStateInvalid)
2831 break;
2832
2833 if (event_sp)
2834 HandlePrivateEvent(event_sp);
2835 }
2836 return state;
2837}
2838
2840 std::lock_guard<std::recursive_mutex> guard(m_thread_mutex);
2841 if (flush)
2842 m_thread_list.Clear();
2843 m_os_up.reset(OperatingSystem::FindPlugin(this, nullptr));
2844 if (flush)
2845 Flush();
2846}
2847
2849 StateType state_after_launch = eStateInvalid;
2850 EventSP first_stop_event_sp;
2851 Status status =
2852 LaunchPrivate(launch_info, state_after_launch, first_stop_event_sp);
2853 if (status.Fail())
2854 return status;
2855
2856 if (state_after_launch != eStateStopped &&
2857 state_after_launch != eStateCrashed)
2858 return Status();
2859
2860 // Note, the stop event was consumed above, but not handled. This
2861 // was done to give DidLaunch a chance to run. The target is either
2862 // stopped or crashed. Directly set the state. This is done to
2863 // prevent a stop message with a bunch of spurious output on thread
2864 // status, as well as not pop a ProcessIOHandler.
2865
2867 SetPublicState(state_after_launch, false);
2869 } else {
2870 StartPrivateStateThread(state_after_launch, false);
2872 // We are not going to get any further here. The only way this could fail
2873 // is if we can't start a host thread, so we're pretty much toast at that
2874 // point.
2875 return Status::FromErrorString("could not start private state thread.");
2876 }
2877 }
2878
2879 // Target was stopped at entry as was intended. Need to notify the
2880 // listeners about it.
2881 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2882 HandlePrivateEvent(first_stop_event_sp);
2883
2884 return Status();
2885}
2886
2888 EventSP &event_sp) {
2889 Status error;
2890 m_abi_sp.reset();
2891 m_dyld_up.reset();
2892 m_jit_loaders_up.reset();
2893 m_system_runtime_up.reset();
2894 m_os_up.reset();
2896
2897 {
2898 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
2899 m_process_input_reader.reset();
2900 }
2901
2903
2904 // The "remote executable path" is hooked up to the local Executable
2905 // module. But we should be able to debug a remote process even if the
2906 // executable module only exists on the remote. However, there needs to
2907 // be a way to express this path, without actually having a module.
2908 // The way to do that is to set the ExecutableFile in the LaunchInfo.
2909 // Figure that out here:
2910
2911 FileSpec exe_spec_to_use;
2912 if (!exe_module) {
2913 if (!launch_info.GetExecutableFile() && !launch_info.IsScriptedProcess()) {
2914 error = Status::FromErrorString("executable module does not exist");
2915 return error;
2916 }
2917 exe_spec_to_use = launch_info.GetExecutableFile();
2918 } else
2919 exe_spec_to_use = exe_module->GetFileSpec();
2920
2921 if (exe_module && FileSystem::Instance().Exists(exe_module->GetFileSpec())) {
2922 // Install anything that might need to be installed prior to launching.
2923 // For host systems, this will do nothing, but if we are connected to a
2924 // remote platform it will install any needed binaries
2925 error = GetTarget().Install(&launch_info);
2926 if (error.Fail())
2927 return error;
2928 }
2929
2930 // Listen and queue events that are broadcasted during the process launch.
2931 ListenerSP listener_sp(Listener::MakeListener("LaunchEventHijack"));
2932 HijackProcessEvents(listener_sp);
2933 llvm::scope_exit on_exit([this]() { RestoreProcessEvents(); });
2934
2937
2938 error = WillLaunch(exe_module);
2939 if (error.Fail()) {
2940 std::string local_exec_file_path = exe_spec_to_use.GetPath();
2941 return Status::FromErrorStringWithFormat("file doesn't exist: '%s'",
2942 local_exec_file_path.c_str());
2943 }
2944
2945 const bool restarted = false;
2946 SetPublicState(eStateLaunching, restarted);
2947 m_should_detach = false;
2948
2950 error = DoLaunch(exe_module, launch_info);
2951
2952 if (error.Fail()) {
2953 if (GetID() != LLDB_INVALID_PROCESS_ID) {
2955 const char *error_string = error.AsCString();
2956 if (error_string == nullptr)
2957 error_string = "launch failed";
2958 SetExitStatus(-1, error_string);
2959 }
2960 return error;
2961 }
2962
2963 // Now wait for the process to launch and return control to us, and then
2964 // call DidLaunch:
2965 state = WaitForProcessStopPrivate(event_sp, seconds(10));
2966
2967 if (state == eStateInvalid || !event_sp) {
2968 // We were able to launch the process, but we failed to catch the
2969 // initial stop.
2970 error = Status::FromErrorString("failed to catch stop after launch");
2971 SetExitStatus(0, error.AsCString());
2972 Destroy(false);
2973 return error;
2974 }
2975
2976 if (state == eStateExited) {
2977 // We exited while trying to launch somehow. Don't call DidLaunch
2978 // as that's not likely to work, and return an invalid pid.
2979 HandlePrivateEvent(event_sp);
2980 return Status();
2981 }
2982
2983 if (state == eStateStopped || state == eStateCrashed) {
2984 DidLaunch();
2985
2986 // Now that we know the process type, update its signal responses from the
2987 // ones stored in the Target:
2990 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());
2991
2993 if (dyld)
2994 dyld->DidLaunch();
2995
2997
2998 SystemRuntime *system_runtime = GetSystemRuntime();
2999 if (system_runtime)
3000 system_runtime->DidLaunch();
3001
3002 if (!m_os_up)
3004
3005 // We successfully launched the process and stopped, now it the
3006 // right time to set up signal filters before resuming.
3008 return Status();
3009 }
3010
3012 "Unexpected process state after the launch: %s, expected %s, "
3013 "%s, %s or %s",
3017}
3018
3022 if (error.Success()) {
3023 ListenerSP listener_sp(
3024 Listener::MakeListener("lldb.process.load_core_listener"));
3025 HijackProcessEvents(listener_sp);
3026
3029 else {
3031 /*RunLock is stopped*/ false);
3033 // We are not going to get any further here. The only way this
3034 // could fail is if we can't start a host thread, so we're pretty much
3035 // toast at that point.
3036 return Status::FromErrorString("could not start private state thread.");
3037 }
3038 }
3039
3041 if (dyld)
3042 dyld->DidAttach();
3043
3045
3046 SystemRuntime *system_runtime = GetSystemRuntime();
3047 if (system_runtime)
3048 system_runtime->DidAttach();
3049
3050 if (!m_os_up)
3052
3053 // We successfully loaded a core file, now pretend we stopped so we can
3054 // show all of the threads in the core file and explore the crashed state.
3056
3057 // Wait for a stopped event since we just posted one above...
3058 lldb::EventSP event_sp;
3059 StateType state =
3060 WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
3061 nullptr, true, SelectMostRelevantFrame);
3062
3063 if (!StateIsStoppedState(state, false)) {
3064 Log *log = GetLog(LLDBLog::Process);
3065 LLDB_LOGF(log, "Process::Halt() failed to stop, state is: %s",
3066 StateAsCString(state));
3068 "Did not get stopped event after loading the core file.");
3069 }
3071 // Since we hijacked the event stream, we will have we won't have run the
3072 // stop hooks. Make sure we do that here:
3073 GetTarget().RunStopHooks(/* at_initial_stop= */ true);
3074 }
3075 return error;
3076}
3077
3079 if (!m_dyld_up)
3080 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3081 return m_dyld_up.get();
3082}
3083
3085 m_dyld_up = std::move(dyld_up);
3086}
3087
3089
3090llvm::Expected<bool> Process::SaveCore(llvm::StringRef outfile) {
3091 return false;
3092}
3093
3095 if (!m_jit_loaders_up) {
3096 m_jit_loaders_up = std::make_unique<JITLoaderList>();
3098 }
3099 return *m_jit_loaders_up;
3100}
3101
3107
3109 uint32_t exec_count)
3110 : NextEventAction(process), m_exec_count(exec_count) {
3111 Log *log = GetLog(LLDBLog::Process);
3112 LLDB_LOGF(
3113 log,
3114 "Process::AttachCompletionHandler::%s process=%p, exec_count=%" PRIu32,
3115 __FUNCTION__, static_cast<void *>(process), exec_count);
3116}
3117
3120 Log *log = GetLog(LLDBLog::Process);
3121
3122 StateType state = ProcessEventData::GetStateFromEvent(event_sp.get());
3123 LLDB_LOGF(log,
3124 "Process::AttachCompletionHandler::%s called with state %s (%d)",
3125 __FUNCTION__, StateAsCString(state), static_cast<int>(state));
3126
3127 switch (state) {
3128 case eStateAttaching:
3129 return eEventActionSuccess;
3130
3131 case eStateRunning:
3132 case eStateConnected:
3133 return eEventActionRetry;
3134
3135 case eStateStopped:
3136 case eStateCrashed:
3137 // During attach, prior to sending the eStateStopped event,
3138 // lldb_private::Process subclasses must set the new process ID.
3139 assert(m_process->GetID() != LLDB_INVALID_PROCESS_ID);
3140 // We don't want these events to be reported, so go set the
3141 // ShouldReportStop here:
3142 m_process->GetThreadList().SetShouldReportStop(eVoteNo);
3143
3144 if (m_exec_count > 0) {
3145 --m_exec_count;
3146
3147 LLDB_LOGF(log,
3148 "Process::AttachCompletionHandler::%s state %s: reduced "
3149 "remaining exec count to %" PRIu32 ", requesting resume",
3150 __FUNCTION__, StateAsCString(state), m_exec_count);
3151
3152 RequestResume();
3153 return eEventActionRetry;
3154 } else {
3155 LLDB_LOGF(log,
3156 "Process::AttachCompletionHandler::%s state %s: no more "
3157 "execs expected to start, continuing with attach",
3158 __FUNCTION__, StateAsCString(state));
3159
3160 m_process->CompleteAttach();
3161 return eEventActionSuccess;
3162 }
3163 break;
3164
3165 default:
3166 case eStateExited:
3167 case eStateInvalid:
3168 break;
3169 }
3170
3171 m_exit_string.assign("No valid Process");
3172 return eEventActionExit;
3173}
3174
3179
3181 return m_exit_string.c_str();
3182}
3183
3185 if (m_listener_sp)
3186 return m_listener_sp;
3187 else
3188 return debugger.GetListener();
3189}
3190
3192 return DoWillLaunch(module);
3193}
3194
3198
3200 bool wait_for_launch) {
3201 return DoWillAttachToProcessWithName(process_name, wait_for_launch);
3202}
3203
3205 m_abi_sp.reset();
3206 {
3207 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3208 m_process_input_reader.reset();
3209 }
3210 m_dyld_up.reset();
3211 m_jit_loaders_up.reset();
3212 m_system_runtime_up.reset();
3213 m_os_up.reset();
3215
3216 lldb::pid_t attach_pid = attach_info.GetProcessID();
3217 Status error;
3218 if (attach_pid == LLDB_INVALID_PROCESS_ID) {
3219 char process_name[PATH_MAX];
3220
3221 if (attach_info.GetExecutableFile().GetPath(process_name,
3222 sizeof(process_name))) {
3223 const bool wait_for_launch = attach_info.GetWaitForLaunch();
3224
3225 if (wait_for_launch) {
3226 error = WillAttachToProcessWithName(process_name, wait_for_launch);
3227 if (error.Success()) {
3228 m_should_detach = true;
3229 // Now attach using these arguments.
3230 error = DoAttachToProcessWithName(process_name, attach_info);
3231
3232 if (error.Fail()) {
3233 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3235 if (error.AsCString() == nullptr)
3236 error = Status::FromErrorString("attach failed");
3237
3238 SetExitStatus(-1, error.AsCString());
3239 }
3240 } else {
3242 this, attach_info.GetResumeCount()));
3245 // We are not going to get any further here. The only way
3246 // this could fail is if we can't start a host thread, and we're
3247 // pretty much toast at that point.
3249 "could not start private state thread.");
3250 }
3251 }
3252 return error;
3253 }
3254 } else {
3255 ProcessInstanceInfoList process_infos;
3256 PlatformSP platform_sp(GetTarget().GetPlatform());
3257
3258 if (platform_sp) {
3259 ProcessInstanceInfoMatch match_info;
3260 match_info.GetProcessInfo() = attach_info;
3262 platform_sp->FindProcesses(match_info, process_infos);
3263 const uint32_t num_matches = process_infos.size();
3264 if (num_matches == 1) {
3265 attach_pid = process_infos[0].GetProcessID();
3266 // Fall through and attach using the above process ID
3267 } else {
3269 process_name, sizeof(process_name));
3270 if (num_matches > 1) {
3271 StreamString s;
3273 for (size_t i = 0; i < num_matches; i++) {
3274 process_infos[i].DumpAsTableRow(
3275 s, platform_sp->GetUserIDResolver(), true, false);
3276 }
3278 "more than one process named %s:\n%s", process_name,
3279 s.GetData());
3280 } else
3282 "could not find a process named %s", process_name);
3283 }
3284 } else {
3286 "invalid platform, can't find processes by name");
3287 return error;
3288 }
3289 }
3290 } else {
3291 error = Status::FromErrorString("invalid process name");
3292 }
3293 }
3294
3295 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
3296 error = WillAttachToProcessWithID(attach_pid);
3297 if (error.Success()) {
3298 // Now attach using these arguments.
3299 m_should_detach = true;
3300 error = DoAttachToProcessWithID(attach_pid, attach_info);
3301
3302 if (error.Success()) {
3304 this, attach_info.GetResumeCount()));
3305
3308 // We are not going to get any further here. The only way this
3309 // could fail is if we can't start a host thread, so we're pretty much
3310 // toast at thatpoint.
3312 "could not start private state thread.");
3313 }
3314 } else {
3317
3318 const char *error_string = error.AsCString();
3319 if (error_string == nullptr)
3320 error_string = "attach failed";
3321
3322 SetExitStatus(-1, error_string);
3323 }
3324 }
3325 }
3326 return error;
3327}
3328
3331 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
3332
3333 // Let the process subclass figure out at much as it can about the process
3334 // before we go looking for a dynamic loader plug-in.
3335 ArchSpec process_arch;
3336 DidAttach(process_arch);
3337
3338 if (process_arch.IsValid()) {
3339 LLDB_LOG(log,
3340 "Process::{0} replacing process architecture with DidAttach() "
3341 "architecture: \"{1}\"",
3342 __FUNCTION__, process_arch.GetTriple().getTriple());
3343 GetTarget().SetArchitecture(process_arch);
3344 }
3345
3346 // We just attached. If we have a platform, ask it for the process
3347 // architecture, and if it isn't the same as the one we've already set,
3348 // switch architectures.
3349 PlatformSP platform_sp(GetTarget().GetPlatform());
3350 assert(platform_sp);
3351 ArchSpec process_host_arch = GetSystemArchitecture();
3352 if (platform_sp) {
3353 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3354 if (target_arch.IsValid() && !platform_sp->IsCompatibleArchitecture(
3355 target_arch, process_host_arch,
3356 ArchSpec::CompatibleMatch, nullptr)) {
3357 ArchSpec platform_arch;
3359 target_arch, process_host_arch, &platform_arch);
3360 if (platform_sp) {
3361 GetTarget().SetPlatform(platform_sp);
3362 GetTarget().SetArchitecture(platform_arch);
3363 LLDB_LOG(log,
3364 "switching platform to {0} and architecture to {1} based on "
3365 "info from attach",
3366 platform_sp->GetName(), platform_arch.GetTriple().getTriple());
3367 }
3368 } else if (!process_arch.IsValid()) {
3369 ProcessInstanceInfo process_info;
3370 GetProcessInfo(process_info);
3371 const ArchSpec &process_arch = process_info.GetArchitecture();
3372 const ArchSpec &target_arch = GetTarget().GetArchitecture();
3373 if (process_arch.IsValid() &&
3374 target_arch.IsCompatibleMatch(process_arch) &&
3375 !target_arch.IsExactMatch(process_arch)) {
3376 GetTarget().SetArchitecture(process_arch);
3377 LLDB_LOGF(log,
3378 "Process::%s switching architecture to %s based on info "
3379 "the platform retrieved for pid %" PRIu64,
3380 __FUNCTION__, process_arch.GetTriple().getTriple().c_str(),
3381 GetID());
3382 }
3383 }
3384 }
3385 // Now that we know the process type, update its signal responses from the
3386 // ones stored in the Target:
3389 m_unix_signals_sp, GetTarget().GetDebugger().GetAsyncErrorStream());
3390
3391 // We have completed the attach, now it is time to find the dynamic loader
3392 // plug-in
3394 if (dyld) {
3395 dyld->DidAttach();
3396 if (log) {
3397 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3398 LLDB_LOG(log,
3399 "after DynamicLoader::DidAttach(), target "
3400 "executable is {0} (using {1} plugin)",
3401 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3402 dyld->GetPluginName());
3403 }
3404 }
3405
3407
3408 SystemRuntime *system_runtime = GetSystemRuntime();
3409 if (system_runtime) {
3410 system_runtime->DidAttach();
3411 if (log) {
3412 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3413 LLDB_LOG(log,
3414 "after SystemRuntime::DidAttach(), target "
3415 "executable is {0} (using {1} plugin)",
3416 exe_module_sp ? exe_module_sp->GetFileSpec() : FileSpec(),
3417 system_runtime->GetPluginName());
3418 }
3419 }
3420
3421 // If we don't have an operating system plugin loaded yet, see if
3422 // LoadOperatingSystemPlugin can find one (and stuff it in m_os_up).
3423 if (!m_os_up)
3425
3426 if (m_os_up) {
3427 // Somebody might have gotten threads before we loaded the OS Plugin above,
3428 // so we need to force the update now or the newly loaded plugin won't get
3429 // a chance to process the threads.
3430 m_thread_list.Clear();
3432 }
3433
3434 // Figure out which one is the executable, and set that in our target:
3435 ModuleSP new_executable_module_sp;
3436 for (ModuleSP module_sp : GetTarget().GetImages().Modules()) {
3437 if (module_sp && module_sp->IsExecutable()) {
3438 if (GetTarget().GetExecutableModulePointer() != module_sp.get())
3439 new_executable_module_sp = module_sp;
3440 break;
3441 }
3442 }
3443 if (new_executable_module_sp) {
3444 GetTarget().SetExecutableModule(new_executable_module_sp,
3446 if (log) {
3447 ModuleSP exe_module_sp = GetTarget().GetExecutableModule();
3448 LLDB_LOGF(
3449 log,
3450 "Process::%s after looping through modules, target executable is %s",
3451 __FUNCTION__,
3452 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
3453 : "<none>");
3454 }
3455 }
3456 // Since we hijacked the event stream, we will have we won't have run the
3457 // stop hooks. Make sure we do that here:
3458 GetTarget().RunStopHooks(/* at_initial_stop= */ true);
3459}
3460
3461Status Process::ConnectRemote(llvm::StringRef remote_url) {
3462 m_abi_sp.reset();
3463 {
3464 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3465 m_process_input_reader.reset();
3466 }
3467
3468 // Find the process and its architecture. Make sure it matches the
3469 // architecture of the current Target, and if not adjust it.
3470
3471 Status error(DoConnectRemote(remote_url));
3472 if (error.Success()) {
3473 if (GetID() != LLDB_INVALID_PROCESS_ID) {
3474 EventSP event_sp;
3475 StateType state = WaitForProcessStopPrivate(event_sp, std::nullopt);
3476
3477 if (state == eStateStopped || state == eStateCrashed) {
3478 // If we attached and actually have a process on the other end, then
3479 // this ended up being the equivalent of an attach.
3480 SetShouldDetach(true);
3482
3483 // This delays passing the stopped event to listeners till
3484 // CompleteAttach gets a chance to complete...
3485 HandlePrivateEvent(event_sp);
3486 }
3487 }
3488
3491 else {
3493 /*RunLock is stopped */ false);
3495 // We are not going to get any further here. The only way this
3496 // could fail is if we can't start a host thread, so we're pretty much
3497 // toast at that point.
3498 return Status::FromErrorString("could not start private state thread.");
3499 }
3500 }
3501 }
3502 return error;
3503}
3504
3506 if (m_base_direction == direction)
3507 return;
3508 m_thread_list.DiscardThreadPlans();
3509 m_base_direction = direction;
3510}
3511
3514 LLDB_LOGF(log,
3515 "Process::PrivateResume() m_stop_id = %u, public state: %s "
3516 "private state: %s",
3517 m_mod_id.GetStopID(), StateAsCString(GetPublicState()),
3519
3520 // If signals handing status changed we might want to update our signal
3521 // filters before resuming.
3523 // Clear any crash info we accumulated for this stop, but don't do so if we
3524 // are running functions; we don't want to wipe out the real stop's info.
3525 if (!GetModID().IsLastResumeForUserExpression())
3527
3529 // Tell the process it is about to resume before the thread list
3530 if (error.Success()) {
3531 // Now let the thread list know we are about to resume so it can let all of
3532 // our threads know that they are about to be resumed. Threads will each be
3533 // called with Thread::WillResume(StateType) where StateType contains the
3534 // state that they are supposed to have when the process is resumed
3535 // (suspended/running/stepping). Threads should also check their resume
3536 // signal in lldb::Thread::GetResumeSignal() to see if they are supposed to
3537 // start back up with a signal.
3538 RunDirection direction;
3539 if (m_thread_list.WillResume(direction)) {
3540 LLDB_LOGF(log, "Process::PrivateResume WillResume direction=%d",
3541 direction);
3542 // Last thing, do the PreResumeActions.
3543 if (!RunPreResumeActions()) {
3545 "Process::PrivateResume PreResumeActions failed, not resuming.");
3546 LLDB_LOGF(
3547 log,
3548 "Process::PrivateResume PreResumeActions failed, not resuming.");
3549 } else {
3550 m_mod_id.BumpResumeID();
3551 if (auto E = FlushDelayedBreakpoints())
3552 LLDB_LOG_ERROR(log, std::move(E),
3553 "Failed to update some delayed breakpoints: {0}");
3554 error = DoResume(direction);
3555 if (error.Success()) {
3556 DidResume();
3557 m_thread_list.DidResume();
3558 LLDB_LOGF(log,
3559 "Process::PrivateResume thinks the process has resumed.");
3560 } else {
3561 LLDB_LOGF(log, "Process::PrivateResume() DoResume failed.");
3562 return error;
3563 }
3564 }
3565 } else {
3566 // Somebody wanted to run without running (e.g. we were faking a step
3567 // from one frame of a set of inlined frames that share the same PC to
3568 // another.) So generate a continue & a stopped event, and let the world
3569 // handle them.
3570 LLDB_LOGF(log,
3571 "Process::PrivateResume() asked to simulate a start & stop.");
3572
3575 }
3576 } else
3577 LLDB_LOGF(log, "Process::PrivateResume() got an error \"%s\".",
3578 error.AsCString("<unknown error>"));
3579 return error;
3580}
3581
3582Status Process::Halt(bool clear_thread_plans, bool use_run_lock) {
3584 return Status::FromErrorString("Process is not running.");
3585
3586 // Don't clear the m_clear_thread_plans_on_stop, only set it to true if in
3587 // case it was already set and some thread plan logic calls halt on its own.
3588 m_clear_thread_plans_on_stop |= clear_thread_plans;
3589
3590 ListenerSP halt_listener_sp(
3591 Listener::MakeListener("lldb.process.halt_listener"));
3592 HijackProcessEvents(halt_listener_sp);
3593
3594 EventSP event_sp;
3595
3597
3599 // Don't hijack and eat the eStateExited as the code that was doing the
3600 // attach will be waiting for this event...
3602 Destroy(false);
3603 SetExitStatus(SIGKILL, "Cancelled async attach.");
3604 return Status();
3605 }
3606
3607 // Wait for the process halt timeout seconds for the process to stop.
3608 // If we are going to use the run lock, that means we're stopping out to the
3609 // user, so we should also select the most relevant frame.
3610 SelectMostRelevant select_most_relevant =
3612 StateType state = WaitForProcessToStop(GetInterruptTimeout(), &event_sp, true,
3613 halt_listener_sp, nullptr,
3614 use_run_lock, select_most_relevant);
3616
3617 if (state == eStateInvalid || !event_sp) {
3618 // We timed out and didn't get a stop event...
3619 return Status::FromErrorStringWithFormat("Halt timed out. State = %s",
3621 }
3622
3623 BroadcastEvent(event_sp);
3624
3625 return Status();
3626}
3627
3629 const uint8_t *buf, size_t size) {
3630 const size_t region_size = high - low;
3631
3632 if (region_size < size)
3633 return LLDB_INVALID_ADDRESS;
3634
3635 // See "Boyer-Moore string search algorithm".
3636 std::vector<size_t> bad_char_heuristic(256, size);
3637 for (size_t idx = 0; idx < size - 1; idx++) {
3638 decltype(bad_char_heuristic)::size_type bcu_idx = buf[idx];
3639 bad_char_heuristic[bcu_idx] = size - idx - 1;
3640 }
3641
3642 // Memory we're currently searching through.
3643 llvm::SmallVector<uint8_t, 0> mem;
3644 // Position of the memory buffer.
3645 addr_t mem_pos = low;
3646 // Maximum number of bytes read (and buffered). We need to read at least
3647 // `size` bytes for a successful match.
3648 const size_t max_read_size = std::max<size_t>(size, 0x10000);
3649
3650 for (addr_t cur_addr = low; cur_addr <= (high - size);) {
3651 if (cur_addr + size > mem_pos + mem.size()) {
3652 // We need to read more data. We don't attempt to reuse the data we've
3653 // already read (up to `size-1` bytes from `cur_addr` to
3654 // `mem_pos+mem.size()`). This is fine for patterns much smaller than
3655 // max_read_size. For very
3656 // long patterns we may need to do something more elaborate.
3657 mem.resize_for_overwrite(max_read_size);
3658 Status error;
3659 mem.resize(ReadMemory(cur_addr, mem.data(),
3660 std::min<addr_t>(mem.size(), high - cur_addr),
3661 error));
3662 mem_pos = cur_addr;
3663 if (size > mem.size()) {
3664 // We didn't read enough data. Skip to the next memory region.
3665 MemoryRegionInfo info;
3666 error = GetMemoryRegionInfo(mem_pos + mem.size(), info);
3667 if (error.Fail())
3668 break;
3669 cur_addr = info.GetRange().GetRangeEnd();
3670 continue;
3671 }
3672 }
3673 int64_t j = size - 1;
3674 while (j >= 0 && buf[j] == mem[cur_addr + j - mem_pos])
3675 j--;
3676 if (j < 0)
3677 return cur_addr; // We have a match.
3678 cur_addr += bad_char_heuristic[mem[cur_addr + size - 1 - mem_pos]];
3679 }
3680
3681 return LLDB_INVALID_ADDRESS;
3682}
3683
3685 Status error;
3686
3687 // Check both the public & private states here. If we're hung evaluating an
3688 // expression, for instance, then the public state will be stopped, but we
3689 // still need to interrupt.
3691 Log *log = GetLog(LLDBLog::Process);
3692 LLDB_LOGF(log, "Process::%s() About to stop.", __FUNCTION__);
3693
3694 ListenerSP listener_sp(
3695 Listener::MakeListener("lldb.Process.StopForDestroyOrDetach.hijack"));
3696 HijackProcessEvents(listener_sp);
3697
3699
3700 // Consume the interrupt event.
3702 &exit_event_sp, true, listener_sp);
3703
3705
3706 // If the process exited while we were waiting for it to stop, put the
3707 // exited event into the shared pointer passed in and return. Our caller
3708 // doesn't need to do anything else, since they don't have a process
3709 // anymore...
3710
3711 if (state == eStateExited || GetPrivateState() == eStateExited) {
3712 LLDB_LOGF(log, "Process::%s() Process exited while waiting to stop.",
3713 __FUNCTION__);
3714 return error;
3715 } else
3716 exit_event_sp.reset(); // It is ok to consume any non-exit stop events
3717
3718 if (state != eStateStopped) {
3719 LLDB_LOGF(log, "Process::%s() failed to stop, state is: %s", __FUNCTION__,
3720 StateAsCString(state));
3721 // If we really couldn't stop the process then we should just error out
3722 // here, but if the lower levels just bobbled sending the event and we
3723 // really are stopped, then continue on.
3724 StateType private_state = GetPrivateState();
3725 if (private_state != eStateStopped) {
3727 "Attempt to stop the target in order to detach timed out. "
3728 "State = %s",
3730 }
3731 }
3732 }
3733 return error;
3734}
3735
3736Status Process::Detach(bool keep_stopped) {
3737 EventSP exit_event_sp;
3738 Status error;
3739 m_destroy_in_process = true;
3740
3741 error = WillDetach();
3742
3743 if (error.Success()) {
3744 if (DetachRequiresHalt()) {
3745 error = StopForDestroyOrDetach(exit_event_sp);
3746 if (!error.Success()) {
3747 m_destroy_in_process = false;
3748 return error;
3749 } else if (exit_event_sp) {
3750 // We shouldn't need to do anything else here. There's no process left
3751 // to detach from...
3753 m_destroy_in_process = false;
3754 return error;
3755 }
3756 }
3757
3758 m_thread_list.DiscardThreadPlans();
3760 if (auto error = FlushDelayedBreakpoints())
3762 GetLog(LLDBLog::Process), std::move(error),
3763 "Failed to update some delayed breakpoints during detach: {0}");
3764
3765 error = DoDetach(keep_stopped);
3766 if (error.Success()) {
3767 DidDetach();
3769 } else {
3770 return error;
3771 }
3772 }
3773 m_destroy_in_process = false;
3774
3775 // If we exited when we were waiting for a process to stop, then forward the
3776 // event here so we don't lose the event
3777 if (exit_event_sp) {
3778 // Directly broadcast our exited event because we shut down our private
3779 // state thread above
3780 BroadcastEvent(exit_event_sp);
3781 }
3782
3783 // If we have been interrupted (to kill us) in the middle of running, we may
3784 // not end up propagating the last events through the event system, in which
3785 // case we might strand the write lock. Unlock it here so when we do to tear
3786 // down the process we don't get an error destroying the lock.
3787
3789 return error;
3790}
3791
3792Status Process::Destroy(bool force_kill) {
3793 // If we've already called Process::Finalize then there's nothing useful to
3794 // be done here. Finalize has actually called Destroy already.
3795 if (m_finalizing)
3796 return {};
3797 return DestroyImpl(force_kill);
3798}
3799
3801 // Tell ourselves we are in the process of destroying the process, so that we
3802 // don't do any unnecessary work that might hinder the destruction. Remember
3803 // to set this back to false when we are done. That way if the attempt
3804 // failed and the process stays around for some reason it won't be in a
3805 // confused state.
3806
3807 if (force_kill)
3808 m_should_detach = false;
3809
3810 if (GetShouldDetach()) {
3811 // FIXME: This will have to be a process setting:
3812 bool keep_stopped = false;
3813 Detach(keep_stopped);
3814 }
3815
3816 m_destroy_in_process = true;
3817
3819 if (error.Success()) {
3820 EventSP exit_event_sp;
3821 if (DestroyRequiresHalt()) {
3822 error = StopForDestroyOrDetach(exit_event_sp);
3823 }
3824
3825 if (GetPublicState() == eStateStopped) {
3826 // Ditch all thread plans, and remove all our breakpoints: in case we
3827 // have to restart the target to kill it, we don't want it hitting a
3828 // breakpoint... Only do this if we've stopped, however, since if we
3829 // didn't manage to halt it above, then we're not going to have much luck
3830 // doing this now.
3831 m_thread_list.DiscardThreadPlans();
3833 if (auto error = FlushDelayedBreakpoints())
3835 GetLog(LLDBLog::Process), std::move(error),
3836 "Failed to update some delayed breakpoints during destroy: {0}");
3837 }
3838
3839 error = DoDestroy();
3840 if (error.Success()) {
3841 DidDestroy();
3843 }
3844 m_stdio_communication.StopReadThread();
3845 m_stdio_communication.Disconnect();
3846 m_stdin_forward = false;
3847
3848 {
3849 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
3851 m_process_input_reader->SetIsDone(true);
3852 m_process_input_reader->Cancel();
3853 m_process_input_reader.reset();
3854 }
3855 }
3856
3857 // If we exited when we were waiting for a process to stop, then forward
3858 // the event here so we don't lose the event
3859 if (exit_event_sp) {
3860 // Directly broadcast our exited event because we shut down our private
3861 // state thread above
3862 BroadcastEvent(exit_event_sp);
3863 }
3864
3865 // If we have been interrupted (to kill us) in the middle of running, we
3866 // may not end up propagating the last events through the event system, in
3867 // which case we might strand the write lock. Unlock it here so when we do
3868 // to tear down the process we don't get an error destroying the lock.
3870 }
3871
3872 m_destroy_in_process = false;
3873
3874 return error;
3875}
3876
3879 if (error.Success()) {
3880 error = DoSignal(signal);
3881 if (error.Success())
3882 DidSignal();
3883 }
3884 return error;
3885}
3886
3888 assert(signals_sp && "null signals_sp");
3889 m_unix_signals_sp = std::move(signals_sp);
3890}
3891
3893 assert(m_unix_signals_sp && "null m_unix_signals_sp");
3894 return m_unix_signals_sp;
3895}
3896
3900
3904
3906 const StateType state =
3908 bool return_value = true;
3910
3911 switch (state) {
3912 case eStateDetached:
3913 case eStateExited:
3914 case eStateUnloaded:
3915 m_stdio_communication.SynchronizeWithReadThread();
3916 m_stdio_communication.StopReadThread();
3917 m_stdio_communication.Disconnect();
3918 m_stdin_forward = false;
3919
3920 [[fallthrough]];
3921 case eStateConnected:
3922 case eStateAttaching:
3923 case eStateLaunching:
3924 // These events indicate changes in the state of the debugging session,
3925 // always report them.
3926 return_value = true;
3927 break;
3928 case eStateInvalid:
3929 // We stopped for no apparent reason, don't report it.
3930 return_value = false;
3931 break;
3932 case eStateRunning:
3933 case eStateStepping:
3934 // If we've started the target running, we handle the cases where we are
3935 // already running and where there is a transition from stopped to running
3936 // differently. running -> running: Automatically suppress extra running
3937 // events stopped -> running: Report except when there is one or more no
3938 // votes
3939 // and no yes votes.
3942 return_value = true;
3943 else {
3944 switch (m_last_broadcast_state) {
3945 case eStateRunning:
3946 case eStateStepping:
3947 // We always suppress multiple runnings with no PUBLIC stop in between.
3948 return_value = false;
3949 break;
3950 default:
3951 // TODO: make this work correctly. For now always report
3952 // run if we aren't running so we don't miss any running events. If I
3953 // run the lldb/test/thread/a.out file and break at main.cpp:58, run
3954 // and hit the breakpoints on multiple threads, then somehow during the
3955 // stepping over of all breakpoints no run gets reported.
3956
3957 // This is a transition from stop to run.
3958 switch (m_thread_list.ShouldReportRun(event_ptr)) {
3959 case eVoteYes:
3960 case eVoteNoOpinion:
3961 return_value = true;
3962 break;
3963 case eVoteNo:
3964 return_value = false;
3965 break;
3966 }
3967 break;
3968 }
3969 }
3970 break;
3971 case eStateStopped:
3972 case eStateCrashed:
3973 case eStateSuspended:
3974 // We've stopped. First see if we're going to restart the target. If we
3975 // are going to stop, then we always broadcast the event. If we aren't
3976 // going to stop, let the thread plans decide if we're going to report this
3977 // event. If no thread has an opinion, we don't report it.
3978
3979 m_stdio_communication.SynchronizeWithReadThread();
3982 LLDB_LOGF(log,
3983 "Process::ShouldBroadcastEvent (%p) stopped due to an "
3984 "interrupt, state: %s",
3985 static_cast<void *>(event_ptr), StateAsCString(state));
3986 // Even though we know we are going to stop, we should let the threads
3987 // have a look at the stop, so they can properly set their state.
3988 m_thread_list.ShouldStop(event_ptr);
3989 return_value = true;
3990 } else {
3991 bool was_restarted = ProcessEventData::GetRestartedFromEvent(event_ptr);
3992 bool should_resume = false;
3993
3994 // It makes no sense to ask "ShouldStop" if we've already been
3995 // restarted... Asking the thread list is also not likely to go well,
3996 // since we are running again. So in that case just report the event.
3997
3998 if (!was_restarted)
3999 should_resume = !m_thread_list.ShouldStop(event_ptr);
4000
4001 if (was_restarted || should_resume || m_resume_requested) {
4002 Vote report_stop_vote = m_thread_list.ShouldReportStop(event_ptr);
4003 LLDB_LOGF(log,
4004 "Process::ShouldBroadcastEvent: should_resume: %i state: "
4005 "%s was_restarted: %i report_stop_vote: %d.",
4006 should_resume, StateAsCString(state), was_restarted,
4007 report_stop_vote);
4008
4009 switch (report_stop_vote) {
4010 case eVoteYes:
4011 return_value = true;
4012 break;
4013 case eVoteNoOpinion:
4014 case eVoteNo:
4015 return_value = false;
4016 break;
4017 }
4018
4019 if (!was_restarted) {
4020 LLDB_LOGF(log,
4021 "Process::ShouldBroadcastEvent (%p) Restarting process "
4022 "from state: %s",
4023 static_cast<void *>(event_ptr), StateAsCString(state));
4025 PrivateResume();
4026 }
4027 } else {
4028 return_value = true;
4030 }
4031 }
4032 break;
4033 }
4034
4035 // Forcing the next event delivery is a one shot deal. So reset it here.
4037
4038 // We do some coalescing of events (for instance two consecutive running
4039 // events get coalesced.) But we only coalesce against events we actually
4040 // broadcast. So we use m_last_broadcast_state to track that. NB - you
4041 // can't use "m_public_state.GetValue()" for that purpose, as was originally
4042 // done, because the PublicState reflects the last event pulled off the
4043 // queue, and there may be several events stacked up on the queue unserviced.
4044 // So the PublicState may not reflect the last broadcasted event yet.
4045 // m_last_broadcast_state gets updated here.
4046
4047 if (return_value)
4048 m_last_broadcast_state = state;
4049
4050 LLDB_LOGF(log,
4051 "Process::ShouldBroadcastEvent (%p) => new state: %s, last "
4052 "broadcast state: %s - %s",
4053 static_cast<void *>(event_ptr), StateAsCString(state),
4055 return_value ? "YES" : "NO");
4056 return return_value;
4057}
4058
4060 llvm::Expected<HostThread> private_state_thread =
4063 [this] { return m_process.RunPrivateStateThread(m_is_override); },
4064 8 * 1024 * 1024);
4065 if (!private_state_thread) {
4066 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), private_state_thread.takeError(),
4067 "failed to launch host thread: {0}");
4068 return false;
4069 }
4070
4071 assert(private_state_thread->IsJoinable());
4072 m_private_state_thread = *private_state_thread;
4073 m_is_running = true;
4074 m_process.ResumePrivateStateThread();
4075 return true;
4076}
4077
4079 return m_private_state_thread.EqualsThread(thread);
4080}
4081
4090
4092 lldb::StateType state, bool run_lock_is_running,
4093 std::shared_ptr<PrivateStateThread> *backup_ptr) {
4094 Log *log = GetLog(LLDBLog::Events);
4095
4096 bool already_running = PrivateStateThreadIsRunning();
4097 LLDB_LOGF(log, "Process::%s()%s ", __FUNCTION__,
4098 already_running ? " already running"
4099 : " starting private state thread");
4100
4101 if (backup_ptr == nullptr && already_running)
4102 return true;
4103
4104 // Create a thread that watches our internal state and controls which events
4105 // make it to clients (into the DCProcess event queue).
4106 char thread_name[1024];
4107 uint32_t max_len = llvm::get_max_thread_name_length();
4108 if (max_len > 0 && max_len <= 30) {
4109 // On platforms with abbreviated thread name lengths, choose thread names
4110 // that fit within the limit.
4111 if (already_running)
4112 snprintf(thread_name, sizeof(thread_name), "intern-state-OV");
4113 else
4114 snprintf(thread_name, sizeof(thread_name), "intern-state");
4115 } else {
4116 if (already_running)
4117 snprintf(thread_name, sizeof(thread_name),
4118 "<lldb.process.internal-state-override(pid=%" PRIu64 ")>",
4119 GetID());
4120 else
4121 snprintf(thread_name, sizeof(thread_name),
4122 "<lldb.process.internal-state(pid=%" PRIu64 ")>", GetID());
4123 }
4124
4125 if (backup_ptr) {
4126 // StartupThread expects the m_current_private_state_thread_sp to be in
4127 // place already, so do that first:
4130 *this, GetPublicState(), GetPrivateState(), thread_name,
4131 /*is_override=*/true));
4132 } else
4133 m_current_private_state_thread_sp->SetThreadName(thread_name);
4134
4135 SetPublicState(state, /*restarted=*/false);
4136 if (run_lock_is_running)
4138 else
4140
4141 return m_current_private_state_thread_sp->StartupThread();
4142}
4143
4147
4151
4154 return;
4155
4156 if (m_current_private_state_thread_sp->IsJoinable())
4158 else {
4159 Log *log = GetLog(LLDBLog::Process);
4160 LLDB_LOGF(
4161 log,
4162 "Went to stop the private state thread, but it was already invalid.");
4163 }
4164}
4165
4167 Log *log = GetLog(LLDBLog::Process);
4168
4169 assert(signal == eBroadcastInternalStateControlStop ||
4172
4173 LLDB_LOGF(log, "Process::%s (signal = %d)", __FUNCTION__, signal);
4174
4175 // Signal the private state thread
4176 if (m_current_private_state_thread_sp->IsJoinable()) {
4177 // Broadcast the event.
4178 // It is important to do this outside of the if below, because it's
4179 // possible that the thread state is invalid but that the thread is waiting
4180 // on a control event instead of simply being on its way out (this should
4181 // not happen, but it apparently can).
4182 LLDB_LOGF(log, "Sending control event of type: %d.", signal);
4183 std::shared_ptr<EventDataReceipt> event_receipt_sp(new EventDataReceipt());
4184 m_private_state_control_broadcaster.BroadcastEvent(signal,
4185 event_receipt_sp);
4186
4187 // Wait for the event receipt or for the private state thread to exit
4188 bool receipt_received = false;
4190 while (!receipt_received) {
4191 // Check for a receipt for n seconds and then check if the private
4192 // state thread is still around.
4193 receipt_received =
4194 event_receipt_sp->WaitForEventReceived(GetUtilityExpressionTimeout());
4195 if (!receipt_received) {
4196 // Check if the private state thread is still around. If it isn't
4197 // then we are done waiting
4199 break; // Private state thread exited or is exiting, we are done
4200 }
4201 }
4202 }
4203
4205 m_current_private_state_thread_sp->JoinAndReset();
4206
4207 } else {
4208 LLDB_LOGF(
4209 log,
4210 "Private state thread already dead, no need to signal it to stop.");
4211 }
4212}
4213
4215 if (thread != nullptr)
4216 m_interrupt_tid = thread->GetProtocolID();
4217 else
4221 nullptr);
4222 else
4224}
4225
4227 Log *log = GetLog(LLDBLog::Process);
4228 m_resume_requested = false;
4229
4230 const StateType new_state =
4232
4233 // First check to see if anybody wants a shot at this event:
4236 m_next_event_action_up->PerformAction(event_sp);
4237 LLDB_LOGF(log, "Ran next event action, result was %d.", action_result);
4238
4239 switch (action_result) {
4241 SetNextEventAction(nullptr);
4242 break;
4243
4245 break;
4246
4248 // Handle Exiting Here. If we already got an exited event, we should
4249 // just propagate it. Otherwise, swallow this event, and set our state
4250 // to exit so the next event will kill us.
4251 if (new_state != eStateExited) {
4252 // FIXME: should cons up an exited event, and discard this one.
4253 SetExitStatus(0, m_next_event_action_up->GetExitString());
4254 SetNextEventAction(nullptr);
4255 return;
4256 }
4257 SetNextEventAction(nullptr);
4258 break;
4259 }
4260 }
4261
4262 // See if we should broadcast this state to external clients?
4263 const bool should_broadcast = ShouldBroadcastEvent(event_sp.get());
4264
4265 if (should_broadcast) {
4266 const bool is_hijacked = IsHijackedForEvent(eBroadcastBitStateChanged);
4267 LLDB_LOGF(log,
4268 "Process::%s (pid = %" PRIu64
4269 ") broadcasting new state %s (old state %s) to %s",
4270 __FUNCTION__, GetID(), StateAsCString(new_state),
4271 StateAsCString(GetState()), is_hijacked ? "hijacked" : "public");
4273 if (StateIsRunningState(new_state)) {
4274 // Only push the input handler if we aren't fowarding events, as this
4275 // means the curses GUI is in use... Or don't push it if we are launching
4276 // since it will come up stopped.
4277 if (!GetTarget().GetDebugger().IsForwardingEvents() &&
4278 new_state != eStateLaunching && new_state != eStateAttaching) {
4280 m_iohandler_sync.SetValue(m_iohandler_sync.GetValue() + 1,
4282 LLDB_LOGF(log, "Process::%s updated m_iohandler_sync to %d",
4283 __FUNCTION__, m_iohandler_sync.GetValue());
4284 }
4285 } else if (StateIsStoppedState(new_state, false)) {
4287 // If the lldb_private::Debugger is handling the events, we don't want
4288 // to pop the process IOHandler here, we want to do it when we receive
4289 // the stopped event so we can carefully control when the process
4290 // IOHandler is popped because when we stop we want to display some
4291 // text stating how and why we stopped, then maybe some
4292 // process/thread/frame info, and then we want the "(lldb) " prompt to
4293 // show up. If we pop the process IOHandler here, then we will cause
4294 // the command interpreter to become the top IOHandler after the
4295 // process pops off and it will update its prompt right away... See the
4296 // Debugger.cpp file where it calls the function as
4297 // "process_sp->PopProcessIOHandler()" to see where I am talking about.
4298 // Otherwise we end up getting overlapping "(lldb) " prompts and
4299 // garbled output.
4300 //
4301 // If we aren't handling the events in the debugger (which is indicated
4302 // by "m_target.GetDebugger().IsHandlingEvents()" returning false) or
4303 // we are hijacked, then we always pop the process IO handler manually.
4304 // Hijacking happens when the internal process state thread is running
4305 // thread plans, or when commands want to run in synchronous mode and
4306 // they call "process->WaitForProcessToStop()". An example of something
4307 // that will hijack the events is a simple expression:
4308 //
4309 // (lldb) expr (int)puts("hello")
4310 //
4311 // This will cause the internal process state thread to resume and halt
4312 // the process (and _it_ will hijack the eBroadcastBitStateChanged
4313 // events) and we do need the IO handler to be pushed and popped
4314 // correctly.
4315
4316 if (is_hijacked || !GetTarget().GetDebugger().IsHandlingEvents())
4318 }
4319 }
4320
4321 BroadcastEvent(event_sp);
4322 } else {
4323 LLDB_LOGF(
4324 log,
4325 "Process::%s (pid = %" PRIu64
4326 ") suppressing state %s (old state %s): should_broadcast == false",
4327 __FUNCTION__, GetID(), StateAsCString(new_state),
4329 }
4330}
4331
4333 EventSP event_sp;
4335 if (error.Fail())
4336 return error;
4337
4338 // Ask the process subclass to actually halt our process
4339 bool caused_stop;
4340 error = DoHalt(caused_stop);
4341
4342 DidHalt();
4343 return error;
4344}
4345
4347 // Override PSTs exist solely to service RunThreadPlan expression evaluation.
4348 // They must see parent frames, not provider-augmented frames.
4349 std::optional<PolicyStack::Guard> policy_guard;
4350 if (is_override)
4351 policy_guard.emplace(Policy::PrivateState());
4352
4353 bool control_only = true;
4354
4355 Log *log = GetLog(LLDBLog::Process);
4356 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread starting...",
4357 __FUNCTION__, static_cast<void *>(this), GetID());
4358
4359 bool exit_now = false;
4360 bool interrupt_requested = false;
4361 while (!exit_now) {
4362 EventSP event_sp;
4363 GetEventsPrivate(event_sp, std::nullopt, control_only);
4364 if (event_sp->BroadcasterIs(&m_private_state_control_broadcaster)) {
4365 LLDB_LOGF(log,
4366 "Process::%s (arg = %p, pid = %" PRIu64
4367 ") got a control event: %d",
4368 __FUNCTION__, static_cast<void *>(this), GetID(),
4369 event_sp->GetType());
4370
4371 switch (event_sp->GetType()) {
4373 exit_now = true;
4374 break; // doing any internal state management below
4375
4377 control_only = true;
4378 break;
4379
4381 control_only = false;
4382 break;
4383 }
4384
4385 continue;
4386 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
4388 LLDB_LOGF(log,
4389 "Process::%s (arg = %p, pid = %" PRIu64
4390 ") woke up with an interrupt while attaching - "
4391 "forwarding interrupt.",
4392 __FUNCTION__, static_cast<void *>(this), GetID());
4393 // The server may be spinning waiting for a process to appear, in which
4394 // case we should tell it to stop doing that. Normally, we don't NEED
4395 // to do that because we will next close the communication to the stub
4396 // and that will get it to shut down. But there are remote debugging
4397 // cases where relying on that side-effect causes the shutdown to be
4398 // flakey, so we should send a positive signal to interrupt the wait.
4402 LLDB_LOGF(log,
4403 "Process::%s (arg = %p, pid = %" PRIu64
4404 ") woke up with an interrupt - Halting.",
4405 __FUNCTION__, static_cast<void *>(this), GetID());
4407 if (error.Fail() && log)
4408 LLDB_LOGF(log,
4409 "Process::%s (arg = %p, pid = %" PRIu64
4410 ") failed to halt the process: %s",
4411 __FUNCTION__, static_cast<void *>(this), GetID(),
4412 error.AsCString());
4413 // Halt should generate a stopped event. Make a note of the fact that
4414 // we were doing the interrupt, so we can set the interrupted flag
4415 // after we receive the event. We deliberately set this to true even if
4416 // HaltPrivate failed, so that we can interrupt on the next natural
4417 // stop.
4418 interrupt_requested = true;
4419 } else {
4420 // This can happen when someone (e.g. Process::Halt) sees that we are
4421 // running and sends an interrupt request, but the process actually
4422 // stops before we receive it. In that case, we can just ignore the
4423 // request. We use m_last_broadcast_state, because the Stopped event
4424 // may not have been popped of the event queue yet, which is when the
4425 // public state gets updated.
4426 LLDB_LOGF(log,
4427 "Process::%s ignoring interrupt as we have already stopped.",
4428 __FUNCTION__);
4429 }
4430 continue;
4431 }
4432
4433 const StateType internal_state =
4435
4436 if (internal_state != eStateInvalid) {
4438 StateIsStoppedState(internal_state, true)) {
4440 m_thread_list.DiscardThreadPlans();
4441 }
4442
4443 if (interrupt_requested) {
4444 if (StateIsStoppedState(internal_state, true)) {
4445 // Only mark interrupt event if it is not thread specific async
4446 // interrupt.
4448 // We requested the interrupt, so mark this as such in the stop
4449 // event so clients can tell an interrupted process from a natural
4450 // stop
4451 ProcessEventData::SetInterruptedInEvent(event_sp.get(), true);
4452 }
4453 interrupt_requested = false;
4454 } else {
4455 LLDB_LOGF(log,
4456 "Process::%s interrupt_requested, but a non-stopped "
4457 "state '%s' received.",
4458 __FUNCTION__, StateAsCString(internal_state));
4459 }
4460 }
4461
4462 HandlePrivateEvent(event_sp);
4463 }
4464
4465 if (internal_state == eStateInvalid || internal_state == eStateExited ||
4466 internal_state == eStateDetached) {
4467 LLDB_LOGF(log,
4468 "Process::%s (arg = %p, pid = %" PRIu64
4469 ") about to exit with internal state %s...",
4470 __FUNCTION__, static_cast<void *>(this), GetID(),
4471 StateAsCString(internal_state));
4472
4473 break;
4474 }
4475 }
4476
4477 // Verify log is still enabled before attempting to write to it...
4478 LLDB_LOGF(log, "Process::%s (arg = %p, pid = %" PRIu64 ") thread exiting...",
4479 __FUNCTION__, static_cast<void *>(this), GetID());
4480
4482 return {};
4483}
4484
4485// Process Event Data
4486
4488
4490 StateType state)
4491 : EventData(), m_process_wp(), m_state(state) {
4492 if (process_sp)
4493 m_process_wp = process_sp;
4494}
4495
4497
4499 return "Process::ProcessEventData";
4500}
4501
4505
4507 bool &found_valid_stopinfo) {
4508 found_valid_stopinfo = false;
4509
4510 ProcessSP process_sp(m_process_wp.lock());
4511 if (!process_sp)
4512 return false;
4513
4514 ThreadList &curr_thread_list = process_sp->GetThreadList();
4515 uint32_t num_threads = curr_thread_list.GetSize();
4516
4517 // The actions might change one of the thread's stop_info's opinions about
4518 // whether we should stop the process, so we need to query that as we go.
4519
4520 // One other complication here, is that we try to catch any case where the
4521 // target has run (except for expressions) and immediately exit, but if we
4522 // get that wrong (which is possible) then the thread list might have
4523 // changed, and that would cause our iteration here to crash. We could
4524 // make a copy of the thread list, but we'd really like to also know if it
4525 // has changed at all, so we store the original thread ID's of all threads and
4526 // check what we get back against this list & bag out if anything differs.
4527 std::vector<std::pair<ThreadSP, size_t>> not_suspended_threads;
4528 for (uint32_t idx = 0; idx < num_threads; ++idx) {
4529 lldb::ThreadSP thread_sp = curr_thread_list.GetThreadAtIndex(idx);
4530
4531 /*
4532 Filter out all suspended threads, they could not be the reason
4533 of stop and no need to perform any actions on them.
4534 */
4535 if (thread_sp->GetResumeState() != eStateSuspended)
4536 not_suspended_threads.emplace_back(thread_sp, thread_sp->GetIndexID());
4537 }
4538
4539 // Use this to track whether we should continue from here. We will only
4540 // continue the target running if no thread says we should stop. Of course
4541 // if some thread's PerformAction actually sets the target running, then it
4542 // doesn't matter what the other threads say...
4543
4544 bool still_should_stop = false;
4545
4546 // Sometimes - for instance if we have a bug in the stub we are talking to,
4547 // we stop but no thread has a valid stop reason. In that case we should
4548 // just stop, because we have no way of telling what the right thing to do
4549 // is, and it's better to let the user decide than continue behind their
4550 // backs.
4551
4552 for (auto [thread_sp, thread_index] : not_suspended_threads) {
4553 if (curr_thread_list.GetSize() != num_threads) {
4555 LLDB_LOGF(
4556 log,
4557 "Number of threads changed from %u to %u while processing event.",
4558 num_threads, curr_thread_list.GetSize());
4559 break;
4560 }
4561
4562 if (thread_sp->GetIndexID() != thread_index) {
4564 LLDB_LOG(log,
4565 "The thread {0} changed from {1} to {2} while processing event.",
4566 thread_sp.get(), thread_index, thread_sp->GetIndexID());
4567 break;
4568 }
4569
4570 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
4571 if (stop_info_sp && stop_info_sp->IsValid()) {
4572 found_valid_stopinfo = true;
4573 bool this_thread_wants_to_stop;
4574 if (stop_info_sp->GetOverrideShouldStop()) {
4575 this_thread_wants_to_stop =
4576 stop_info_sp->GetOverriddenShouldStopValue();
4577 } else {
4578 stop_info_sp->PerformAction(event_ptr);
4579 // The stop action might restart the target. If it does, then we
4580 // want to mark that in the event so that whoever is receiving it
4581 // will know to wait for the running event and reflect that state
4582 // appropriately. We also need to stop processing actions, since they
4583 // aren't expecting the target to be running.
4584
4585 // Clear the selected frame which may have been set as part of utility
4586 // expressions that have been run as part of this stop. If we didn't
4587 // clear this, then StopInfo::GetSuggestedStackFrameIndex would not
4588 // take affect when we next called SelectMostRelevantFrame.
4589 // PerformAction should not be the one setting a selected frame, instead
4590 // this should be done via GetSuggestedStackFrameIndex.
4591 thread_sp->ClearSelectedFrameIndex();
4592
4593 // FIXME: we might have run.
4594 if (stop_info_sp->HasTargetRunSinceMe()) {
4595 SetRestarted(true);
4596 break;
4597 }
4598
4599 this_thread_wants_to_stop = stop_info_sp->ShouldStop(event_ptr);
4600 }
4601
4602 if (!still_should_stop)
4603 still_should_stop = this_thread_wants_to_stop;
4604 }
4605 }
4606
4607 return still_should_stop;
4608}
4609
4611 Event *event_ptr) {
4612 // STDIO and the other async event notifications should always be forwarded.
4613 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4614 return true;
4615
4616 // For state changed events, if the update state is zero, we are handling
4617 // this on the private state thread. We should wait for the public event.
4618 // After the primary listener processes it in DoOnRemoval, m_update_state
4619 // is incremented from 1 to 2, which is when we forward to pending
4620 // (secondary) listeners.
4621 return m_update_state > 1;
4622}
4623
4625 // We only have work to do for state changed events:
4626 if (event_ptr->GetType() != Process::eBroadcastBitStateChanged)
4627 return;
4628
4629 ProcessSP process_sp(m_process_wp.lock());
4630
4631 if (!process_sp)
4632 return;
4633
4634 // This function gets called twice for each event, once when the event gets
4635 // pulled off of the private process event queue, and then any number of
4636 // times, first when it gets pulled off of the public event queue, then other
4637 // times when we're pretending that this is where we stopped at the end of
4638 // expression evaluation. m_update_state is used to distinguish these
4639 // cases; it is 0 when we're just pulling it off for private handling, 1
4640 // when the primary public listener consumes it, and > 1 after that (e.g.
4641 // secondary listeners or expression evaluation) where we don't want to
4642 // redo the breakpoint command handling or stop hooks.
4643 if (m_update_state != 1)
4644 return;
4646
4647 process_sp->SetPublicState(
4649
4650 if (m_state == eStateStopped && !m_restarted) {
4651 // Let process subclasses know we are about to do a public stop and do
4652 // anything they might need to in order to speed up register and memory
4653 // accesses.
4654 process_sp->WillPublicStop();
4655 }
4656
4657 // If this is a halt event, even if the halt stopped with some reason other
4658 // than a plain interrupt (e.g. we had already stopped for a breakpoint when
4659 // the halt request came through) don't do the StopInfo actions, as they may
4660 // end up restarting the process.
4661 if (m_interrupted)
4662 return;
4663
4664 // If we're not stopped or have restarted, then skip the StopInfo actions:
4665 if (m_state != eStateStopped || m_restarted) {
4666 return;
4667 }
4668
4669 bool does_anybody_have_an_opinion = false;
4670 bool still_should_stop = ShouldStop(event_ptr, does_anybody_have_an_opinion);
4671
4672 if (GetRestarted()) {
4673 return;
4674 }
4675
4676 if (!still_should_stop && does_anybody_have_an_opinion) {
4677 // We've been asked to continue, so do that here.
4678 SetRestarted(true);
4679 // Use the private resume method here, since we aren't changing the run
4680 // lock state.
4681 process_sp->PrivateResume();
4682 } else {
4683 bool hijacked = process_sp->IsHijackedForEvent(eBroadcastBitStateChanged) &&
4684 !process_sp->StateChangedIsHijackedForSynchronousResume();
4685
4686 if (!hijacked) {
4687 // If we didn't restart, run the Stop Hooks here.
4688 // Don't do that if state changed events aren't hooked up to the
4689 // public (or SyncResume) broadcasters. StopHooks are just for
4690 // real public stops. They might also restart the target,
4691 // so watch for that.
4692 if (process_sp->GetTarget().RunStopHooks())
4693 SetRestarted(true);
4694 }
4695 }
4696}
4697
4699 ProcessSP process_sp(m_process_wp.lock());
4700
4701 if (process_sp)
4702 s->Printf(" process = %p (pid = %" PRIu64 "), ",
4703 static_cast<void *>(process_sp.get()), process_sp->GetID());
4704 else
4705 s->PutCString(" process = NULL, ");
4706
4707 s->Printf("state = %s", StateAsCString(GetState()));
4708}
4709
4712 if (event_ptr) {
4713 const EventData *event_data = event_ptr->GetData();
4714 if (event_data &&
4716 return static_cast<const ProcessEventData *>(event_ptr->GetData());
4717 }
4718 return nullptr;
4719}
4720
4723 ProcessSP process_sp;
4724 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4725 if (data)
4726 process_sp = data->GetProcessSP();
4727 return process_sp;
4728}
4729
4731 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4732 if (data == nullptr)
4733 return eStateInvalid;
4734 else
4735 return data->GetState();
4736}
4737
4739 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4740 if (data == nullptr)
4741 return false;
4742 else
4743 return data->GetRestarted();
4744}
4745
4747 bool new_value) {
4748 ProcessEventData *data =
4749 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4750 if (data != nullptr)
4751 data->SetRestarted(new_value);
4752}
4753
4754size_t
4756 ProcessEventData *data =
4757 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4758 if (data != nullptr)
4759 return data->GetNumRestartedReasons();
4760 else
4761 return 0;
4762}
4763
4764const char *
4766 size_t idx) {
4767 ProcessEventData *data =
4768 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4769 if (data != nullptr)
4770 return data->GetRestartedReasonAtIndex(idx);
4771 else
4772 return nullptr;
4773}
4774
4776 const char *reason) {
4777 ProcessEventData *data =
4778 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4779 if (data != nullptr)
4780 data->AddRestartedReason(reason);
4781}
4782
4784 const Event *event_ptr) {
4785 const ProcessEventData *data = GetEventDataFromEvent(event_ptr);
4786 if (data == nullptr)
4787 return false;
4788 else
4789 return data->GetInterrupted();
4790}
4791
4793 bool new_value) {
4794 ProcessEventData *data =
4795 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4796 if (data != nullptr)
4797 data->SetInterrupted(new_value);
4798}
4799
4801 ProcessEventData *data =
4802 const_cast<ProcessEventData *>(GetEventDataFromEvent(event_ptr));
4803 if (data) {
4805 return true;
4806 }
4807 return false;
4808}
4809
4811
4813 exe_ctx.SetTargetPtr(&GetTarget());
4814 exe_ctx.SetProcessPtr(this);
4815 exe_ctx.SetThreadPtr(nullptr);
4816 exe_ctx.SetFramePtr(nullptr);
4817}
4818
4819// uint32_t
4820// Process::ListProcessesMatchingName (const char *name, StringList &matches,
4821// std::vector<lldb::pid_t> &pids)
4822//{
4823// return 0;
4824//}
4825//
4826// ArchSpec
4827// Process::GetArchSpecForExistingProcess (lldb::pid_t pid)
4828//{
4829// return Host::GetArchSpecForExistingProcess (pid);
4830//}
4831//
4832// ArchSpec
4833// Process::GetArchSpecForExistingProcess (const char *process_name)
4834//{
4835// return Host::GetArchSpecForExistingProcess (process_name);
4836//}
4837
4839 auto event_data_sp =
4840 std::make_shared<ProcessEventData>(shared_from_this(), GetState());
4841 return std::make_shared<Event>(event_type, event_data_sp);
4842}
4843
4844void Process::AppendSTDOUT(const char *s, size_t len) {
4845 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4846 m_stdout_data.append(s, len);
4848 BroadcastEventIfUnique(event_sp);
4849}
4850
4851void Process::AppendSTDERR(const char *s, size_t len) {
4852 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4853 m_stderr_data.append(s, len);
4855 BroadcastEventIfUnique(event_sp);
4856}
4857
4858void Process::BroadcastAsyncProfileData(const std::string &one_profile_data) {
4859 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4860 m_profile_data.push_back(one_profile_data);
4862 BroadcastEventIfUnique(event_sp);
4863}
4864
4866 const StructuredDataPluginSP &plugin_sp) {
4867 auto data_sp = std::make_shared<EventDataStructuredData>(
4868 shared_from_this(), object_sp, plugin_sp);
4870}
4871
4873Process::GetStructuredDataPlugin(llvm::StringRef type_name) const {
4874 auto find_it = m_structured_data_plugin_map.find(type_name);
4875 if (find_it != m_structured_data_plugin_map.end())
4876 return find_it->second;
4877 else
4878 return StructuredDataPluginSP();
4879}
4880
4881size_t Process::GetAsyncProfileData(char *buf, size_t buf_size, Status &error) {
4882 std::lock_guard<std::recursive_mutex> guard(m_profile_data_comm_mutex);
4883 if (m_profile_data.empty())
4884 return 0;
4885
4886 std::string &one_profile_data = m_profile_data.front();
4887 size_t bytes_available = one_profile_data.size();
4888 if (bytes_available > 0) {
4889 Log *log = GetLog(LLDBLog::Process);
4890 LLDB_LOGF(log, "Process::GetProfileData (buf = %p, size = %" PRIu64 ")",
4891 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4892 if (bytes_available > buf_size) {
4893 memcpy(buf, one_profile_data.c_str(), buf_size);
4894 one_profile_data.erase(0, buf_size);
4895 bytes_available = buf_size;
4896 } else {
4897 memcpy(buf, one_profile_data.c_str(), bytes_available);
4898 m_profile_data.erase(m_profile_data.begin());
4899 }
4900 }
4901 return bytes_available;
4902}
4903
4904// Process STDIO
4905
4906size_t Process::GetSTDOUT(char *buf, size_t buf_size, Status &error) {
4907 std::lock_guard<std::recursive_mutex> guard(m_stdio_communication_mutex);
4908 size_t bytes_available = m_stdout_data.size();
4909 if (bytes_available > 0) {
4910 Log *log = GetLog(LLDBLog::Process);
4911 LLDB_LOGF(log, "Process::GetSTDOUT (buf = %p, size = %" PRIu64 ")",
4912 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4913 if (bytes_available > buf_size) {
4914 memcpy(buf, m_stdout_data.c_str(), buf_size);
4915 m_stdout_data.erase(0, buf_size);
4916 bytes_available = buf_size;
4917 } else {
4918 memcpy(buf, m_stdout_data.c_str(), bytes_available);
4919 m_stdout_data.clear();
4920 }
4921 }
4922 return bytes_available;
4923}
4924
4925size_t Process::GetSTDERR(char *buf, size_t buf_size, Status &error) {
4926 std::lock_guard<std::recursive_mutex> gaurd(m_stdio_communication_mutex);
4927 size_t bytes_available = m_stderr_data.size();
4928 if (bytes_available > 0) {
4929 Log *log = GetLog(LLDBLog::Process);
4930 LLDB_LOGF(log, "Process::GetSTDERR (buf = %p, size = %" PRIu64 ")",
4931 static_cast<void *>(buf), static_cast<uint64_t>(buf_size));
4932 if (bytes_available > buf_size) {
4933 memcpy(buf, m_stderr_data.c_str(), buf_size);
4934 m_stderr_data.erase(0, buf_size);
4935 bytes_available = buf_size;
4936 } else {
4937 memcpy(buf, m_stderr_data.c_str(), bytes_available);
4938 m_stderr_data.clear();
4939 }
4940 }
4941 return bytes_available;
4942}
4943
4944void Process::STDIOReadThreadBytesReceived(void *baton, const void *src,
4945 size_t src_len) {
4946 Process *process = (Process *)baton;
4947 process->AppendSTDOUT(static_cast<const char *>(src), src_len);
4948}
4949
4951public:
4952 IOHandlerProcessSTDIO(Process *process, int write_fd)
4953 : IOHandler(process->GetTarget().GetDebugger(),
4955 m_process(process),
4956 m_read_file(GetInputFD(), File::eOpenOptionReadOnly, false),
4957 m_write_file(write_fd, File::eOpenOptionWriteOnly, false) {
4958 m_pipe.CreateNew();
4959 }
4960
4961 ~IOHandlerProcessSTDIO() override = default;
4962
4963 void SetIsRunning(bool running) {
4964 std::lock_guard<std::mutex> guard(m_mutex);
4965 SetIsDone(!running);
4966 m_is_running = running;
4967 }
4968
4969 // Each IOHandler gets to run until it is done. It should read data from the
4970 // "in" and place output into "out" and "err and return when done.
4971 void Run() override {
4972 if (!m_read_file.IsValid() || !m_write_file.IsValid() ||
4973 !m_pipe.CanRead() || !m_pipe.CanWrite()) {
4974 SetIsDone(true);
4975 return;
4976 }
4977
4978 SetIsDone(false);
4979 const int read_fd = m_read_file.GetDescriptor();
4980 Terminal terminal(read_fd);
4981 TerminalState terminal_state(terminal, false);
4982 // FIXME: error handling?
4983 llvm::consumeError(terminal.SetCanonical(false));
4984 llvm::consumeError(terminal.SetEcho(false));
4985// FD_ZERO, FD_SET are not supported on windows
4986#ifndef _WIN32
4987 const int pipe_read_fd = m_pipe.GetReadFileDescriptor();
4988 SetIsRunning(true);
4989 while (true) {
4990 {
4991 std::lock_guard<std::mutex> guard(m_mutex);
4992 if (GetIsDone())
4993 break;
4994 }
4995
4996 SelectHelper select_helper;
4997 select_helper.FDSetRead(read_fd);
4998 select_helper.FDSetRead(pipe_read_fd);
4999 Status error = select_helper.Select();
5000
5001 if (error.Fail())
5002 break;
5003
5004 char ch = 0;
5005 size_t n;
5006 if (select_helper.FDIsSetRead(read_fd)) {
5007 n = 1;
5008 if (m_read_file.Read(&ch, n).Success() && n == 1) {
5009 if (m_write_file.Write(&ch, n).Fail() || n != 1)
5010 break;
5011 } else
5012 break;
5013 }
5014
5015 if (select_helper.FDIsSetRead(pipe_read_fd)) {
5016 // Consume the interrupt byte
5017 if (llvm::Expected<size_t> bytes_read = m_pipe.Read(&ch, 1)) {
5018 if (ch == 'q')
5019 break;
5020 if (ch == 'i')
5021 if (StateIsRunningState(m_process->GetState()))
5022 m_process->SendAsyncInterrupt();
5023 } else {
5024 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), bytes_read.takeError(),
5025 "Pipe read failed: {0}");
5026 }
5027 }
5028 }
5029 SetIsRunning(false);
5030#endif
5031 }
5032
5033 void Cancel() override {
5034 std::lock_guard<std::mutex> guard(m_mutex);
5035 SetIsDone(true);
5036 // Only write to our pipe to cancel if we are in
5037 // IOHandlerProcessSTDIO::Run(). We can end up with a python command that
5038 // is being run from the command interpreter:
5039 //
5040 // (lldb) step_process_thousands_of_times
5041 //
5042 // In this case the command interpreter will be in the middle of handling
5043 // the command and if the process pushes and pops the IOHandler thousands
5044 // of times, we can end up writing to m_pipe without ever consuming the
5045 // bytes from the pipe in IOHandlerProcessSTDIO::Run() and end up
5046 // deadlocking when the pipe gets fed up and blocks until data is consumed.
5047 if (m_is_running) {
5048 char ch = 'q'; // Send 'q' for quit
5049 if (llvm::Error err = m_pipe.Write(&ch, 1).takeError()) {
5050 LLDB_LOG_ERROR(GetLog(LLDBLog::Process), std::move(err),
5051 "Pipe write failed: {0}");
5052 }
5053 }
5054 }
5055
5056 bool Interrupt() override {
5057 // Do only things that are safe to do in an interrupt context (like in a
5058 // SIGINT handler), like write 1 byte to a file descriptor. This will
5059 // interrupt the IOHandlerProcessSTDIO::Run() and we can look at the byte
5060 // that was written to the pipe and then call
5061 // m_process->SendAsyncInterrupt() from a much safer location in code.
5062 if (m_active) {
5063 char ch = 'i'; // Send 'i' for interrupt
5064 return !errorToBool(m_pipe.Write(&ch, 1).takeError());
5065 } else {
5066 // This IOHandler might be pushed on the stack, but not being run
5067 // currently so do the right thing if we aren't actively watching for
5068 // STDIN by sending the interrupt to the process. Otherwise the write to
5069 // the pipe above would do nothing. This can happen when the command
5070 // interpreter is running and gets a "expression ...". It will be on the
5071 // IOHandler thread and sending the input is complete to the delegate
5072 // which will cause the expression to run, which will push the process IO
5073 // handler, but not run it.
5074
5075 if (StateIsRunningState(m_process->GetState())) {
5076 m_process->SendAsyncInterrupt();
5077 return true;
5078 }
5079 }
5080 return false;
5081 }
5082
5083 void GotEOF() override {}
5084
5085protected:
5087 NativeFile m_read_file; // Read from this file (usually actual STDIN for LLDB
5088 NativeFile m_write_file; // Write to this file (usually the primary pty for
5089 // getting io to debuggee)
5091 std::mutex m_mutex;
5092 bool m_is_running = false;
5093};
5094
5096 // First set up the Read Thread for reading/handling process I/O
5097 m_stdio_communication.SetConnection(
5098 std::make_unique<ConnectionFileDescriptor>(fd, true));
5099 if (m_stdio_communication.IsConnected()) {
5100 m_stdio_communication.SetReadThreadBytesReceivedCallback(
5102 m_stdio_communication.StartReadThread();
5103
5104 // Now read thread is set up, set up input reader.
5105 {
5106 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5109 std::make_shared<IOHandlerProcessSTDIO>(this, fd);
5110 }
5111 }
5112}
5113
5115 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5116 IOHandlerSP io_handler_sp(m_process_input_reader);
5117 if (io_handler_sp)
5118 return GetTarget().GetDebugger().IsTopIOHandler(io_handler_sp);
5119 return false;
5120}
5121
5123 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5124 IOHandlerSP io_handler_sp(m_process_input_reader);
5125 if (io_handler_sp) {
5126 Log *log = GetLog(LLDBLog::Process);
5127 LLDB_LOGF(log, "Process::%s pushing IO handler", __FUNCTION__);
5128
5129 io_handler_sp->SetIsDone(false);
5130 // If we evaluate an utility function, then we don't cancel the current
5131 // IOHandler. Our IOHandler is non-interactive and shouldn't disturb the
5132 // existing IOHandler that potentially provides the user interface (e.g.
5133 // the IOHandler for Editline).
5134 bool cancel_top_handler = !m_mod_id.IsRunningUtilityFunction();
5135 GetTarget().GetDebugger().RunIOHandlerAsync(io_handler_sp,
5136 cancel_top_handler);
5137 return true;
5138 }
5139 return false;
5140}
5141
5143 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
5144 IOHandlerSP io_handler_sp(m_process_input_reader);
5145 if (io_handler_sp)
5146 return GetTarget().GetDebugger().RemoveIOHandler(io_handler_sp);
5147 return false;
5148}
5149
5150// The process needs to know about installed plug-ins
5152
5154
5155namespace {
5156// RestorePlanState is used to record the "is private", "is controlling" and
5157// "okay
5158// to discard" fields of the plan we are running, and reset it on Clean or on
5159// destruction. It will only reset the state once, so you can call Clean and
5160// then monkey with the state and it won't get reset on you again.
5161
5162class RestorePlanState {
5163public:
5164 RestorePlanState(lldb::ThreadPlanSP thread_plan_sp)
5165 : m_thread_plan_sp(thread_plan_sp) {
5166 if (m_thread_plan_sp) {
5167 m_private = m_thread_plan_sp->GetPrivate();
5168 m_is_controlling = m_thread_plan_sp->IsControllingPlan();
5169 m_okay_to_discard = m_thread_plan_sp->OkayToDiscard();
5170 }
5171 }
5172
5173 ~RestorePlanState() { Clean(); }
5174
5175 void Clean() {
5176 if (!m_already_reset && m_thread_plan_sp) {
5177 m_already_reset = true;
5178 m_thread_plan_sp->SetPrivate(m_private);
5179 m_thread_plan_sp->SetIsControllingPlan(m_is_controlling);
5180 m_thread_plan_sp->SetOkayToDiscard(m_okay_to_discard);
5181 }
5182 }
5183
5184private:
5185 lldb::ThreadPlanSP m_thread_plan_sp;
5186 bool m_already_reset = false;
5187 bool m_private = false;
5188 bool m_is_controlling = false;
5189 bool m_okay_to_discard = false;
5190};
5191} // anonymous namespace
5192
5193static microseconds
5195 const milliseconds default_one_thread_timeout(250);
5196
5197 // If the overall wait is forever, then we don't need to worry about it.
5198 if (!options.GetTimeout()) {
5199 return options.GetOneThreadTimeout() ? *options.GetOneThreadTimeout()
5200 : default_one_thread_timeout;
5201 }
5202
5203 // If the one thread timeout is set, use it.
5204 if (options.GetOneThreadTimeout())
5205 return *options.GetOneThreadTimeout();
5206
5207 // Otherwise use half the total timeout, bounded by the
5208 // default_one_thread_timeout.
5209 return std::min<microseconds>(default_one_thread_timeout,
5210 *options.GetTimeout() / 2);
5211}
5212
5213static Timeout<std::micro>
5215 bool before_first_timeout) {
5216 // If we are going to run all threads the whole time, or if we are only going
5217 // to run one thread, we can just return the overall timeout.
5218 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5219 return options.GetTimeout();
5220
5221 if (before_first_timeout)
5222 return GetOneThreadExpressionTimeout(options);
5223
5224 if (!options.GetTimeout())
5225 return std::nullopt;
5226 else
5227 return *options.GetTimeout() - GetOneThreadExpressionTimeout(options);
5228}
5229
5230static std::optional<ExpressionResults>
5231HandleStoppedEvent(lldb::tid_t thread_id, const ThreadPlanSP &thread_plan_sp,
5232 RestorePlanState &restorer, const EventSP &event_sp,
5233 EventSP &event_to_broadcast_sp,
5234 const EvaluateExpressionOptions &options,
5235 bool handle_interrupts) {
5237
5238 ThreadSP thread_sp = thread_plan_sp->GetTarget()
5239 .GetProcessSP()
5240 ->GetThreadList()
5241 .FindThreadByID(thread_id);
5242 if (!thread_sp) {
5243 LLDB_LOG(log,
5244 "The thread on which we were running the "
5245 "expression: tid = {0}, exited while "
5246 "the expression was running.",
5247 thread_id);
5249 }
5250
5251 ThreadPlanSP plan = thread_sp->GetCompletedPlan();
5252 if (plan == thread_plan_sp && plan->PlanSucceeded()) {
5253 LLDB_LOG(log, "execution completed successfully");
5254
5255 // Restore the plan state so it will get reported as intended when we are
5256 // done.
5257 restorer.Clean();
5258 return eExpressionCompleted;
5259 }
5260
5261 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
5262 if (stop_info_sp && stop_info_sp->GetStopReason() == eStopReasonBreakpoint &&
5263 stop_info_sp->ShouldNotify(event_sp.get())) {
5264 LLDB_LOG(log, "stopped for breakpoint: {0}.", stop_info_sp->GetDescription());
5265 if (!options.DoesIgnoreBreakpoints()) {
5266 // Restore the plan state and then force Private to false. We are going
5267 // to stop because of this plan so we need it to become a public plan or
5268 // it won't report correctly when we continue to its termination later
5269 // on.
5270 restorer.Clean();
5271 thread_plan_sp->SetPrivate(false);
5272 event_to_broadcast_sp = event_sp;
5273 }
5275 }
5276
5277 if (!handle_interrupts &&
5279 return std::nullopt;
5280
5281 LLDB_LOG(log, "thread plan did not successfully complete");
5282 if (!options.DoesUnwindOnError())
5283 event_to_broadcast_sp = event_sp;
5285}
5286
5289 lldb::ThreadPlanSP &thread_plan_sp,
5290 const EvaluateExpressionOptions &options,
5291 DiagnosticManager &diagnostic_manager) {
5293
5294 std::lock_guard<std::mutex> run_thread_plan_locker(m_run_thread_plan_lock);
5295
5296 if (!thread_plan_sp) {
5297 diagnostic_manager.PutString(
5298 lldb::eSeverityError, "RunThreadPlan called with empty thread plan.");
5299 return eExpressionSetupError;
5300 }
5301
5302 if (!thread_plan_sp->ValidatePlan(nullptr)) {
5303 diagnostic_manager.PutString(
5305 "RunThreadPlan called with an invalid thread plan.");
5306 return eExpressionSetupError;
5307 }
5308
5309 if (exe_ctx.GetProcessPtr() != this) {
5310 diagnostic_manager.PutString(lldb::eSeverityError,
5311 "RunThreadPlan called on wrong process.");
5312 return eExpressionSetupError;
5313 }
5314
5315 Thread *thread = exe_ctx.GetThreadPtr();
5316 if (thread == nullptr) {
5317 diagnostic_manager.PutString(lldb::eSeverityError,
5318 "RunThreadPlan called with invalid thread.");
5319 return eExpressionSetupError;
5320 }
5321
5322 // Record the thread's id so we can tell when a thread we were using
5323 // to run the expression exits during the expression evaluation.
5324 lldb::tid_t expr_thread_id = thread->GetID();
5325
5326 // We need to change some of the thread plan attributes for the thread plan
5327 // runner. This will restore them when we are done:
5328
5329 RestorePlanState thread_plan_restorer(thread_plan_sp);
5330
5331 // We rely on the thread plan we are running returning "PlanCompleted" if
5332 // when it successfully completes. For that to be true the plan can't be
5333 // private - since private plans suppress themselves in the GetCompletedPlan
5334 // call.
5335
5336 thread_plan_sp->SetPrivate(false);
5337
5338 // The plans run with RunThreadPlan also need to be terminal controlling plans
5339 // or when they are done we will end up asking the plan above us whether we
5340 // should stop, which may give the wrong answer.
5341
5342 thread_plan_sp->SetIsControllingPlan(true);
5343 thread_plan_sp->SetOkayToDiscard(false);
5344
5345 // If we are running some utility expression for LLDB, we now have to mark
5346 // this in the ProcesModID of this process. This RAII takes care of marking
5347 // and reverting the mark it once we are done running the expression.
5348 UtilityFunctionScope util_scope(options.IsForUtilityExpr() ? this : nullptr);
5349
5350 if (GetPrivateState() != eStateStopped) {
5351 diagnostic_manager.PutString(
5353 "RunThreadPlan called while the private state was not stopped.");
5354 return eExpressionSetupError;
5355 }
5356
5357 // Save the thread & frame from the exe_ctx for restoration after we run
5358 const uint32_t thread_idx_id = thread->GetIndexID();
5359 StackFrameSP selected_frame_sp =
5360 thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5361 if (!selected_frame_sp) {
5362 thread->SetSelectedFrame(nullptr);
5363 selected_frame_sp = thread->GetSelectedFrame(DoNoSelectMostRelevantFrame);
5364 if (!selected_frame_sp) {
5365 diagnostic_manager.Printf(
5367 "RunThreadPlan called without a selected frame on thread %d",
5368 thread_idx_id);
5369 return eExpressionSetupError;
5370 }
5371 }
5372
5373 // Make sure the timeout values make sense. The one thread timeout needs to
5374 // be smaller than the overall timeout.
5375 if (options.GetOneThreadTimeout() && options.GetTimeout() &&
5376 *options.GetTimeout() < *options.GetOneThreadTimeout()) {
5377 diagnostic_manager.PutString(lldb::eSeverityError,
5378 "RunThreadPlan called with one thread "
5379 "timeout greater than total timeout");
5380 return eExpressionSetupError;
5381 }
5382
5383 // If the ExecutionContext has a frame, we want to make sure to save/restore
5384 // that frame into exe_ctx. This can happen when we run expressions from a
5385 // non-selected SBFrame, in which case we don't want some thread-plan
5386 // to overwrite the ExecutionContext frame.
5387 StackID ctx_frame_id = exe_ctx.HasFrameScope()
5388 ? exe_ctx.GetFrameRef().GetStackID()
5389 : selected_frame_sp->GetStackID();
5390
5391 // N.B. Running the target may unset the currently selected thread and frame.
5392 // We don't want to do that either, so we should arrange to reset them as
5393 // well.
5394
5395 lldb::ThreadSP selected_thread_sp = GetThreadList().GetSelectedThread();
5396
5397 uint32_t selected_tid;
5398 StackID selected_stack_id;
5399 if (selected_thread_sp) {
5400 selected_tid = selected_thread_sp->GetIndexID();
5401 selected_stack_id =
5402 selected_thread_sp->GetSelectedFrame(DoNoSelectMostRelevantFrame)
5403 ->GetStackID();
5404 } else {
5405 selected_tid = LLDB_INVALID_THREAD_ID;
5406 }
5407
5408 std::shared_ptr<PrivateStateThread> backup_private_state_thread;
5409 lldb::StateType old_state = eStateInvalid;
5410 lldb::ThreadPlanSP stopper_base_plan_sp;
5411
5414 // Yikes, we are running on the private state thread! So we can't wait for
5415 // public events on this thread, since we are the thread that is generating
5416 // public events. The simplest thing to do is to spin up a temporary thread
5417 // to handle private state thread events while we are fielding public
5418 // events here.
5419 LLDB_LOGF(log, "Running thread plan on private state thread, spinning up "
5420 "another state thread to handle the events.");
5421
5422 // One other bit of business: we want to run just this thread plan and
5423 // anything it pushes, and then stop, returning control here. But in the
5424 // normal course of things, the plan above us on the stack would be given a
5425 // shot at the stop event before deciding to stop, and we don't want that.
5426 // So we insert a "stopper" base plan on the stack before the plan we want
5427 // to run. Since base plans always stop and return control to the user,
5428 // that will do just what we want.
5429 stopper_base_plan_sp.reset(new ThreadPlanBase(*thread));
5430 thread->QueueThreadPlan(stopper_base_plan_sp, false);
5431 // Have to make sure our public state is stopped, since otherwise the
5432 // reporting logic below doesn't work correctly.
5433 old_state = GetPublicState();
5434 m_current_private_state_thread_sp->SetPublicStateNoLock(eStateStopped);
5435
5436 // Now spin up the private state thread:
5437 StartPrivateStateThread(lldb::eStateStopped, /* RunLock is stopped*/ false,
5438 &backup_private_state_thread);
5440 // If we can't spin up a thread here we can't run this expression. But
5441 // presumably the old private state thread is still good, so just put it
5442 // back and return an error.
5443 diagnostic_manager.Printf(
5445 "could not spin up a thread to handle events for an expression"
5446 " run on the private state thread.");
5447 m_current_private_state_thread_sp = backup_private_state_thread;
5448 return eExpressionSetupError;
5449 }
5450 }
5451
5452 thread->QueueThreadPlan(
5453 thread_plan_sp, false); // This used to pass "true" does that make sense?
5454
5455 if (options.GetDebug()) {
5456 // In this case, we aren't actually going to run, we just want to stop
5457 // right away. Flush this thread so we will refetch the stacks and show the
5458 // correct backtrace.
5459 // FIXME: To make this prettier we should invent some stop reason for this,
5460 // but that
5461 // is only cosmetic, and this functionality is only of use to lldb
5462 // developers who can live with not pretty...
5463 thread->Flush();
5465 }
5466
5467 ListenerSP listener_sp(
5468 Listener::MakeListener("lldb.process.listener.run-thread-plan"));
5469
5470 lldb::EventSP event_to_broadcast_sp;
5471
5472 {
5473 // This process event hijacker Hijacks the Public events and its destructor
5474 // makes sure that the process events get restored on exit to the function.
5475 //
5476 // If the event needs to propagate beyond the hijacker (e.g., the process
5477 // exits during execution), then the event is put into
5478 // event_to_broadcast_sp for rebroadcasting.
5479
5480 ProcessEventHijacker run_thread_plan_hijacker(*this, listener_sp);
5481
5482 if (log) {
5483 StreamString s;
5484 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
5485 LLDB_LOGF(log,
5486 "Process::RunThreadPlan(): Resuming thread %u - 0x%4.4" PRIx64
5487 " to run thread plan \"%s\".",
5488 thread_idx_id, expr_thread_id, s.GetData());
5489 }
5490
5491 bool got_event;
5492 lldb::EventSP event_sp;
5494
5495 bool before_first_timeout = true; // This is set to false the first time
5496 // that we have to halt the target.
5497 bool do_resume = true;
5498 bool handle_running_event = true;
5499
5500 // This is just for accounting:
5501 uint32_t num_resumes = 0;
5502
5503 // If we are going to run all threads the whole time, or if we are only
5504 // going to run one thread, then we don't need the first timeout. So we
5505 // pretend we are after the first timeout already.
5506 if (!options.GetStopOthers() || !options.GetTryAllThreads())
5507 before_first_timeout = false;
5508
5509 LLDB_LOGF(log, "Stop others: %u, try all: %u, before_first: %u.\n",
5510 options.GetStopOthers(), options.GetTryAllThreads(),
5511 before_first_timeout);
5512
5513 // This isn't going to work if there are unfetched events on the queue. Are
5514 // there cases where we might want to run the remaining events here, and
5515 // then try to call the function? That's probably being too tricky for our
5516 // own good.
5517
5518 Event *other_events = listener_sp->PeekAtNextEvent();
5519 if (other_events != nullptr) {
5520 diagnostic_manager.PutString(
5522 "RunThreadPlan called with pending events on the queue.");
5523 return eExpressionSetupError;
5524 }
5525
5526 // We also need to make sure that the next event is delivered. We might be
5527 // calling a function as part of a thread plan, in which case the last
5528 // delivered event could be the running event, and we don't want event
5529 // coalescing to cause us to lose OUR running event...
5531
5532// This while loop must exit out the bottom, there's cleanup that we need to do
5533// when we are done. So don't call return anywhere within it.
5534
5535#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5536 // It's pretty much impossible to write test cases for things like: One
5537 // thread timeout expires, I go to halt, but the process already stopped on
5538 // the function call stop breakpoint. Turning on this define will make us
5539 // not fetch the first event till after the halt. So if you run a quick
5540 // function, it will have completed, and the completion event will be
5541 // waiting, when you interrupt for halt. The expression evaluation should
5542 // still succeed.
5543 bool miss_first_event = true;
5544#endif
5545 bool pending_stop_on_vfork_done = false;
5546
5547 // If we spawned an override PST, mark the current (original) PST so
5548 // GetStackFrameList returns parent frames during event processing.
5549 std::optional<PolicyStack::Guard> policy_guard;
5550 if (backup_private_state_thread)
5551 policy_guard.emplace(Policy::PrivateState());
5552
5553 while (true) {
5554 // We usually want to resume the process if we get to the top of the
5555 // loop. The only exception is if we get two running events with no
5556 // intervening stop, which can happen, we will just wait for then next
5557 // stop event.
5558 LLDB_LOGF(log,
5559 "Top of while loop: do_resume: %i handle_running_event: %i "
5560 "before_first_timeout: %i.",
5561 do_resume, handle_running_event, before_first_timeout);
5562
5563 if (do_resume || handle_running_event) {
5564 // Do the initial resume and wait for the running event before going
5565 // further.
5566
5567 if (do_resume) {
5568 num_resumes++;
5569 Status resume_error = PrivateResume();
5570 if (!resume_error.Success()) {
5571 diagnostic_manager.Printf(
5573 "couldn't resume inferior the %d time: \"%s\".", num_resumes,
5574 resume_error.AsCString());
5575 return_value = eExpressionSetupError;
5576 break;
5577 }
5578 }
5579
5580 got_event =
5581 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5582 if (!got_event) {
5583 LLDB_LOGF(log,
5584 "Process::RunThreadPlan(): didn't get any event after "
5585 "resume %" PRIu32 ", exiting.",
5586 num_resumes);
5587
5588 diagnostic_manager.Printf(lldb::eSeverityError,
5589 "didn't get any event after resume %" PRIu32
5590 ", exiting.",
5591 num_resumes);
5592 return_value = eExpressionSetupError;
5593 break;
5594 }
5595
5596 stop_state =
5598
5599 if (stop_state != eStateRunning) {
5600 bool restarted = false;
5601
5602 if (stop_state == eStateStopped) {
5604 event_sp.get());
5605 LLDB_LOGF(
5606 log,
5607 "Process::RunThreadPlan(): didn't get running event after "
5608 "resume %d, got %s instead (restarted: %i, do_resume: %i, "
5609 "handle_running_event: %i).",
5610 num_resumes, StateAsCString(stop_state), restarted, do_resume,
5611 handle_running_event);
5612 }
5613
5614 if (restarted) {
5615 // This is probably an overabundance of caution, I don't think I
5616 // should ever get a stopped & restarted event here. But if I do,
5617 // the best thing is to Halt and then get out of here.
5618 const bool clear_thread_plans = false;
5619 const bool use_run_lock = false;
5620 Halt(clear_thread_plans, use_run_lock);
5621 }
5622
5623 diagnostic_manager.Printf(
5625 "didn't get running event after initial resume, got %s instead.",
5626 StateAsCString(stop_state));
5627 return_value = eExpressionSetupError;
5628 break;
5629 }
5630
5631 if (log)
5632 log->PutCString("Process::RunThreadPlan(): resuming succeeded.");
5633 // We need to call the function synchronously, so spin waiting for it
5634 // to return. If we get interrupted while executing, we're going to
5635 // lose our context, and won't be able to gather the result at this
5636 // point. We set the timeout AFTER the resume, since the resume takes
5637 // some time and we don't want to charge that to the timeout.
5638 } else {
5639 if (log)
5640 log->PutCString("Process::RunThreadPlan(): waiting for next event.");
5641 }
5642
5643 do_resume = true;
5644 handle_running_event = true;
5645
5646 // Now wait for the process to stop again:
5647 event_sp.reset();
5648
5649 Timeout<std::micro> timeout =
5650 GetExpressionTimeout(options, before_first_timeout);
5651 if (log) {
5652 if (timeout) {
5653 auto now = system_clock::now();
5654 LLDB_LOGF(log,
5655 "Process::RunThreadPlan(): about to wait - now is %s - "
5656 "endpoint is %s",
5657 llvm::to_string(now).c_str(),
5658 llvm::to_string(now + *timeout).c_str());
5659 } else {
5660 LLDB_LOGF(log, "Process::RunThreadPlan(): about to wait forever.");
5661 }
5662 }
5663
5664#ifdef LLDB_RUN_THREAD_HALT_WITH_EVENT
5665 // See comment above...
5666 if (miss_first_event) {
5667 std::this_thread::sleep_for(std::chrono::milliseconds(1));
5668 miss_first_event = false;
5669 got_event = false;
5670 } else
5671#endif
5672 got_event = listener_sp->GetEvent(event_sp, timeout);
5673
5674 if (got_event) {
5675 if (event_sp) {
5676 bool keep_going = false;
5677 if (event_sp->GetType() == eBroadcastBitInterrupt) {
5678 const bool clear_thread_plans = false;
5679 const bool use_run_lock = false;
5680 Halt(clear_thread_plans, use_run_lock);
5681 return_value = eExpressionInterrupted;
5682 diagnostic_manager.PutString(lldb::eSeverityInfo,
5683 "execution halted by user interrupt.");
5684 LLDB_LOGF(log, "Process::RunThreadPlan(): Got interrupted by "
5685 "eBroadcastBitInterrupted, exiting.");
5686 break;
5687 } else {
5688 stop_state =
5690 LLDB_LOGF(log,
5691 "Process::RunThreadPlan(): in while loop, got event: %s.",
5692 StateAsCString(stop_state));
5693
5694 switch (stop_state) {
5695 case lldb::eStateStopped: {
5697 event_sp.get())) {
5698 // If we were restarted, we just need to go back up to fetch
5699 // another event.
5700 LLDB_LOGF(log, "Process::RunThreadPlan(): Got a stop and "
5701 "restart, so we'll continue waiting.");
5702 keep_going = true;
5703 do_resume = false;
5704 handle_running_event = true;
5705 } else {
5706 // Check for fork/vfork/vforkdone stop reasons. DidFork /
5707 // DidVFork / DidVForkDone have already been called by
5708 // PerformAction (via DoOnRemoval).
5709 bool handled_fork = false;
5710 if (ThreadSP fork_thread_sp =
5711 GetThreadList().FindThreadByID(expr_thread_id)) {
5712 if (StopInfoSP stop_info_sp = fork_thread_sp->GetStopInfo()) {
5713 StopReason reason = stop_info_sp->GetStopReason();
5714 if (reason == eStopReasonFork ||
5715 reason == eStopReasonVFork ||
5716 reason == eStopReasonVForkDone) {
5717 handled_fork = true;
5718 if (reason == eStopReasonFork &&
5719 options.GetStopOnFork()) {
5720 // Fork + stop-on-fork: DidFork already ran via
5721 // PerformAction. Parent breakpoints are unaffected.
5722 LLDB_LOGF(log, "Process::RunThreadPlan(): stopped for "
5723 "fork, stop-on-fork is set.");
5724 return_value = eExpressionInterrupted;
5725 } else if (reason == eStopReasonVFork &&
5726 options.GetStopOnFork()) {
5727 // VFork + stop-on-fork: DidVFork already disabled
5728 // software breakpoints (parent and child share
5729 // address space). Interrupting now would leave the
5730 // user with non-functional breakpoints. Defer the
5731 // stop until vforkdone, when DidVForkDone restores
5732 // breakpoint state.
5733 LLDB_LOGF(log,
5734 "Process::RunThreadPlan(): got vfork with "
5735 "stop-on-fork, deferring stop to "
5736 "vforkdone.");
5737 pending_stop_on_vfork_done = true;
5738 keep_going = true;
5739 do_resume = true;
5740 handle_running_event = true;
5741 } else if (reason == eStopReasonVForkDone &&
5742 pending_stop_on_vfork_done) {
5743 // Deferred vfork stop: the vfork cycle has
5744 // completed. DidVForkDone has re-enabled software
5745 // breakpoints and decremented
5746 // m_vfork_in_progress_count.
5747 LLDB_LOGF(log, "Process::RunThreadPlan(): vfork cycle "
5748 "complete, stop-on-fork is set.");
5749 pending_stop_on_vfork_done = false;
5750 return_value = eExpressionInterrupted;
5751 } else {
5752 LLDB_LOGF(log, "Process::RunThreadPlan(): got fork "
5753 "event, continuing.");
5754 keep_going = true;
5755 do_resume = true;
5756 handle_running_event = true;
5757 }
5758 }
5759 }
5760 }
5761
5762 if (!handled_fork) {
5763 const bool handle_interrupts = true;
5764 return_value = *HandleStoppedEvent(
5765 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5766 event_sp, event_to_broadcast_sp, options,
5767 handle_interrupts);
5768 if (return_value == eExpressionThreadVanished)
5769 keep_going = false;
5770 }
5771 }
5772 } break;
5773
5775 // This shouldn't really happen, but sometimes we do get two
5776 // running events without an intervening stop, and in that case
5777 // we should just go back to waiting for the stop.
5778 do_resume = false;
5779 keep_going = true;
5780 handle_running_event = false;
5781 break;
5782
5783 default:
5784 LLDB_LOGF(log,
5785 "Process::RunThreadPlan(): execution stopped with "
5786 "unexpected state: %s.",
5787 StateAsCString(stop_state));
5788
5789 if (stop_state == eStateExited)
5790 event_to_broadcast_sp = event_sp;
5791
5792 diagnostic_manager.PutString(
5794 "execution stopped with unexpected state.");
5795 return_value = eExpressionInterrupted;
5796 break;
5797 }
5798 }
5799
5800 if (keep_going)
5801 continue;
5802 else
5803 break;
5804 } else {
5805 if (log)
5806 log->PutCString("Process::RunThreadPlan(): got_event was true, but "
5807 "the event pointer was null. How odd...");
5808 return_value = eExpressionInterrupted;
5809 break;
5810 }
5811 } else {
5812 // If we didn't get an event that means we've timed out... We will
5813 // interrupt the process here. Depending on what we were asked to do
5814 // we will either exit, or try with all threads running for the same
5815 // timeout.
5816
5817 if (log) {
5818 if (options.GetTryAllThreads()) {
5819 if (before_first_timeout) {
5820 LLDB_LOG(log,
5821 "Running function with one thread timeout timed out.");
5822 } else
5823 LLDB_LOG(log, "Restarting function with all threads enabled and "
5824 "timeout: {0} timed out, abandoning execution.",
5825 timeout);
5826 } else
5827 LLDB_LOG(log, "Running function with timeout: {0} timed out, "
5828 "abandoning execution.",
5829 timeout);
5830 }
5831
5832 // It is possible that between the time we issued the Halt, and we get
5833 // around to calling Halt the target could have stopped. That's fine,
5834 // Halt will figure that out and send the appropriate Stopped event.
5835 // BUT it is also possible that we stopped & restarted (e.g. hit a
5836 // signal with "stop" set to false.) In
5837 // that case, we'll get the stopped & restarted event, and we should go
5838 // back to waiting for the Halt's stopped event. That's what this
5839 // while loop does.
5840
5841 bool back_to_top = true;
5842 uint32_t try_halt_again = 0;
5843 bool do_halt = true;
5844 const uint32_t num_retries = 5;
5845 while (try_halt_again < num_retries) {
5846 Status halt_error;
5847 if (do_halt) {
5848 LLDB_LOGF(log, "Process::RunThreadPlan(): Running Halt.");
5849 const bool clear_thread_plans = false;
5850 const bool use_run_lock = false;
5851 Halt(clear_thread_plans, use_run_lock);
5852 }
5853 if (halt_error.Success()) {
5854 if (log)
5855 log->PutCString("Process::RunThreadPlan(): Halt succeeded.");
5856
5857 got_event =
5858 listener_sp->GetEvent(event_sp, GetUtilityExpressionTimeout());
5859
5860 if (got_event) {
5861 stop_state =
5863 if (log) {
5864 LLDB_LOGF(log,
5865 "Process::RunThreadPlan(): Stopped with event: %s",
5866 StateAsCString(stop_state));
5867 if (stop_state == lldb::eStateStopped &&
5869 event_sp.get()))
5870 log->PutCString(" Event was the Halt interruption event.");
5871 }
5872
5873 if (stop_state == lldb::eStateStopped) {
5875 event_sp.get())) {
5876 if (log)
5877 log->PutCString("Process::RunThreadPlan(): Went to halt "
5878 "but got a restarted event, there must be "
5879 "an un-restarted stopped event so try "
5880 "again... "
5881 "Exiting wait loop.");
5882 try_halt_again++;
5883 do_halt = false;
5884 continue;
5885 }
5886
5887 // Between the time we initiated the Halt and the time we
5888 // delivered it, the process could have already finished its
5889 // job. Check that here:
5890 const bool handle_interrupts = false;
5891 if (auto result = HandleStoppedEvent(
5892 expr_thread_id, thread_plan_sp, thread_plan_restorer,
5893 event_sp, event_to_broadcast_sp, options,
5894 handle_interrupts)) {
5895 return_value = *result;
5896 back_to_top = false;
5897 break;
5898 }
5899
5900 if (!options.GetTryAllThreads()) {
5901 if (log)
5902 log->PutCString("Process::RunThreadPlan(): try_all_threads "
5903 "was false, we stopped so now we're "
5904 "quitting.");
5905 return_value = eExpressionInterrupted;
5906 back_to_top = false;
5907 break;
5908 }
5909
5910 if (before_first_timeout) {
5911 // Set all the other threads to run, and return to the top of
5912 // the loop, which will continue;
5913 before_first_timeout = false;
5914 thread_plan_sp->SetStopOthers(false);
5915 if (log)
5916 log->PutCString(
5917 "Process::RunThreadPlan(): about to resume.");
5918
5919 back_to_top = true;
5920 break;
5921 } else {
5922 // Running all threads failed, so return Interrupted.
5923 if (log)
5924 log->PutCString("Process::RunThreadPlan(): running all "
5925 "threads timed out.");
5926 return_value = eExpressionInterrupted;
5927 back_to_top = false;
5928 break;
5929 }
5930 }
5931 } else {
5932 if (log)
5933 log->PutCString("Process::RunThreadPlan(): halt said it "
5934 "succeeded, but I got no event. "
5935 "I'm getting out of here passing Interrupted.");
5936 return_value = eExpressionInterrupted;
5937 back_to_top = false;
5938 break;
5939 }
5940 } else {
5941 try_halt_again++;
5942 continue;
5943 }
5944 }
5945
5946 if (!back_to_top || try_halt_again > num_retries)
5947 break;
5948 else
5949 continue;
5950 }
5951 } // END WAIT LOOP
5952
5953 policy_guard.reset();
5954
5955 // If we had to start up a temporary private state thread to run this
5956 // thread plan, shut it down now.
5957 if (backup_private_state_thread &&
5958 backup_private_state_thread->IsJoinable()) {
5960 Status error;
5961 m_current_private_state_thread_sp = backup_private_state_thread;
5962 if (stopper_base_plan_sp) {
5963 thread->DiscardThreadPlansUpToPlan(stopper_base_plan_sp);
5964 }
5965 if (old_state != eStateInvalid)
5966 m_current_private_state_thread_sp->SetPublicStateNoLock(old_state);
5967 }
5968
5969 // If our thread went away on us, we need to get out of here without
5970 // doing any more work. We don't have to clean up the thread plan, that
5971 // will have happened when the Thread was destroyed.
5972 if (return_value == eExpressionThreadVanished) {
5973 return return_value;
5974 }
5975
5976 if (return_value != eExpressionCompleted && log) {
5977 // Print a backtrace into the log so we can figure out where we are:
5978 StreamString s;
5979 s.PutCString("Thread state after unsuccessful completion: \n");
5980 thread->GetStackFrameStatus(s, 0, UINT32_MAX, true, UINT32_MAX,
5981 /*show_hidden*/ true);
5982 log->PutString(s.GetString());
5983 }
5984 // Restore the thread state if we are going to discard the plan execution.
5985 // There are three cases where this could happen: 1) The execution
5986 // successfully completed 2) We hit a breakpoint, and ignore_breakpoints
5987 // was true 3) We got some other error, and discard_on_error was true
5988 bool should_unwind = (return_value == eExpressionInterrupted &&
5989 options.DoesUnwindOnError()) ||
5990 (return_value == eExpressionHitBreakpoint &&
5991 options.DoesIgnoreBreakpoints());
5992
5993 if (return_value == eExpressionCompleted || should_unwind) {
5994 thread_plan_sp->RestoreThreadState();
5995 }
5996
5997 // Now do some processing on the results of the run:
5998 if (return_value == eExpressionInterrupted ||
5999 return_value == eExpressionHitBreakpoint) {
6000 if (log) {
6001 StreamString s;
6002 if (event_sp)
6003 event_sp->Dump(&s);
6004 else {
6005 log->PutCString("Process::RunThreadPlan(): Stop event that "
6006 "interrupted us is NULL.");
6007 }
6008
6009 StreamString ts;
6010
6011 const char *event_explanation = nullptr;
6012
6013 do {
6014 if (!event_sp) {
6015 event_explanation = "<no event>";
6016 break;
6017 } else if (event_sp->GetType() == eBroadcastBitInterrupt) {
6018 event_explanation = "<user interrupt>";
6019 break;
6020 } else {
6021 const Process::ProcessEventData *event_data =
6023 event_sp.get());
6024
6025 if (!event_data) {
6026 event_explanation = "<no event data>";
6027 break;
6028 }
6029
6030 Process *process = event_data->GetProcessSP().get();
6031
6032 if (!process) {
6033 event_explanation = "<no process>";
6034 break;
6035 }
6036
6037 ThreadList &thread_list = process->GetThreadList();
6038
6039 uint32_t num_threads = thread_list.GetSize();
6040 uint32_t thread_index;
6041
6042 ts.Printf("<%u threads> ", num_threads);
6043
6044 for (thread_index = 0; thread_index < num_threads; ++thread_index) {
6045 Thread *thread = thread_list.GetThreadAtIndex(thread_index).get();
6046
6047 if (!thread) {
6048 ts.Printf("<?> ");
6049 continue;
6050 }
6051
6052 ts.Printf("<0x%4.4" PRIx64 " ", thread->GetID());
6053 RegisterContext *register_context =
6054 thread->GetRegisterContext().get();
6055
6056 if (register_context)
6057 ts.Printf("[ip 0x%" PRIx64 "] ", register_context->GetPC());
6058 else
6059 ts.Printf("[ip unknown] ");
6060
6061 // Show the private stop info here, the public stop info will be
6062 // from the last natural stop.
6063 lldb::StopInfoSP stop_info_sp = thread->GetPrivateStopInfo();
6064 if (stop_info_sp) {
6065 const char *stop_desc = stop_info_sp->GetDescription();
6066 if (stop_desc)
6067 ts.PutCString(stop_desc);
6068 }
6069 ts.Printf(">");
6070 }
6071
6072 event_explanation = ts.GetData();
6073 }
6074 } while (false);
6075
6076 if (event_explanation)
6077 LLDB_LOGF(log,
6078 "Process::RunThreadPlan(): execution interrupted: %s %s",
6079 s.GetData(), event_explanation);
6080 else
6081 LLDB_LOGF(log, "Process::RunThreadPlan(): execution interrupted: %s",
6082 s.GetData());
6083 }
6084
6085 if (should_unwind) {
6086 LLDB_LOGF(log,
6087 "Process::RunThreadPlan: ExecutionInterrupted - "
6088 "discarding thread plans up to %p.",
6089 static_cast<void *>(thread_plan_sp.get()));
6090 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6091 } else {
6092 LLDB_LOGF(log,
6093 "Process::RunThreadPlan: ExecutionInterrupted - for "
6094 "plan: %p not discarding.",
6095 static_cast<void *>(thread_plan_sp.get()));
6096 }
6097 } else if (return_value == eExpressionSetupError) {
6098 if (log)
6099 log->PutCString("Process::RunThreadPlan(): execution set up error.");
6100
6101 if (options.DoesUnwindOnError()) {
6102 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6103 }
6104 } else {
6105 if (thread->IsThreadPlanDone(thread_plan_sp.get())) {
6106 if (log)
6107 log->PutCString("Process::RunThreadPlan(): thread plan is done");
6108 return_value = eExpressionCompleted;
6109 } else if (thread->WasThreadPlanDiscarded(thread_plan_sp.get())) {
6110 if (log)
6111 log->PutCString(
6112 "Process::RunThreadPlan(): thread plan was discarded");
6113 return_value = eExpressionDiscarded;
6114 } else {
6115 if (log)
6116 log->PutCString(
6117 "Process::RunThreadPlan(): thread plan stopped in mid course");
6118 if (options.DoesUnwindOnError() && thread_plan_sp) {
6119 if (log)
6120 log->PutCString("Process::RunThreadPlan(): discarding thread plan "
6121 "'cause unwind_on_error is set.");
6122 thread->DiscardThreadPlansUpToPlan(thread_plan_sp);
6123 }
6124 }
6125 }
6126
6127 // Thread we ran the function in may have gone away because we ran the
6128 // target Check that it's still there, and if it is put it back in the
6129 // context. Also restore the frame in the context if it is still present.
6130 thread = GetThreadList().FindThreadByIndexID(thread_idx_id, true).get();
6131 if (thread) {
6132 exe_ctx.SetFrameSP(thread->GetFrameWithStackID(ctx_frame_id));
6133 }
6134
6135 // Also restore the current process'es selected frame & thread, since this
6136 // function calling may be done behind the user's back.
6137
6138 if (selected_tid != LLDB_INVALID_THREAD_ID) {
6139 if (GetThreadList().SetSelectedThreadByIndexID(selected_tid) &&
6140 selected_stack_id.IsValid()) {
6141 // We were able to restore the selected thread, now restore the frame:
6142 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6143 StackFrameSP old_frame_sp =
6144 GetThreadList().GetSelectedThread()->GetFrameWithStackID(
6145 selected_stack_id);
6146 if (old_frame_sp)
6147 GetThreadList().GetSelectedThread()->SetSelectedFrame(
6148 old_frame_sp.get());
6149 }
6150 }
6151 }
6152
6153 // If the process exited during the run of the thread plan, notify everyone.
6154
6155 if (event_to_broadcast_sp) {
6156 if (log)
6157 log->PutCString("Process::RunThreadPlan(): rebroadcasting event.");
6158 BroadcastEvent(event_to_broadcast_sp);
6159 }
6160
6161 return return_value;
6162}
6163
6165 const StateType state = GetState();
6166 if (StateIsStoppedState(state, false)) {
6167 if (state == eStateExited) {
6168 int exit_status = GetExitStatus();
6169 const char *exit_description = GetExitDescription();
6170 strm.Printf("Process %" PRIu64 " exited with status = %i (0x%8.8x) %s\n",
6171 GetID(), exit_status, exit_status,
6172 exit_description ? exit_description : "");
6173 } else {
6174 if (state == eStateConnected)
6175 strm.Printf("Connected to remote target.\n");
6176 else
6177 strm.Printf("Process %" PRIu64 " %s\n", GetID(), StateAsCString(state));
6178 }
6179 } else {
6180 strm.Printf("Process %" PRIu64 " is running.\n", GetID());
6181 }
6182}
6183
6185 bool only_threads_with_stop_reason,
6186 uint32_t start_frame, uint32_t num_frames,
6187 uint32_t num_frames_with_source,
6188 bool stop_format) {
6189 size_t num_thread_infos_dumped = 0;
6190
6191 // You can't hold the thread list lock while calling Thread::GetStatus. That
6192 // very well might run code (e.g. if we need it to get return values or
6193 // arguments.) For that to work the process has to be able to acquire it.
6194 // So instead copy the thread ID's, and look them up one by one:
6195
6196 uint32_t num_threads;
6197 std::vector<lldb::tid_t> thread_id_array;
6198 // Scope for thread list locker;
6199 {
6200 std::lock_guard<std::recursive_mutex> guard(GetThreadList().GetMutex());
6201 ThreadList &curr_thread_list = GetThreadList();
6202 num_threads = curr_thread_list.GetSize();
6203 uint32_t idx;
6204 thread_id_array.resize(num_threads);
6205 for (idx = 0; idx < num_threads; ++idx)
6206 thread_id_array[idx] = curr_thread_list.GetThreadAtIndex(idx)->GetID();
6207 }
6208
6209 for (uint32_t i = 0; i < num_threads; i++) {
6210 ThreadSP thread_sp(GetThreadList().FindThreadByID(thread_id_array[i]));
6211 if (thread_sp) {
6212 if (only_threads_with_stop_reason) {
6213 StopInfoSP stop_info_sp = thread_sp->GetStopInfo();
6214 if (!stop_info_sp || !stop_info_sp->ShouldShow())
6215 continue;
6216 }
6217 thread_sp->GetStatus(strm, start_frame, num_frames,
6218 num_frames_with_source, stop_format,
6219 /*show_hidden*/ num_frames <= 1);
6220 ++num_thread_infos_dumped;
6221 } else {
6222 Log *log = GetLog(LLDBLog::Process);
6223 LLDB_LOGF(log, "Process::GetThreadStatus - thread 0x" PRIu64
6224 " vanished while running Thread::GetStatus.");
6225 }
6226 }
6227 return num_thread_infos_dumped;
6228}
6229
6231 m_memory_cache.AddInvalidRange(region.GetRangeBase(), region.GetByteSize());
6232}
6233
6235 return m_memory_cache.RemoveInvalidRange(region.GetRangeBase(),
6236 region.GetByteSize());
6237}
6238
6240 void *baton) {
6241 m_pre_resume_actions.push_back(PreResumeCallbackAndBaton(callback, baton));
6242}
6243
6245 bool result = true;
6246 while (!m_pre_resume_actions.empty()) {
6247 struct PreResumeCallbackAndBaton action = m_pre_resume_actions.back();
6248 m_pre_resume_actions.pop_back();
6249 bool this_result = action.callback(action.baton);
6250 if (result)
6251 result = this_result;
6252 }
6253 return result;
6254}
6255
6257
6259{
6260 PreResumeCallbackAndBaton element(callback, baton);
6261 auto found_iter = llvm::find(m_pre_resume_actions, element);
6262 if (found_iter != m_pre_resume_actions.end())
6263 {
6264 m_pre_resume_actions.erase(found_iter);
6265 }
6266}
6267
6271
6279
6281 // If we haven't started up the private state thread yet, then whatever thread
6282 // is fetching this event should be temporarily the private state thread.
6285 return true;
6286 return m_current_private_state_thread_sp->IsOnThread(
6288}
6289
6291 m_thread_list.Flush();
6292 m_extended_thread_list.Flush();
6294 m_queue_list.Clear();
6297}
6298
6300 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6301 return AddressableBits::AddressableBitToMask(num_bits_setting);
6302
6303 return m_code_address_mask;
6304}
6305
6307 if (uint32_t num_bits_setting = GetVirtualAddressableBits())
6308 return AddressableBits::AddressableBitToMask(num_bits_setting);
6309
6310 return m_data_address_mask;
6311}
6312
6321
6330
6333 "Setting Process code address mask to {0:x}", code_address_mask);
6334 m_code_address_mask = code_address_mask;
6335}
6336
6339 "Setting Process data address mask to {0:x}", data_address_mask);
6340 m_data_address_mask = data_address_mask;
6341}
6342
6345 "Setting Process highmem code address mask to {0:x}",
6346 code_address_mask);
6347 m_highmem_code_address_mask = code_address_mask;
6348}
6349
6352 "Setting Process highmem data address mask to {0:x}",
6353 data_address_mask);
6354 m_highmem_data_address_mask = data_address_mask;
6355}
6356
6358 if (ABISP abi_sp = GetABI())
6359 addr = abi_sp->FixCodeAddress(addr);
6360 return addr;
6361}
6362
6364 if (ABISP abi_sp = GetABI())
6365 addr = abi_sp->FixDataAddress(addr);
6366 return addr;
6367}
6368
6370 if (ABISP abi_sp = GetABI())
6371 addr = abi_sp->FixAnyAddress(addr);
6372 return addr;
6373}
6374
6376 Log *log = GetLog(LLDBLog::Process);
6377 LLDB_LOGF(log, "Process::%s()", __FUNCTION__);
6378
6379 Target &target = GetTarget();
6380 target.CleanupProcess();
6381 target.ClearModules(false);
6382 m_dynamic_checkers_up.reset();
6383 m_abi_sp.reset();
6384 m_system_runtime_up.reset();
6385 m_os_up.reset();
6386 m_dyld_up.reset();
6387 m_jit_loaders_up.reset();
6388 m_image_tokens.clear();
6389 // After an exec, the inferior is a new process and these memory regions are
6390 // no longer allocated.
6391 m_allocated_memory_cache.Clear(/*deallocte_memory=*/false);
6392 {
6393 std::lock_guard<std::recursive_mutex> guard(m_language_runtimes_mutex);
6394 m_language_runtimes.clear();
6395 }
6397 m_thread_list.DiscardThreadPlans();
6398 m_memory_cache.Clear(true);
6399 DoDidExec();
6401 // Flush the process (threads and all stack frames) after running
6402 // CompleteAttach() in case the dynamic loader loaded things in new
6403 // locations.
6404 Flush();
6405
6406 // After we figure out what was loaded/unloaded in CompleteAttach, we need to
6407 // let the target know so it can do any cleanup it needs to.
6408 target.DidExec();
6409}
6410
6412 if (address == nullptr) {
6413 error = Status::FromErrorString("Invalid address argument");
6414 return LLDB_INVALID_ADDRESS;
6415 }
6416
6417 addr_t function_addr = LLDB_INVALID_ADDRESS;
6418
6419 addr_t addr = address->GetLoadAddress(&GetTarget());
6420 std::map<addr_t, addr_t>::const_iterator iter =
6422 if (iter != m_resolved_indirect_addresses.end()) {
6423 function_addr = (*iter).second;
6424 } else {
6425 if (!CallVoidArgVoidPtrReturn(address, function_addr)) {
6426 const Symbol *symbol = address->CalculateSymbolContextSymbol();
6428 "Unable to call resolver for indirect function %s",
6429 symbol ? symbol->GetName().AsCString(nullptr) : "<UNKNOWN>");
6430 function_addr = LLDB_INVALID_ADDRESS;
6431 } else {
6432 if (ABISP abi_sp = GetABI())
6433 function_addr = abi_sp->FixCodeAddress(function_addr);
6435 std::pair<addr_t, addr_t>(addr, function_addr));
6436 }
6437 }
6438 return function_addr;
6439}
6440
6442 // Inform the system runtime of the modified modules.
6443 SystemRuntime *sys_runtime = GetSystemRuntime();
6444 if (sys_runtime)
6445 sys_runtime->ModulesDidLoad(module_list);
6446
6447 GetJITLoaders().ModulesDidLoad(module_list);
6448
6449 // Give the instrumentation runtimes a chance to be created before informing
6450 // them of the modified modules.
6453 for (auto &runtime : m_instrumentation_runtimes)
6454 runtime.second->ModulesDidLoad(module_list);
6455
6456 // Give the language runtimes a chance to be created before informing them of
6457 // the modified modules.
6458 for (const lldb::LanguageType lang_type : Language::GetSupportedLanguages()) {
6459 if (LanguageRuntime *runtime = GetLanguageRuntime(lang_type))
6460 runtime->ModulesDidLoad(module_list);
6461 }
6462
6463 // If we don't have an operating system plug-in, try to load one since
6464 // loading shared libraries might cause a new one to try and load
6465 if (!m_os_up)
6467
6468 // Inform the structured-data plugins of the modified modules.
6469 for (auto &pair : m_structured_data_plugin_map) {
6470 if (pair.second)
6471 pair.second->ModulesDidLoad(*this, module_list);
6472 }
6473}
6474
6477 return;
6478 if (!sc.module_sp || !sc.function || !sc.function->GetIsOptimized())
6479 return;
6480 sc.module_sp->ReportWarningOptimization(GetTarget().GetDebugger().GetID());
6481}
6482
6485 return;
6486 if (!sc.module_sp)
6487 return;
6488 LanguageType language = sc.GetLanguage();
6489 if (language == eLanguageTypeUnknown ||
6490 language == lldb::eLanguageTypeAssembly ||
6492 return;
6493 LanguageSet plugins =
6495 if (plugins[language])
6496 return;
6497 sc.module_sp->ReportWarningUnsupportedLanguage(
6498 language, GetTarget().GetDebugger().GetID());
6499}
6500
6502 info.Clear();
6503
6504 PlatformSP platform_sp = GetTarget().GetPlatform();
6505 if (!platform_sp)
6506 return false;
6507
6508 return platform_sp->GetProcessInfo(GetID(), info);
6509}
6510
6511lldb_private::UUID Process::FindModuleUUID(const llvm::StringRef path) {
6512 return lldb_private::UUID();
6513}
6514
6516 ThreadCollectionSP threads;
6517
6518 const MemoryHistorySP &memory_history =
6519 MemoryHistory::FindPlugin(shared_from_this());
6520
6521 if (!memory_history) {
6522 return threads;
6523 }
6524
6525 threads = std::make_shared<ThreadCollection>(
6526 memory_history->GetHistoryThreads(addr));
6527
6528 return threads;
6529}
6530
6533 InstrumentationRuntimeCollection::iterator pos;
6534 pos = m_instrumentation_runtimes.find(type);
6535 if (pos == m_instrumentation_runtimes.end()) {
6536 return InstrumentationRuntimeSP();
6537 } else
6538 return (*pos).second;
6539}
6540
6541bool Process::GetModuleSpec(const FileSpec &module_file_spec,
6542 const ArchSpec &arch, ModuleSpec &module_spec) {
6543 module_spec.Clear();
6544 return false;
6545}
6546
6548 m_image_tokens.push_back(image_ptr);
6549 return m_image_tokens.size() - 1;
6550}
6551
6553 if (token < m_image_tokens.size())
6554 return m_image_tokens[token];
6555 return LLDB_INVALID_ADDRESS;
6556}
6557
6558void Process::ResetImageToken(size_t token) {
6559 if (token < m_image_tokens.size())
6561}
6562
6563Address
6565 AddressRange range_bounds) {
6566 Target &target = GetTarget();
6567 DisassemblerSP disassembler_sp;
6568 InstructionList *insn_list = nullptr;
6569
6570 Address retval = default_stop_addr;
6571
6572 if (!target.GetUseFastStepping())
6573 return retval;
6574 if (!default_stop_addr.IsValid())
6575 return retval;
6576
6577 const char *plugin_name = nullptr;
6578 const char *flavor = nullptr;
6579 const char *cpu = nullptr;
6580 const char *features = nullptr;
6581 disassembler_sp = Disassembler::DisassembleRange(
6582 target.GetArchitecture(), plugin_name, flavor, cpu, features, GetTarget(),
6583 range_bounds);
6584 if (disassembler_sp)
6585 insn_list = &disassembler_sp->GetInstructionList();
6586
6587 if (insn_list == nullptr) {
6588 return retval;
6589 }
6590
6591 size_t insn_offset =
6592 insn_list->GetIndexOfInstructionAtAddress(default_stop_addr);
6593 if (insn_offset == UINT32_MAX) {
6594 return retval;
6595 }
6596
6597 uint32_t branch_index = insn_list->GetIndexOfNextBranchInstruction(
6598 insn_offset, false /* ignore_calls*/, nullptr);
6599 if (branch_index == UINT32_MAX) {
6600 return retval;
6601 }
6602
6603 if (branch_index > insn_offset) {
6604 Address next_branch_insn_address =
6605 insn_list->GetInstructionAtIndex(branch_index)->GetAddress();
6606 if (next_branch_insn_address.IsValid() &&
6607 range_bounds.ContainsFileAddress(next_branch_insn_address)) {
6608 retval = next_branch_insn_address;
6609 }
6610 }
6611
6612 return retval;
6613}
6614
6616 MemoryRegionInfo &range_info) {
6617 if (const lldb::ABISP &abi = GetABI())
6618 load_addr = abi->FixAnyAddress(load_addr);
6619 Status error = DoGetMemoryRegionInfo(load_addr, range_info);
6620 // Reject a region that does not contain the requested address.
6621 if (error.Success() && !range_info.GetRange().Contains(load_addr))
6622 error = Status::FromErrorString("Invalid memory region");
6623
6624 return error;
6625}
6626
6628 Status error;
6629
6630 lldb::addr_t range_end = 0;
6631 const lldb::ABISP &abi = GetABI();
6632
6633 region_list.clear();
6634 do {
6636 error = GetMemoryRegionInfo(range_end, region_info);
6637 // GetMemoryRegionInfo should only return an error if it is unimplemented.
6638 if (error.Fail()) {
6639 region_list.clear();
6640 break;
6641 }
6642
6643 // We only check the end address, not start and end, because we assume that
6644 // the start will not have non-address bits until the first unmappable
6645 // region. We will have exited the loop by that point because the previous
6646 // region, the last mappable region, will have non-address bits in its end
6647 // address.
6648 range_end = region_info.GetRange().GetRangeEnd();
6649 if (region_info.GetMapped() == eLazyBoolYes) {
6650 region_list.push_back(std::move(region_info));
6651 }
6652 } while (
6653 // For a process with no non-address bits, all address bits
6654 // set means the end of memory.
6655 range_end != LLDB_INVALID_ADDRESS &&
6656 // If we have non-address bits and some are set then the end
6657 // is at or beyond the end of mappable memory.
6658 !(abi && (abi->FixAnyAddress(range_end) != range_end)));
6659
6660 return error;
6661}
6662
6663Status
6664Process::ConfigureStructuredData(llvm::StringRef type_name,
6665 const StructuredData::ObjectSP &config_sp) {
6666 // If you get this, the Process-derived class needs to implement a method to
6667 // enable an already-reported asynchronous structured data feature. See
6668 // ProcessGDBRemote for an example implementation over gdb-remote.
6669 return Status::FromErrorString("unimplemented");
6670}
6671
6673 const StructuredData::Array &supported_type_names) {
6674 Log *log = GetLog(LLDBLog::Process);
6675
6676 // Bail out early if there are no type names to map.
6677 if (supported_type_names.GetSize() == 0) {
6678 LLDB_LOG(log, "no structured data types supported");
6679 return;
6680 }
6681
6682 // These StringRefs are backed by the input parameter.
6683 std::set<llvm::StringRef> type_names;
6684
6685 LLDB_LOG(log,
6686 "the process supports the following async structured data types:");
6687
6688 supported_type_names.ForEach(
6689 [&type_names, &log](StructuredData::Object *object) {
6690 // There shouldn't be null objects in the array.
6691 if (!object)
6692 return false;
6693
6694 // All type names should be strings.
6695 const llvm::StringRef type_name = object->GetStringValue();
6696 if (type_name.empty())
6697 return false;
6698
6699 type_names.insert(type_name);
6700 LLDB_LOG(log, "- {0}", type_name);
6701 return true;
6702 });
6703
6704 // For each StructuredDataPlugin, if the plugin handles any of the types in
6705 // the supported_type_names, map that type name to that plugin. Stop when
6706 // we've consumed all the type names.
6707 // FIXME: should we return an error if there are type names nobody
6708 // supports?
6710 if (type_names.empty())
6711 break;
6712
6713 // Create the plugin.
6714 StructuredDataPluginSP plugin_sp = (*cbs.create_callback)(*this);
6715 if (!plugin_sp) {
6716 // This plugin doesn't think it can work with the process. Move on to the
6717 // next.
6718 continue;
6719 }
6720
6721 // For any of the remaining type names, map any that this plugin supports.
6722 std::vector<llvm::StringRef> names_to_remove;
6723 for (llvm::StringRef type_name : type_names) {
6724 if (plugin_sp->SupportsStructuredDataType(type_name)) {
6726 std::make_pair(type_name, plugin_sp));
6727 names_to_remove.push_back(type_name);
6728 LLDB_LOG(log, "using plugin {0} for type name {1}",
6729 plugin_sp->GetPluginName(), type_name);
6730 }
6731 }
6732
6733 // Remove the type names that were consumed by this plugin.
6734 for (llvm::StringRef type_name : names_to_remove)
6735 type_names.erase(type_name);
6736 }
6737}
6738
6740 const StructuredData::ObjectSP object_sp) {
6741 // Nothing to do if there's no data.
6742 if (!object_sp)
6743 return false;
6744
6745 // The contract is this must be a dictionary, so we can look up the routing
6746 // key via the top-level 'type' string value within the dictionary.
6747 StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
6748 if (!dictionary)
6749 return false;
6750
6751 // Grab the async structured type name (i.e. the feature/plugin name).
6752 llvm::StringRef type_name;
6753 if (!dictionary->GetValueForKeyAsString("type", type_name))
6754 return false;
6755
6756 // Check if there's a plugin registered for this type name.
6757 auto find_it = m_structured_data_plugin_map.find(type_name);
6758 if (find_it == m_structured_data_plugin_map.end()) {
6759 // We don't have a mapping for this structured data type.
6760 return false;
6761 }
6762
6763 // Route the structured data to the plugin.
6764 find_it->second->HandleArrivalOfStructuredData(*this, type_name, object_sp);
6765 return true;
6766}
6767
6769 // Default implementation does nothign.
6770 // No automatic signal filtering to speak of.
6771 return Status();
6772}
6773
6775 Platform *platform,
6776 llvm::function_ref<std::unique_ptr<UtilityFunction>()> factory) {
6777 if (platform != GetTarget().GetPlatform().get())
6778 return nullptr;
6779 llvm::call_once(m_dlopen_utility_func_flag_once,
6780 [&] { m_dlopen_utility_func_up = factory(); });
6781 return m_dlopen_utility_func_up.get();
6782}
6783
6784llvm::Expected<TraceSupportedResponse> Process::TraceSupported() {
6785 if (!IsLiveDebugSession())
6786 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6787 "Can't trace a non-live process.");
6788 return llvm::make_error<UnimplementedError>();
6789}
6790
6792 addr_t &returned_func,
6793 bool trap_exceptions) {
6795 if (thread == nullptr || address == nullptr)
6796 return false;
6797
6799 options.SetStopOthers(true);
6800 options.SetUnwindOnError(true);
6801 options.SetIgnoreBreakpoints(true);
6802 options.SetTryAllThreads(true);
6803 options.SetDebug(false);
6805 options.SetTrapExceptions(trap_exceptions);
6806
6807 auto type_system_or_err =
6809 if (!type_system_or_err) {
6810 llvm::consumeError(type_system_or_err.takeError());
6811 return false;
6812 }
6813 auto ts = *type_system_or_err;
6814 if (!ts)
6815 return false;
6816 CompilerType void_ptr_type =
6819 *thread, *address, void_ptr_type, llvm::ArrayRef<addr_t>(), options));
6820 if (call_plan_sp) {
6821 DiagnosticManager diagnostics;
6822
6823 StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
6824 if (frame) {
6825 ExecutionContext exe_ctx;
6826 frame->CalculateExecutionContext(exe_ctx);
6827 ExpressionResults result =
6828 RunThreadPlan(exe_ctx, call_plan_sp, options, diagnostics);
6829 if (result == eExpressionCompleted) {
6830 returned_func =
6831 call_plan_sp->GetReturnValueObject()->GetValueAsUnsigned(
6833
6834 if (GetAddressByteSize() == 4) {
6835 if (returned_func == UINT32_MAX)
6836 return false;
6837 } else if (GetAddressByteSize() == 8) {
6838 if (returned_func == UINT64_MAX)
6839 return false;
6840 }
6841 return true;
6842 }
6843 }
6844 }
6845
6846 return false;
6847}
6848
6849llvm::Expected<const MemoryTagManager *> Process::GetMemoryTagManager() {
6851 const MemoryTagManager *tag_manager =
6852 arch ? arch->GetMemoryTagManager() : nullptr;
6853 if (!arch || !tag_manager) {
6854 return llvm::createStringError(
6855 llvm::inconvertibleErrorCode(),
6856 "This architecture does not support memory tagging");
6857 }
6858
6859 if (!SupportsMemoryTagging()) {
6860 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6861 "Process does not support memory tagging");
6862 }
6863
6864 return tag_manager;
6865}
6866
6867llvm::Expected<std::vector<lldb::addr_t>>
6869 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6871 if (!tag_manager_or_err)
6872 return tag_manager_or_err.takeError();
6873
6874 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6875 llvm::Expected<std::vector<uint8_t>> tag_data =
6876 DoReadMemoryTags(addr, len, tag_manager->GetAllocationTagType());
6877 if (!tag_data)
6878 return tag_data.takeError();
6879
6880 return tag_manager->UnpackTagsData(*tag_data,
6881 len / tag_manager->GetGranuleSize());
6882}
6883
6885 const std::vector<lldb::addr_t> &tags) {
6886 llvm::Expected<const MemoryTagManager *> tag_manager_or_err =
6888 if (!tag_manager_or_err)
6889 return Status::FromError(tag_manager_or_err.takeError());
6890
6891 const MemoryTagManager *tag_manager = *tag_manager_or_err;
6892 llvm::Expected<std::vector<uint8_t>> packed_tags =
6893 tag_manager->PackTags(tags);
6894 if (!packed_tags) {
6895 return Status::FromError(packed_tags.takeError());
6896 }
6897
6898 return DoWriteMemoryTags(addr, len, tag_manager->GetAllocationTagType(),
6899 *packed_tags);
6900}
6901
6902// Create a CoreFileMemoryRange from a MemoryRegionInfo
6905 const addr_t addr = region.GetRange().GetRangeBase();
6906 llvm::AddressRange range(addr, addr + region.GetRange().GetByteSize());
6907 return {range, region.GetLLDBPermissions()};
6908}
6909
6910// Add dirty pages to the core file ranges and return true if dirty pages
6911// were added. Return false if the dirty page information is not valid or in
6912// the region.
6914 CoreFileMemoryRanges &ranges) {
6915 const auto &dirty_page_list = region.GetDirtyPageList();
6916 if (!dirty_page_list)
6917 return false;
6918 const uint32_t lldb_permissions = region.GetLLDBPermissions();
6919 const addr_t page_size = region.GetPageSize();
6920 if (page_size == 0)
6921 return false;
6922 llvm::AddressRange range(0, 0);
6923 for (addr_t page_addr : *dirty_page_list) {
6924 if (range.empty()) {
6925 // No range yet, initialize the range with the current dirty page.
6926 range = llvm::AddressRange(page_addr, page_addr + page_size);
6927 } else {
6928 if (range.end() == page_addr) {
6929 // Combine consective ranges.
6930 range = llvm::AddressRange(range.start(), page_addr + page_size);
6931 } else {
6932 // Add previous contiguous range and init the new range with the
6933 // current dirty page.
6934 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6935 range = llvm::AddressRange(page_addr, page_addr + page_size);
6936 }
6937 }
6938 }
6939 // The last range
6940 if (!range.empty())
6941 ranges.Append(range.start(), range.size(), {range, lldb_permissions});
6942 return true;
6943}
6944
6945// Given a region, add the region to \a ranges.
6946//
6947// Only add the region if it isn't empty and if it has some permissions.
6948// If \a try_dirty_pages is true, then try to add only the dirty pages for a
6949// given region. If the region has dirty page information, only dirty pages
6950// will be added to \a ranges, else the entire range will be added to \a
6951// ranges.
6953 bool try_dirty_pages, CoreFileMemoryRanges &ranges) {
6954 // Don't add empty ranges.
6955 if (region.GetRange().GetByteSize() == 0)
6956 return;
6957 // Don't add ranges with no read permissions.
6958 if ((region.GetLLDBPermissions() & lldb::ePermissionsReadable) == 0)
6959 return;
6960 if (try_dirty_pages && AddDirtyPages(region, ranges))
6961 return;
6962
6963 ranges.Append(region.GetRange().GetRangeBase(),
6964 region.GetRange().GetByteSize(),
6966}
6967
6969 const SaveCoreOptions &options,
6970 CoreFileMemoryRanges &ranges,
6971 std::set<addr_t> &stack_ends) {
6972 DynamicLoader *dyld = process.GetDynamicLoader();
6973 if (!dyld)
6974 return;
6975
6976 std::vector<lldb_private::MemoryRegionInfo> dynamic_loader_mem_regions;
6977 std::function<bool(const lldb_private::Thread &)> save_thread_predicate =
6978 [&](const lldb_private::Thread &t) -> bool {
6979 return options.ShouldThreadBeSaved(t.GetID());
6980 };
6981 dyld->CalculateDynamicSaveCoreRanges(process, dynamic_loader_mem_regions,
6982 save_thread_predicate);
6983 for (const auto &region : dynamic_loader_mem_regions) {
6984 // The Dynamic Loader can give us regions that could include a truncated
6985 // stack
6986 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
6987 AddRegion(region, true, ranges);
6988 }
6989}
6990
6992 const SaveCoreOptions &core_options,
6993 const MemoryRegionInfos &regions,
6994 CoreFileMemoryRanges &ranges,
6995 std::set<addr_t> &stack_ends) {
6996 const bool try_dirty_pages = true;
6997
6998 // Before we take any dump, we want to save off the used portions of the
6999 // stacks and mark those memory regions as saved. This prevents us from saving
7000 // the unused portion of the stack below the stack pointer. Saving space on
7001 // the dump.
7002 for (lldb::ThreadSP thread_sp : process.GetThreadList().Threads()) {
7003 if (!thread_sp)
7004 continue;
7005 StackFrameSP frame_sp = thread_sp->GetStackFrameAtIndex(0);
7006 if (!frame_sp)
7007 continue;
7008 RegisterContextSP reg_ctx_sp = frame_sp->GetRegisterContext();
7009 if (!reg_ctx_sp)
7010 continue;
7011 const addr_t sp = reg_ctx_sp->GetSP();
7012 const size_t red_zone = process.GetABI()->GetRedZoneSize();
7014 if (process.GetMemoryRegionInfo(sp, sp_region).Success()) {
7015 const size_t stack_head = (sp - red_zone);
7016 const size_t stack_size = sp_region.GetRange().GetRangeEnd() - stack_head;
7017 // Even if the SaveCoreOption doesn't want us to save the stack
7018 // we still need to populate the stack_ends set so it doesn't get saved
7019 // off in other calls
7020 sp_region.GetRange().SetRangeBase(stack_head);
7021 sp_region.GetRange().SetByteSize(stack_size);
7022 const addr_t range_end = sp_region.GetRange().GetRangeEnd();
7023 stack_ends.insert(range_end);
7024 // This will return true if the threadlist the user specified is empty,
7025 // or contains the thread id from thread_sp.
7026 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
7027 AddRegion(sp_region, try_dirty_pages, ranges);
7028 }
7029 }
7030 }
7031}
7032
7033// Save all memory regions that are not empty or have at least some permissions
7034// for a full core file style.
7036 const MemoryRegionInfos &regions,
7037 CoreFileMemoryRanges &ranges,
7038 std::set<addr_t> &stack_ends) {
7039
7040 // Don't add only dirty pages, add full regions.
7041 const bool try_dirty_pages = false;
7042 for (const auto &region : regions)
7043 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0)
7044 AddRegion(region, try_dirty_pages, ranges);
7045}
7046
7047// Save only the dirty pages to the core file. Make sure the process has at
7048// least some dirty pages, as some OS versions don't support reporting what
7049// pages are dirty within an memory region. If no memory regions have dirty
7050// page information fall back to saving out all ranges with write permissions.
7052 const MemoryRegionInfos &regions,
7053 CoreFileMemoryRanges &ranges,
7054 std::set<addr_t> &stack_ends) {
7055
7056 // Iterate over the regions and find all dirty pages.
7057 bool have_dirty_page_info = false;
7058 for (const auto &region : regions) {
7059 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7060 AddDirtyPages(region, ranges))
7061 have_dirty_page_info = true;
7062 }
7063
7064 if (!have_dirty_page_info) {
7065 // We didn't find support for reporting dirty pages from the process
7066 // plug-in so fall back to any region with write access permissions.
7067 const bool try_dirty_pages = false;
7068 for (const auto &region : regions)
7069 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7070 region.GetWritable() == eLazyBoolYes)
7071 AddRegion(region, try_dirty_pages, ranges);
7072 }
7073}
7074
7075// Save all thread stacks to the core file. Some OS versions support reporting
7076// when a memory region is stack related. We check on this information, but we
7077// also use the stack pointers of each thread and add those in case the OS
7078// doesn't support reporting stack memory. This function also attempts to only
7079// emit dirty pages from the stack if the memory regions support reporting
7080// dirty regions as this will make the core file smaller. If the process
7081// doesn't support dirty regions, then it will fall back to adding the full
7082// stack region.
7084 const MemoryRegionInfos &regions,
7085 CoreFileMemoryRanges &ranges,
7086 std::set<addr_t> &stack_ends) {
7087 const bool try_dirty_pages = true;
7088 // Some platforms support annotating the region information that tell us that
7089 // it comes from a thread stack. So look for those regions first.
7090
7091 for (const auto &region : regions) {
7092 // Save all the stack memory ranges not associated with a stack pointer.
7093 if (stack_ends.count(region.GetRange().GetRangeEnd()) == 0 &&
7094 region.IsStackMemory() == eLazyBoolYes)
7095 AddRegion(region, try_dirty_pages, ranges);
7096 }
7097}
7098
7099// TODO: We should refactor CoreFileMemoryRanges to use the lldb range type, and
7100// then add an intersect method on it, or MemoryRegionInfo.
7101static lldb_private::MemoryRegionInfo
7104
7106 region_info.SetLLDBPermissions(lhs.GetLLDBPermissions());
7107 region_info.GetRange() = lhs.GetRange().Intersect(rhs);
7108
7109 return region_info;
7110}
7111
7113 const MemoryRegionInfos &regions,
7114 const SaveCoreOptions &options,
7115 CoreFileMemoryRanges &ranges) {
7116 const auto &option_ranges = options.GetCoreFileMemoryRanges();
7117 if (option_ranges.IsEmpty())
7118 return;
7119
7120 for (const auto &range : regions) {
7121 auto *entry = option_ranges.FindEntryThatIntersects(range.GetRange());
7122 if (entry) {
7123 if (*entry != range.GetRange()) {
7124 AddRegion(Intersect(range, *entry), true, ranges);
7125 } else {
7126 // If they match, add the range directly.
7127 AddRegion(range, true, ranges);
7128 }
7129 }
7130 }
7131}
7132
7134 CoreFileMemoryRanges &ranges) {
7136 Status err = GetMemoryRegions(regions);
7137 SaveCoreStyle core_style = options.GetStyle();
7138 if (err.Fail())
7139 return err;
7140 if (regions.empty())
7142 "failed to get any valid memory regions from the process");
7143 if (core_style == eSaveCoreUnspecified)
7145 "callers must set the core_style to something other than "
7146 "eSaveCoreUnspecified");
7147
7148 GetUserSpecifiedCoreFileSaveRanges(*this, regions, options, ranges);
7149
7150 std::set<addr_t> stack_ends;
7151 // For fully custom set ups, we don't want to even look at threads if there
7152 // are no threads specified.
7153 if (core_style != lldb::eSaveCoreCustomOnly ||
7154 options.HasSpecifiedThreads()) {
7155 SaveOffRegionsWithStackPointers(*this, options, regions, ranges,
7156 stack_ends);
7157 // Save off the dynamic loader sections, so if we are on an architecture
7158 // that supports Thread Locals, that we include those as well.
7159 SaveDynamicLoaderSections(*this, options, ranges, stack_ends);
7160 }
7161
7162 switch (core_style) {
7165 break;
7166
7167 case eSaveCoreFull:
7168 GetCoreFileSaveRangesFull(*this, regions, ranges, stack_ends);
7169 break;
7170
7171 case eSaveCoreDirtyOnly:
7172 GetCoreFileSaveRangesDirtyOnly(*this, regions, ranges, stack_ends);
7173 break;
7174
7175 case eSaveCoreStackOnly:
7176 GetCoreFileSaveRangesStackOnly(*this, regions, ranges, stack_ends);
7177 break;
7178 }
7179
7180 if (err.Fail())
7181 return err;
7182
7183 if (ranges.IsEmpty())
7185 "no valid address ranges found for core style");
7186
7187 return ranges.FinalizeCoreFileSaveRanges();
7188}
7189
7190std::vector<ThreadSP>
7192 std::vector<ThreadSP> thread_list;
7193 for (const lldb::ThreadSP &thread_sp : m_thread_list.Threads()) {
7194 if (core_options.ShouldThreadBeSaved(thread_sp->GetID())) {
7195 thread_list.push_back(thread_sp);
7196 }
7197 }
7198
7199 return thread_list;
7200}
7201
7203 uint32_t low_memory_addr_bits = bit_masks.GetLowmemAddressableBits();
7204 uint32_t high_memory_addr_bits = bit_masks.GetHighmemAddressableBits();
7205
7206 if (low_memory_addr_bits == 0 && high_memory_addr_bits == 0)
7207 return;
7208
7209 if (low_memory_addr_bits != 0) {
7210 addr_t low_addr_mask =
7211 AddressableBits::AddressableBitToMask(low_memory_addr_bits);
7212 SetCodeAddressMask(low_addr_mask);
7213 SetDataAddressMask(low_addr_mask);
7214 }
7215
7216 if (high_memory_addr_bits != 0) {
7217 addr_t high_addr_mask =
7218 AddressableBits::AddressableBitToMask(high_memory_addr_bits);
7219 SetHighmemCodeAddressMask(high_addr_mask);
7220 SetHighmemDataAddressMask(high_addr_mask);
7221 }
7222}
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:7035
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:5231
static void SaveDynamicLoaderSections(Process &process, const SaveCoreOptions &options, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6968
static CoreFileMemoryRange CreateCoreFileMemoryRange(const lldb_private::MemoryRegionInfo &region)
Definition Process.cpp:6904
static constexpr unsigned g_string_read_width
Definition Process.cpp:133
static bool AddDirtyPages(const lldb_private::MemoryRegionInfo &region, CoreFileMemoryRanges &ranges)
Definition Process.cpp:6913
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:7112
static void GetCoreFileSaveRangesDirtyOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:7051
static bool ShouldShowError(Process &process)
Definition Process.cpp:1660
static void AddRegion(const lldb_private::MemoryRegionInfo &region, bool try_dirty_pages, CoreFileMemoryRanges &ranges)
Definition Process.cpp:6952
static Timeout< std::micro > GetExpressionTimeout(const EvaluateExpressionOptions &options, bool before_first_timeout)
Definition Process.cpp:5214
static microseconds GetOneThreadExpressionTimeout(const EvaluateExpressionOptions &options)
Definition Process.cpp:5194
static addr_t ComputeConstituentLoadAddress(BreakpointLocation &constituent, Process &proc)
Definition Process.cpp:1680
static lldb_private::MemoryRegionInfo Intersect(const lldb_private::MemoryRegionInfo &lhs, const lldb_private::MemoryRegionInfo::RangeType &rhs)
Definition Process.cpp:7102
static void SaveOffRegionsWithStackPointers(Process &process, const SaveCoreOptions &core_options, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:6991
static void GetCoreFileSaveRangesStackOnly(Process &process, const MemoryRegionInfos &regions, CoreFileMemoryRanges &ranges, std::set< addr_t > &stack_ends)
Definition Process.cpp:7083
@ ePropertyExperimental
Definition Process.cpp:141
#define LLDB_SCOPED_TIMER()
Definition Timer.h:83
void Run() override
Definition Process.cpp:4971
void SetIsRunning(bool running)
Definition Process.cpp:4963
void Cancel() override
Definition Process.cpp:5033
~IOHandlerProcessSTDIO() override=default
void GotEOF() override
Definition Process.cpp:5083
bool Interrupt() override
Definition Process.cpp:5056
NativeFile m_write_file
Definition Process.cpp:5088
IOHandlerProcessSTDIO(Process *process, int write_fd)
Definition Process.cpp:4952
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:224
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:226
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:395
void SetTryAllThreads(bool try_others=true)
Definition Target.h:428
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:416
void SetStopOthers(bool stop_others=true)
Definition Target.h:432
const Timeout< std::micro > & GetTimeout() const
Definition Target.h:414
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:399
const Timeout< std::micro > & GetOneThreadTimeout() const
Definition Target.h:418
friend class Event
Definition Event.h:36
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition Event.h:199
uint32_t GetType() const
Definition Event.h:205
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void SetFrameSP(const lldb::StackFrameSP &frame_sp)
Set accessor to set only the frame shared pointer.
void SetProcessPtr(Process *process)
Set accessor to set only the process shared pointer from a process pointer.
void SetThreadPtr(Thread *thread)
Set accessor to set only the thread shared pointer from a thread pointer.
void SetTargetPtr(Target *target)
Set accessor to set only the target shared pointer from a target pointer.
StackFrame & GetFrameRef() const
Returns a reference to the thread object.
bool HasFrameScope() const
Returns true the ExecutionContext object contains a valid target, process, thread and frame.
void SetFramePtr(StackFrame *frame)
Set accessor to set only the frame shared pointer from a frame pointer.
Process * GetProcessPtr() const
Returns a pointer to the process object.
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
static FileSystem & Instance()
An abstract base class for files.
Definition File.h:36
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
bool GetIsOptimized()
Get whether compiler optimizations were enabled for this function.
Definition Function.cpp: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:90
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:446
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
A plug-in interface definition class for halted OS helpers.
virtual lldb::ThreadSP CreateThread(lldb::tid_t tid, lldb::addr_t context)
static OperatingSystem * FindPlugin(Process *process, const char *plugin_name)
Find a halted OS plugin for a given process.
virtual bool UpdateThreadList(ThreadList &old_thread_list, ThreadList &real_thread_list, ThreadList &new_thread_list)=0
virtual bool DoesPluginReportAllThreads()=0
auto GetPropertyAtIndexAs(size_t idx, const ExecutionContext *exe_ctx=nullptr) const
Property * ProtectedGetPropertyAtIndex(size_t idx)
bool SetPropertyAtIndex(size_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
lldb::PlatformSP GetOrCreate(llvm::StringRef name)
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:79
virtual llvm::StringRef GetPluginName()=0
static llvm::SmallVector< ProcessCreateInstance > GetProcessCreateCallbacks()
static ProcessCreateInstance GetProcessCreateCallbackForPluginName(llvm::StringRef name)
static llvm::SmallVector< StructuredDataPluginCallbacks > GetStructuredDataPluginCallbacks()
static LanguageSet GetAllTypeSystemSupportedLanguagesForTypes()
static PolicyStack & Get()
Definition Policy.h:87
Policy Current() const
Definition Policy.cpp:17
uint32_t GetResumeCount() const
Definition Process.h:155
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3184
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:121
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:3176
EventActionResult PerformAction(lldb::EventSP &event_sp) override
Definition Process.cpp:3119
AttachCompletionHandler(Process *process, uint32_t exec_count)
Definition Process.cpp:3108
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4738
virtual bool ShouldStop(Event *event_ptr, bool &found_valid_stopinfo)
Definition Process.cpp:4506
static void AddRestartedReason(Event *event_ptr, const char *reason)
Definition Process.cpp:4775
void SetInterrupted(bool new_value)
Definition Process.h:489
lldb::ProcessSP GetProcessSP() const
Definition Process.h:437
void SetRestarted(bool new_value)
Definition Process.h:487
static void SetRestartedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4746
static lldb::ProcessSP GetProcessFromEvent(const Event *event_ptr)
Definition Process.cpp:4722
static void SetInterruptedInEvent(Event *event_ptr, bool new_value)
Definition Process.cpp:4792
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:4610
llvm::StringRef GetFlavor() const override
Definition Process.cpp:4502
static bool GetInterruptedFromEvent(const Event *event_ptr)
Definition Process.cpp:4783
const char * GetRestartedReasonAtIndex(size_t idx)
Definition Process.h:444
static bool SetUpdateStateOnRemoval(Event *event_ptr)
Definition Process.cpp:4800
static lldb::StateType GetStateFromEvent(const Event *event_ptr)
Definition Process.cpp:4730
lldb::StateType GetState() const
Definition Process.h:439
static const Process::ProcessEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Process.cpp:4711
static llvm::StringRef GetFlavorString()
Definition Process.cpp:4498
void DoOnRemoval(Event *event_ptr) override
Definition Process.cpp:4624
void Dump(Stream *s) const override
Definition Process.cpp:4698
A plug-in interface definition class for debugging a process.
Definition Process.h:356
virtual Status EnableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2253
Status WillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.cpp:3199
virtual llvm::Expected< TraceSupportedResponse > TraceSupported()
Get the processor tracing type supported for this process.
Definition Process.cpp:6784
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3488
friend class ProcessProperties
Definition Process.h:2466
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:6774
virtual Status DoSignal(int signal)
Sends a process a UNIX signal signal.
Definition Process.h:1201
virtual Status WillResume()
Called before resuming to a process.
Definition Process.h:1088
std::mutex m_process_input_reader_mutex
Definition Process.h:3489
lldb::addr_t m_code_address_mask
Mask for code an data addresses.
Definition Process.h:3538
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1561
std::vector< lldb::addr_t > m_image_tokens
Definition Process.h:3471
virtual Status DoHalt(bool &caused_stop)
Halts a running process.
Definition Process.h:1148
virtual void DidLaunch()
Called after launching a process.
Definition Process.h:1080
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1930
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:539
lldb::break_id_t CreateBreakpointSite(const lldb::BreakpointLocationSP &owner, bool use_hardware)
Definition Process.cpp:1748
virtual Status WillSignal()
Called before sending a signal to a process.
Definition Process.h:1195
void ResetImageToken(size_t token)
Definition Process.cpp:6558
lldb::JITLoaderListUP m_jit_loaders_up
Definition Process.h:3477
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:2688
void SetNextEventAction(Process::NextEventAction *next_event_action)
Definition Process.h:3109
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:3792
virtual Status WillDetach()
Called before detaching from a process.
Definition Process.h:1165
virtual Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.h:1072
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:3473
void ControlPrivateStateThread(uint32_t signal)
Definition Process.cpp:4166
ThreadList & GetThreadList()
Definition Process.h:2347
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7202
virtual DataExtractor GetAuxvData()
Definition Process.cpp:3088
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:5288
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:6483
Status LaunchPrivate(ProcessLaunchInfo &launch_info, lldb::StateType &state, lldb::EventSP &event_sp)
Definition Process.cpp:2887
std::vector< std::string > m_profile_data
Definition Process.h:3497
bool m_can_interpret_function_calls
Definition Process.h:3551
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:3887
virtual void DidExit()
Definition Process.h:1438
std::string m_stdout_data
Remember if stdin must be forwarded to remote debug server.
Definition Process.h:3494
bool RemoveInvalidMemoryRange(const LoadRange &region)
Definition Process.cpp:6234
DelayedBreakpointCache m_delayed_breakpoints
Definition Process.h:3579
uint32_t GetNextThreadIndexID(uint64_t thread_id)
Definition Process.cpp:1260
Status PrivateResume()
The "private" side of resuming a process.
Definition Process.cpp:3512
void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers)
Definition Process.cpp:1557
void SendAsyncInterrupt(Thread *thread=nullptr)
Send an async interrupt request.
Definition Process.cpp:4214
void AddInvalidMemoryRegion(const LoadRange &region)
Definition Process.cpp:6230
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6441
InstrumentationRuntimeCollection m_instrumentation_runtimes
Definition Process.h:3505
std::atomic< bool > m_destructing
Definition Process.h:3526
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:3432
virtual llvm::Error UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action)
Definition Process.cpp:1735
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:3034
@ eBroadcastInternalStateControlResume
Definition Process.h:385
@ eBroadcastInternalStateControlStop
Definition Process.h:383
@ eBroadcastInternalStateControlPause
Definition Process.h:384
int GetExitStatus()
Get the exit status for a process.
Definition Process.cpp:1028
OperatingSystem * GetOperatingSystem()
Definition Process.h:2492
Status WillAttachToProcessWithID(lldb::pid_t pid)
Called before attaching to a process.
Definition Process.cpp:3195
virtual Status DoDetach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.h:1172
std::unique_ptr< UtilityFunction > m_dlopen_utility_func_up
Definition Process.h:3559
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:3436
int64_t ReadSignedIntegerFromMemory(lldb::addr_t load_addr, size_t byte_size, int64_t fail_value, Status &error)
Definition Process.cpp:2482
Address AdvanceAddressToNextBranchInstruction(Address default_stop_addr, AddressRange range_bounds)
Find the next branch instruction to set a breakpoint on.
Definition Process.cpp:6564
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:2789
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:3380
virtual size_t GetAsyncProfileData(char *buf, size_t buf_size, Status &error)
Get any available profile data.
Definition Process.cpp:4881
lldb::addr_t FixDataAddress(lldb::addr_t pc)
Definition Process.cpp:6363
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2677
std::unique_ptr< NextEventAction > m_next_event_action_up
Definition Process.h:3506
void SetHighmemDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6350
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:1182
std::function< IterationAction(lldb_private::Status &error, lldb::addr_t bytes_addr, const void *bytes, lldb::offset_t bytes_size)> ReadMemoryChunkCallback
Definition Process.h:1651
Status EnableBreakpointSiteByID(lldb::user_id_t break_id)
Definition Process.cpp:1628
ProcessModID GetModID() const
Get the Modification ID of the process.
Definition Process.h:1486
size_t ReadMemoryFromInferior(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)
Read of memory from a process.
Definition Process.cpp:2359
size_t ReadScalarIntegerFromMemory(lldb::addr_t addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error)
Definition Process.cpp:2634
virtual Status Launch(ProcessLaunchInfo &launch_info)
Launch a new process.
Definition Process.cpp:2848
std::mutex m_run_thread_plan_lock
Definition Process.h:3554
static void SettingsInitialize()
Definition Process.cpp:5151
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:4865
void Flush()
Flush all data in the process.
Definition Process.cpp:6290
bool m_clear_thread_plans_on_stop
Definition Process.h:3544
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:2313
void ResumePrivateStateThread()
Definition Process.cpp:4148
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:6672
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:3487
virtual void DidSignal()
Called after sending a signal to a process.
Definition Process.h:1219
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2271
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3102
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3441
lldb::StateType GetPrivateState() const
Definition Process.h:3398
void SetPrivateStateNoLock(lldb::StateType new_state)
Definition Process.h:3410
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:3425
uint32_t m_extended_thread_stop_id
The natural stop id when extended_thread_list was last updated.
Definition Process.h:3461
bool PreResumeActionCallback(void *)
Definition Process.h:2672
lldb::RunDirection m_base_direction
ThreadPlanBase run direction.
Definition Process.h:3460
Range< lldb::addr_t, lldb::addr_t > LoadRange
Definition Process.h:388
static constexpr llvm::StringRef ResumeSynchronousHijackListenerName
Definition Process.h:405
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3668
bool WritePointerToMemory(lldb::addr_t vm_addr, lldb::addr_t ptr_value, Status &error)
Definition Process.cpp:2507
QueueList m_queue_list
The list of libdispatch queues at a given stop point.
Definition Process.h:3464
void ClearPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6258
virtual Status WillDestroy()
Definition Process.h:1207
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:3507
void SetCanJIT(bool can_jit)
Sets whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2727
lldb::StateType GetStateChangedEventsPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:993
void LoadOperatingSystemPlugin(bool flush)
Definition Process.cpp:2839
lldb::StructuredDataPluginSP GetStructuredDataPlugin(llvm::StringRef type_name) const
Returns the StructuredDataPlugin associated with a given type name, if there is one.
Definition Process.cpp:4873
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3476
friend class ProcessEventData
Definition Process.h:360
void ResetExtendedCrashInfoDict()
Definition Process.h:2756
AddressRanges FindRangesInMemory(const uint8_t *buf, uint64_t size, const AddressRanges &ranges, size_t alignment, size_t max_matches, Status &error)
Definition Process.cpp:2145
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:6541
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:1770
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2666
std::recursive_mutex m_stdio_communication_mutex
Definition Process.h:3491
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:3468
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:6849
~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:3237
std::recursive_mutex m_profile_data_comm_mutex
Definition Process.h:3496
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1656
lldb::InstrumentationRuntimeSP GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type)
Definition Process.cpp:6532
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:6369
lldb::thread_result_t RunPrivateStateThread(bool is_override)
Definition Process.cpp:4346
virtual Status DoWillLaunch(Module *module)
Called before launching to a process.
Definition Process.h:1053
virtual Status ConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.cpp:3461
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4844
llvm::StringMap< lldb::StructuredDataPluginSP > m_structured_data_plugin_map
Definition Process.h:3555
virtual Status DisableBreakpointSite(BreakpointSite *bp_site)
Definition Process.h:2258
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:6184
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Process.cpp:4812
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:2027
Event * PeekAtStateChangedEvents()
Definition Process.cpp:976
std::vector< Notifications > m_notifications
The list of notifications that this process can deliver.
Definition Process.h:3469
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:2444
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6547
llvm::Error FlushDelayedBreakpoints()
Definition Process.cpp:1718
lldb::StateType GetPrivateStateNoLock() const
Definition Process.h:3404
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:2114
virtual bool DestroyRequiresHalt()
Definition Process.h:1213
lldb::EventSP CreateEventFromProcessState(uint32_t event_type)
Definition Process.cpp:4838
StructuredData::DictionarySP m_crash_info_dict_sp
A repository for extra crash information, consulted in GetExtendedCrashInformation.
Definition Process.h:3567
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:7133
lldb::TargetSP CalculateTarget() override
Definition Process.cpp:4810
bool SetPublicRunLockToStopped()
Definition Process.h:3374
void SetHighmemCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6343
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3897
Status Detach(bool keep_stopped)
Detaches from a running or stopped process.
Definition Process.cpp:3736
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:6868
virtual void DidResume()
Called after resuming a process.
Definition Process.h:1123
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6375
void SetCodeAddressMask(lldb::addr_t code_address_mask)
Definition Process.cpp:6331
AllocatedMemoryCache m_allocated_memory_cache
Definition Process.h:3500
virtual Status LoadCore()
Definition Process.cpp:3019
std::mutex m_exit_status_mutex
Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads.
Definition Process.h:3444
Status Signal(int signal)
Sends a process a UNIX signal signal.
Definition Process.cpp:3877
void SetDynamicLoader(lldb::DynamicLoaderUP dyld)
Definition Process.cpp:3084
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:3453
std::recursive_mutex m_thread_mutex
Definition Process.h:3446
virtual Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp)
Configure asynchronous structured data feature.
Definition Process.cpp:6664
virtual Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch)
Called before attaching to a process.
Definition Process.h:953
bool m_currently_handling_do_on_removals
Definition Process.h:3508
void HandlePrivateEvent(lldb::EventSP &event_sp)
Definition Process.cpp:4226
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4858
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:936
ProcessRunLock & GetRunLock()
Definition Process.cpp:6268
virtual Status DoLoadCore()
Definition Process.h:617
Predicate< uint32_t > m_iohandler_sync
Definition Process.h:3498
LanguageRuntimeCollection m_language_runtimes
Should we detach if the process object goes away with an explicit call to Kill or Detach?
Definition Process.h:3503
virtual Status GetMemoryRegions(lldb_private::MemoryRegionInfos &region_list)
Obtain all the mapped memory regions within this process.
Definition Process.cpp:6627
size_t WriteMemoryPrivate(lldb::addr_t addr, const void *buf, size_t size, Status &error)
Definition Process.cpp:2519
void GetStatus(Stream &ostrm)
Definition Process.cpp:6164
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:3580
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:2764
bool CurrentThreadPosesAsPrivateStateThread()
Definition Process.cpp:6280
void RemoveConstituentFromBreakpointSite(lldb::user_id_t site_id, lldb::user_id_t constituent_id, lldb::BreakpointSiteSP &bp_site_sp)
Definition Process.cpp:1799
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:3628
lldb::OperatingSystemUP m_os_up
Definition Process.h:3483
uint32_t GetLastNaturalStopID() const
Definition Process.h:1498
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:3486
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:3514
void SetDataAddressMask(lldb::addr_t data_address_mask)
Definition Process.cpp:6337
virtual Status DoConnectRemote(llvm::StringRef remote_url)
Attach to a remote system via a URL.
Definition Process.h:965
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:2432
llvm::once_flag m_dlopen_utility_func_flag_once
Definition Process.h:3560
virtual void UpdateQueueListIfNeeded()
Definition Process.cpp:1240
virtual Status UpdateAutomaticSignalFiltering()
Definition Process.cpp:6768
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:3549
virtual Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info)
Attach to an existing process using a process ID.
Definition Process.h:983
llvm::SmallVector< std::optional< std::string > > ReadCStringsFromMemory(llvm::ArrayRef< lldb::addr_t > addresses)
Definition Process.cpp:2238
void SetCanRunCode(bool can_run_code)
Sets whether executing code in this process is possible.
Definition Process.cpp:2731
Status ClearBreakpointSiteByID(lldb::user_id_t break_id)
Definition Process.cpp:1577
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1850
void AppendSTDERR(const char *s, size_t len)
Definition Process.cpp:4851
bool GetShouldDetach() const
Definition Process.h:762
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:3439
bool ProcessIOHandlerExists() const
Definition Process.h:3652
virtual Status DoResume(lldb::RunDirection direction)
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.h:1112
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6739
virtual void DidDestroy()
Definition Process.h:1211
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:2388
lldb::addr_t ReadPointerFromMemory(lldb::addr_t vm_addr, Status &error)
Definition Process.cpp:2493
bool IsBreakpointSiteEnabled(const BreakpointSite &site)
Definition Process.cpp:1642
Broadcaster m_private_state_control_broadcaster
Definition Process.h:3421
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:6313
bool IsRunning() const
Definition Process.cpp:1024
size_t RemoveBreakpointOpcodesFromBuffer(lldb::addr_t addr, size_t size, uint8_t *buf) const
Definition Process.cpp:1813
Broadcaster m_private_state_broadcaster
Definition Process.h:3418
virtual bool DetachRequiresHalt()
Definition Process.h:1184
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:3447
lldb::addr_t m_data_address_mask
Definition Process.h:3539
virtual ArchSpec GetSystemArchitecture()
Get the system architecture for this process.
Definition Process.h:728
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2736
virtual Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2811
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:1017
virtual lldb::addr_t ResolveIndirectFunction(const Address *address, Status &error)
Resolve dynamically loaded indirect functions.
Definition Process.cpp:6411
lldb::StateType m_last_broadcast_state
Definition Process.h:3546
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:3434
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:544
friend class Target
Definition Process.h:362
virtual JITLoaderList & GetJITLoaders()
Definition Process.cpp:3094
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:3465
void PrintWarningOptimization(const SymbolContext &sc)
Print a user-visible warning about a module being built with optimization.
Definition Process.cpp:6475
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:3054
static ProcessProperties & GetGlobalProperties()
Definition Process.cpp:553
lldb::addr_t m_highmem_code_address_mask
Definition Process.h:3540
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6552
int m_exit_status
The exit status of the process, or -1 if not set.
Definition Process.h:3442
std::vector< LanguageRuntime * > GetLanguageRuntimes()
Definition Process.cpp:1488
void SetShouldDetach(bool b)
Definition Process.h:764
bool StartPrivateStateThread(lldb::StateType state, bool run_lock_is_running, std::shared_ptr< PrivateStateThread > *backup_ptr=nullptr)
Definition Process.cpp:4091
MemoryCache m_memory_cache
Definition Process.h:3499
static void STDIOReadThreadBytesReceived(void *baton, const void *src, size_t src_len)
Definition Process.cpp:4944
virtual bool GetProcessInfo(ProcessInstanceInfo &info)
Definition Process.cpp:6501
virtual void DidHalt()
Called after halting a process.
Definition Process.h:1156
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:6357
lldb::StateType WaitForProcessStopPrivate(lldb::EventSP &event_sp, const Timeout< std::micro > &timeout)
Definition Process.cpp:2818
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:3193
bool SetPrivateRunLockToRunning()
Definition Process.h:3368
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:3901
uint32_t GetStopID() const
Definition Process.h:1490
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1402
lldb::addr_t m_highmem_data_address_mask
Definition Process.h:3541
virtual Status DoDestroy()=0
Status StopForDestroyOrDetach(lldb::EventSP &exit_event_sp)
Definition Process.cpp:3684
bool GetWatchpointReportedAfter()
Whether lldb will be notified about watchpoints after the instruction has completed executing,...
Definition Process.cpp:2745
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:3212
bool StateChangedIsExternallyHijacked()
Definition Process.cpp:1384
lldb::StateType GetPublicState() const
Definition Process.h:3392
virtual size_t GetSTDERR(char *buf, size_t buf_size, Status &error)
Get any available STDERR.
Definition Process.cpp:4925
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2535
virtual llvm::Expected< bool > SaveCore(llvm::StringRef outfile)
Save core dump into the specified file.
Definition Process.cpp:3090
bool ProcessIOHandlerIsActive()
Definition Process.cpp:5114
Status DestroyImpl(bool force_kill)
Definition Process.cpp:3800
bool m_force_next_event_delivery
Definition Process.h:3545
lldb::SystemRuntimeUP m_system_runtime_up
Definition Process.h:3484
virtual Status WillHalt()
Called before halting to a process.
Definition Process.h:1131
bool ShouldBroadcastEvent(Event *event_ptr)
This is the part of the event handling that for a process event.
Definition Process.cpp:3905
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3078
std::string m_exit_string
A textual description of why a process exited.
Definition Process.h:3443
lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_up
The functions used by the expression parser to validate data that expressions use.
Definition Process.h:3478
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:3143
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:5095
virtual Status Attach(ProcessAttachInfo &attach_info)
Attach to an existing process using the process attach info.
Definition Process.cpp:3204
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:6306
std::recursive_mutex & GetPrivateStateMutex()
Definition Process.h:3387
virtual bool ShouldUseDelayedBreakpoints() const
Reports whether this process should delay physically enabling/disabling breakpoints until the process...
Definition Process.h:2316
void SynchronouslyNotifyStateChanged(lldb::StateType state)
Definition Process.cpp:635
bool SetPrivateRunLockToStopped()
Definition Process.h:3362
bool CanJIT()
Determines whether executing JIT-compiled code in this process is possible.
Definition Process.cpp:2698
llvm::Error ExecuteBreakpointSiteAction(BreakpointSite &site, Process::BreakpointAction action)
Definition Process.cpp:1601
virtual lldb_private::UUID FindModuleUUID(const llvm::StringRef path)
Definition Process.cpp:6511
virtual Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info)
Attach to an existing process using a partial process name.
Definition Process.h:1004
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3449
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:3892
void SetBaseDirection(lldb::RunDirection direction)
Set the base run direction for the process.
Definition Process.cpp:3505
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:6884
virtual size_t DoReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, Status &error)=0
Actually do the reading of memory from a process.
virtual bool IsLiveDebugSession() const
Check if a process is a live debug session, or a corefile/post-mortem.
Definition Process.h:1534
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3416
virtual void DoDidExec()
Subclasses of Process should implement this function if they need to do anything after a process exec...
Definition Process.h:1029
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:2502
virtual void RefreshStateAfterStop()=0
Currently called as part of ShouldStop.
virtual llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > ReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Read from multiple memory ranges and write the results into buffer.
Definition Process.cpp:2072
lldb::addr_t GetCodeAddressMask()
Get the current address mask in the Process.
Definition Process.cpp:6299
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:6615
friend class DynamicLoader
Definition Process.h:359
static void SettingsTerminate()
Definition Process.cpp:5153
lldb::addr_t GetHighmemDataAddressMask()
Definition Process.cpp:6322
ThreadList m_extended_thread_list
Constituent for extended threads that may be generated, cleared on natural stops.
Definition Process.h:3458
bool CallVoidArgVoidPtrReturn(const Address *address, lldb::addr_t &returned_func, bool trap_exceptions=false)
Definition Process.cpp:6791
bool CurrentThreadIsPrivateStateThread()
Definition Process.cpp:6272
void AddPreResumeAction(PreResumeActionCallback callback, void *baton)
Definition Process.cpp:6239
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition Process.cpp:1843
Status Halt(bool clear_thread_plans=false, bool use_run_lock=true)
Halts a running process.
Definition Process.cpp:3582
lldb::pid_t m_pid
Definition Process.h:3417
const lldb::ABISP & GetABI()
Definition Process.cpp:1482
friend class Debugger
Definition Process.h:358
Status WillLaunch(Module *module)
Called before launching to a process.
Definition Process.cpp:3191
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:7191
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:2616
virtual size_t GetSTDOUT(char *buf, size_t buf_size, Status &error)
Get any available STDOUT.
Definition Process.cpp:4906
lldb::ThreadCollectionSP GetHistoryThreads(lldb::addr_t addr)
Definition Process.cpp:6515
bool PrivateStateThreadIsRunning() const
Definition Process.h:3132
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:3490
std::atomic< bool > m_finalizing
The tid of the thread that issued the async interrupt, used by thread plan timeout.
Definition Process.h:3521
std::recursive_mutex m_language_runtimes_mutex
Definition Process.h:3504
std::string m_stderr_data
Definition Process.h:3495
friend class ThreadList
Definition Process.h:363
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1254
virtual Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true)
Definition Process.cpp:2805
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:5185
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:5178
Module * GetExecutableModulePointer()
Definition Target.cpp:1610
Debugger & GetDebugger() const
Definition Target.h:1323
void UpdateSignalsFromDummy(lldb::UnixSignalsSP signals_sp, lldb::StreamSP warning_stream_sp)
Updates the signals in signals_sp using the stored dummy signals.
Definition Target.cpp:4079
void ClearAllLoadedSections()
Definition Target.cpp:3531
void ClearModules(bool delete_locations)
Definition Target.cpp:1614
Architecture * GetArchitecturePlugin() const
Definition Target.h:1321
TargetStats & GetStatistics()
Definition Target.h:2183
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1756
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2673
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1594
void DidExec()
Called as the last function in Process::DidExec().
Definition Target.cpp:1621
bool RunStopHooks(bool at_initial_stop=false)
Definition Target.cpp:3198
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3421
lldb::PlatformSP GetPlatform()
Definition Target.h:1972
const ArchSpec & GetArchitecture() const
Definition Target.h:1282
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1627
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:1974
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:1997
static void SettingsTerminate()
Definition Thread.cpp:1999
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:3703
"lldb/Expression/UtilityFunction.h" Encapsulates a bit of source code that provides a function that i...
lldb::LanguageType GetObjectRuntimeLanguage()
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define UINT64_MAX
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_ADDRESS_MASK
Address Mask Bits not used for addressing are set to 1 in the mask; all mask bits set is an invalid v...
#define LLDB_INVALID_THREAD_ID
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
@ DoNoSelectMostRelevantFrame
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:327
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
void RegisterAssertFrameRecognizer(Process *process)
Registers the assert stack frame recognizer.
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition State.cpp:68
lldb::ProcessSP(* ProcessCreateInstance)(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
@ eBroadcastAlways
Always send a broadcast when the value is modified.
Definition Predicate.h:29
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:3576
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:417
void(* process_state_changed)(void *baton, Process *process, lldb::StateType state)
Definition Process.h:420
void(* initialize)(void *baton, Process *process)
Definition Process.h:419
The PrivateStateThread struct gathers all the bits of state needed to manage handling Process events,...
Definition Process.h:3266
Process & m_process
The process state that we show to client code.
Definition Process.h:3338
bool IsOnThread(const HostThread &thread) const
Definition Process.cpp:4078
bool m_is_override
This will be the thread name given to the Private State HostThread when it gets spun up.
Definition Process.h:3356
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