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