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