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