LLDB mainline
Thread.cpp
Go to the documentation of this file.
1//===-- Thread.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
11#include "lldb/Core/Debugger.h"
13#include "lldb/Core/Module.h"
15#include "lldb/Host/Host.h"
23#include "lldb/Target/ABI.h"
27#include "lldb/Target/Process.h"
33#include "lldb/Target/Target.h"
49#include "lldb/Utility/Log.h"
50#include "lldb/Utility/Policy.h"
53#include "lldb/Utility/State.h"
54#include "lldb/Utility/Stream.h"
59
60#include "llvm/Support/MathExtras.h"
61
62#include <memory>
63#include <optional>
64
65using namespace lldb;
66using namespace lldb_private;
67
69 // NOTE: intentional leak so we don't crash if global destructor chain gets
70 // called as other threads still use the result of this function
71 static ThreadProperties *g_settings_ptr = new ThreadProperties(true);
72 return *g_settings_ptr;
73}
74
75#define LLDB_PROPERTIES_thread
76#include "TargetProperties.inc"
77
78enum {
79#define LLDB_PROPERTIES_thread
80#include "TargetPropertiesEnum.inc"
81};
82
84 : public Cloneable<ThreadOptionValueProperties, OptionValueProperties> {
85public:
86 ThreadOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
87
88 const Property *
90 const ExecutionContext *exe_ctx) const override {
91 // When getting the value for a key from the thread options, we will always
92 // try and grab the setting from the current thread if there is one. Else
93 // we just use the one from this instance.
94 if (exe_ctx) {
95 Thread *thread = exe_ctx->GetThreadPtr();
96 if (thread) {
97 ThreadOptionValueProperties *instance_properties =
98 static_cast<ThreadOptionValueProperties *>(
99 thread->GetValueProperties().get());
100 if (this != instance_properties)
101 return instance_properties->ProtectedGetPropertyAtIndex(idx);
102 }
103 }
104 return ProtectedGetPropertyAtIndex(idx);
105 }
106};
107
109 if (is_global) {
110 m_collection_sp = std::make_shared<ThreadOptionValueProperties>("thread");
111 m_collection_sp->Initialize(g_thread_properties_def);
112 } else
115}
116
118
120 const uint32_t idx = ePropertyStepAvoidRegex;
122}
123
125 const uint32_t idx = ePropertyStepAvoidLibraries;
127}
128
130 const uint32_t idx = ePropertyEnableThreadTrace;
132 idx, g_thread_properties[idx].default_uint_value != 0);
133}
134
136 const uint32_t idx = ePropertyStepInAvoidsNoDebug;
138 idx, g_thread_properties[idx].default_uint_value != 0);
139}
140
142 const uint32_t idx = ePropertyStepOutAvoidsNoDebug;
144 idx, g_thread_properties[idx].default_uint_value != 0);
145}
146
148 const uint32_t idx = ePropertyMaxBacktraceDepth;
150 idx, g_thread_properties[idx].default_uint_value);
151}
152
154 const uint32_t idx = ePropertySingleThreadPlanTimeout;
156 idx, g_thread_properties[idx].default_uint_value);
157}
158
159// Thread Event Data
160
162 return "Thread::ThreadEventData";
163}
164
167
169 const StackID &stack_id)
170 : m_thread_sp(thread_sp), m_stack_id(stack_id) {}
171
173
175
177
180 if (event_ptr) {
181 const EventData *event_data = event_ptr->GetData();
182 if (event_data &&
184 return static_cast<const ThreadEventData *>(event_ptr->GetData());
185 }
186 return nullptr;
187}
188
190 ThreadSP thread_sp;
191 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
192 if (event_data)
193 thread_sp = event_data->GetThread();
194 return thread_sp;
195}
196
198 StackID stack_id;
199 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
200 if (event_data)
201 stack_id = event_data->GetStackID();
202 return stack_id;
203}
204
207 const ThreadEventData *event_data = GetEventDataFromEvent(event_ptr);
208 StackFrameSP frame_sp;
209 if (event_data) {
210 ThreadSP thread_sp = event_data->GetThread();
211 if (thread_sp) {
212 frame_sp = thread_sp->GetStackFrameList()->GetFrameWithStackID(
213 event_data->GetStackID());
214 }
215 }
216 return frame_sp;
217}
218
219// Thread class
220
222 static constexpr llvm::StringLiteral class_name("lldb.thread");
223 return class_name;
224}
225
226Thread::Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id)
227 : ThreadProperties(false), UserID(tid),
228 Broadcaster(process.GetTarget().GetDebugger().GetBroadcasterManager(),
230 m_process_wp(process.shared_from_this()), m_stop_info_sp(),
234 m_index_id(use_invalid_index_id ? LLDB_INVALID_INDEX32
235 : process.GetNextThreadIndexID(tid)),
243 Log *log = GetLog(LLDBLog::Object);
244 LLDB_LOGF(log, "%p Thread::Thread(tid = 0x%4.4" PRIx64 ")",
245 static_cast<void *>(this), GetID());
246
248}
249
251 Log *log = GetLog(LLDBLog::Object);
252 LLDB_LOGF(log, "%p Thread::~Thread(tid = 0x%4.4" PRIx64 ")",
253 static_cast<void *>(this), GetID());
254 /// If you hit this assert, it means your derived class forgot to call
255 /// DestroyThread in its destructor.
256 assert(m_destroy_called);
257}
258
260 m_destroy_called = true;
261 m_stop_info_sp.reset();
262 m_reg_context_sp.reset();
263 m_unwinder_up.reset();
264 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
265 m_curr_frames_sp.reset();
266 m_prev_frames_sp.reset();
268 m_unwinder_frames_sp.reset();
269 m_frame_providers.clear();
270 m_provider_chain_ids.clear();
271 m_frame_lists_by_id.clear();
272 {
273 std::lock_guard<std::mutex> pguard(m_provider_frames_mutex);
275 }
276 m_prev_framezero_pc.reset();
277}
278
281 auto data_sp =
282 std::make_shared<ThreadEventData>(shared_from_this(), new_frame_id);
284 }
285}
286
289 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
290 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
291 stack_frame_list_sp->GetSelectedFrameIndex(select_most_relevant));
292 FrameSelectedCallback(frame_sp.get());
293 return frame_sp;
294}
295
297 bool broadcast) {
298 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
299 if (broadcast)
302 return ret_value;
303}
304
305bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
306 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
307 if (frame_sp) {
308 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
309 if (broadcast)
310 BroadcastSelectedFrameChange(frame_sp->GetStackID());
311 FrameSelectedCallback(frame_sp.get());
312 return true;
313 } else
314 return false;
315}
316
318 Stream &output_stream) {
319 const bool broadcast = true;
320 bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
321 if (success) {
323 if (frame_sp) {
324 bool already_shown = false;
325 SymbolContext frame_sc(
326 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
327 const Debugger &debugger = GetProcess()->GetTarget().GetDebugger();
328 if (debugger.GetUseExternalEditor() && frame_sc.line_entry.GetFile() &&
329 frame_sc.line_entry.line != 0) {
330 if (llvm::Error e = Host::OpenFileInExternalEditor(
331 debugger.GetExternalEditor(), frame_sc.line_entry.GetFile(),
332 frame_sc.line_entry.line)) {
333 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
334 "OpenFileInExternalEditor failed: {0}");
335 } else {
336 already_shown = true;
337 }
338 }
339
340 bool show_frame_info = true;
341 bool show_source = !already_shown;
342 FrameSelectedCallback(frame_sp.get());
343 return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
344 }
345 return false;
346 } else
347 return false;
348}
349
351 if (!frame)
352 return;
353
354 if (frame->HasDebugInformation() &&
355 (GetProcess()->GetWarningsOptimization() ||
356 GetProcess()->GetWarningsUnsupportedLanguage())) {
357 SymbolContext sc =
358 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
359 GetProcess()->PrintWarningOptimization(sc);
360 GetProcess()->PrintWarningUnsupportedLanguage(sc);
361 }
362}
363
366 return m_stop_info_sp;
367
368 ThreadPlanSP completed_plan_sp(GetCompletedPlan());
369 ProcessSP process_sp(GetProcess());
370 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
371
372 // Here we select the stop info according to priorirty: - m_stop_info_sp (if
373 // not trace) - preset value - completed plan stop info - new value with plan
374 // from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -
375 // ask GetPrivateStopInfo to set stop info
376
377 bool have_valid_stop_info = m_stop_info_sp &&
378 m_stop_info_sp ->IsValid() &&
379 m_stop_info_stop_id == stop_id;
380 bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();
381 bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();
382 bool plan_overrides_trace =
383 have_valid_stop_info && have_valid_completed_plan
384 && (m_stop_info_sp->GetStopReason() == eStopReasonTrace);
385
386 if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {
387 return m_stop_info_sp;
388 } else if (completed_plan_sp) {
390 completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());
391 } else {
393 return m_stop_info_sp;
394 }
395}
396
401
403 if (!calculate)
404 return m_stop_info_sp;
405
407 return m_stop_info_sp;
408
409 ProcessSP process_sp(GetProcess());
410 if (process_sp) {
411 const uint32_t process_stop_id = process_sp->GetStopID();
412 if (m_stop_info_stop_id != process_stop_id) {
413 // We preserve the old stop info for a variety of reasons:
414 // 1) Someone has already updated it by the time we get here
415 // 2) We didn't get to execute the breakpoint instruction we stopped at
416 // 3) This is a virtual step so we didn't actually run
417 // 4) If this thread wasn't allowed to run the last time round.
418 if (m_stop_info_sp) {
419 if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
420 GetCurrentPlan()->IsVirtualStep()
423 else
424 m_stop_info_sp.reset();
425 }
426
427 if (!m_stop_info_sp) {
428 if (!CalculateStopInfo())
430 }
431 }
432
433 // The stop info can be manually set by calling Thread::SetStopInfo() prior
434 // to this function ever getting called, so we can't rely on
435 // "m_stop_info_stop_id != process_stop_id" as the condition for the if
436 // statement below, we must also check the stop info to see if we need to
437 // override it. See the header documentation in
438 // Architecture::OverrideStopInfo() for more information on the stop
439 // info override callback.
440 if (m_stop_info_override_stop_id != process_stop_id) {
441 m_stop_info_override_stop_id = process_stop_id;
442 if (m_stop_info_sp) {
443 if (const Architecture *arch =
444 process_sp->GetTarget().GetArchitecturePlugin())
445 arch->OverrideStopInfo(*this);
446 }
447 }
448 }
449
450 // If we were resuming the process and it was interrupted,
451 // return no stop reason. This thread would like to resume.
452 if (m_stop_info_sp && m_stop_info_sp->WasContinueInterrupted(*this))
453 return {};
454
455 return m_stop_info_sp;
456}
457
459 lldb::StopInfoSP stop_info_sp(GetStopInfo());
460 if (stop_info_sp)
461 return stop_info_sp->GetStopReason();
462 return eStopReasonNone;
463}
464
466 ProcessSP process_sp(GetProcess());
467 if (process_sp)
468 return m_stop_info_stop_id == process_sp->GetStopID();
469 else
470 return true; // Process is no longer around so stop info is always up to
471 // date...
472}
473
475 if (m_stop_info_sp) {
476 m_stop_info_sp.reset();
477 }
478}
479
480void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
481 m_stop_info_sp = stop_info_sp;
482 if (m_stop_info_sp) {
483 m_stop_info_sp->MakeStopInfoValid();
484 // If we are overriding the ShouldReportStop, do that here:
486 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
488 }
489
490 ProcessSP process_sp(GetProcess());
491 if (process_sp)
492 m_stop_info_stop_id = process_sp->GetStopID();
493 else
495 Log *log = GetLog(LLDBLog::Thread);
496 LLDB_LOGF(log, "%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
497 static_cast<void *>(this), GetID(),
498 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
500}
501
503 if (vote == eVoteNoOpinion)
504 return;
505 else {
507 if (m_stop_info_sp)
508 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
510 }
511}
512
514 // Note, we can't just NULL out the private reason, or the native thread
515 // implementation will try to go calculate it again. For now, just set it to
516 // a Unix Signal with an invalid signal number.
519}
520
522
524 saved_state.register_backup_sp.reset();
526 if (frame_sp) {
527 lldb::RegisterCheckpointSP reg_checkpoint_sp(
529 if (reg_checkpoint_sp) {
530 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
531 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
532 saved_state.register_backup_sp = reg_checkpoint_sp;
533 }
534 }
535 if (!saved_state.register_backup_sp)
536 return false;
537
538 saved_state.stop_info_sp = GetStopInfo();
539 ProcessSP process_sp(GetProcess());
540 if (process_sp)
541 saved_state.orig_stop_id = process_sp->GetStopID();
543 saved_state.m_completed_plan_checkpoint =
546
547 return true;
548}
549
551 ThreadStateCheckpoint &saved_state) {
552 if (saved_state.register_backup_sp) {
554 if (frame_sp) {
555 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
556 if (reg_ctx_sp) {
557 bool ret =
558 reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
559
560 // Clear out all stack frames as our world just changed.
562 reg_ctx_sp->InvalidateIfNeeded(true);
563 if (m_unwinder_up)
564 m_unwinder_up->Clear();
565 return ret;
566 }
567 }
568 }
569 return false;
570}
571
573 ThreadStateCheckpoint &saved_state) {
574 if (saved_state.stop_info_sp)
575 saved_state.stop_info_sp->MakeStopInfoValid();
576 SetStopInfo(saved_state.stop_info_sp);
577 GetStackFrameList()->SetCurrentInlinedDepth(
578 saved_state.current_inlined_depth);
580 saved_state.m_completed_plan_checkpoint);
582}
583
585 // If any other threads access this we will need a mutex for it
586 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
587 return m_state;
588}
589
591 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
592 m_state = state;
593}
594
597
598 if (!frame_sp)
599 return GetStopDescriptionRaw();
600
601 auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
602
603 if (!recognized_frame_sp)
604 return GetStopDescriptionRaw();
605
606 std::string recognized_stop_description =
607 recognized_frame_sp->GetStopDescription();
608
609 if (!recognized_stop_description.empty())
610 return recognized_stop_description;
611
612 return GetStopDescriptionRaw();
613}
614
616 StopInfoSP stop_info_sp = GetStopInfo();
617 std::string raw_stop_description;
618 if (stop_info_sp && stop_info_sp->IsValid()) {
619 raw_stop_description = stop_info_sp->GetDescription();
620 assert((!raw_stop_description.empty() ||
621 stop_info_sp->GetStopReason() == eStopReasonNone) &&
622 "StopInfo returned an empty description.");
623 }
624 return raw_stop_description;
625}
626
628 ThreadPlan *current_plan = GetCurrentPlan();
629
630 // FIXME: I may decide to disallow threads with no plans. In which
631 // case this should go to an assert.
632
633 if (!current_plan)
634 return;
635
636 current_plan->WillStop();
637}
638
641 // First check whether this thread is going to "actually" resume at all.
642 // For instance, if we're stepping from one level to the next of an
643 // virtual inlined call stack, we just change the inlined call stack index
644 // without actually running this thread. In that case, for this thread we
645 // shouldn't push a step over breakpoint plan or do that work.
646 if (GetCurrentPlan()->IsVirtualStep())
647 return false;
648
649 // If we're at a breakpoint push the step-over breakpoint plan. Do this
650 // before telling the current plan it will resume, since we might change
651 // what the current plan is.
652
654 ProcessSP process_sp(GetProcess());
655 if (reg_ctx_sp && process_sp && direction == eRunForward) {
656 const addr_t thread_pc = reg_ctx_sp->GetPC();
657 BreakpointSiteSP bp_site_sp =
658 process_sp->GetBreakpointSiteList().FindByAddress(thread_pc);
659 // If we're at a BreakpointSite which we have either
660 // 1. already triggered/hit, or
661 // 2. the Breakpoint was added while stopped, or the pc was moved
662 // to this BreakpointSite
663 // Step past the breakpoint before resuming.
664 // If we stopped at a breakpoint instruction/BreakpointSite location
665 // without hitting it, and we're still at that same address on
666 // resuming, then we want to hit the BreakpointSite when we resume.
667 if (bp_site_sp && m_stopped_at_unexecuted_bp != thread_pc) {
668 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
669 // target may not require anything special to step over a breakpoint.
670
671 ThreadPlan *cur_plan = GetCurrentPlan();
672
673 bool push_step_over_bp_plan = false;
674 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
677 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
678 push_step_over_bp_plan = true;
679 } else
680 push_step_over_bp_plan = true;
681
682 if (push_step_over_bp_plan) {
683 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
684 if (step_bp_plan_sp) {
685 step_bp_plan_sp->SetPrivate(true);
686
687 if (GetCurrentPlan()->RunState() != eStateStepping) {
688 ThreadPlanStepOverBreakpoint *step_bp_plan =
689 static_cast<ThreadPlanStepOverBreakpoint *>(
690 step_bp_plan_sp.get());
691 step_bp_plan->SetAutoContinue(true);
692 }
693 QueueThreadPlan(step_bp_plan_sp, false);
694 return true;
695 }
696 }
697 }
698 }
699 }
700 return false;
701}
702
703bool Thread::ShouldResume(StateType resume_state) {
704 // At this point clear the completed plan stack.
707
708 StateType prev_resume_state = GetTemporaryResumeState();
709
710 SetTemporaryResumeState(resume_state);
711
712 lldb::ThreadSP backing_thread_sp(GetBackingThread());
713 if (backing_thread_sp)
714 backing_thread_sp->SetTemporaryResumeState(resume_state);
715
716 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
717 // in the previous run.
718 if (prev_resume_state != eStateSuspended)
720
721 // This is a little dubious, but we are trying to limit how often we actually
722 // fetch stop info from the target, 'cause that slows down single stepping.
723 // So assume that if we got to the point where we're about to resume, and we
724 // haven't yet had to fetch the stop reason, then it doesn't need to know
725 // about the fact that we are resuming...
726 const uint32_t process_stop_id = GetProcess()->GetStopID();
727 if (m_stop_info_stop_id == process_stop_id &&
728 (m_stop_info_sp && m_stop_info_sp->IsValid())) {
729 if (StopInfoSP stop_info_sp = GetPrivateStopInfo())
730 stop_info_sp->WillResume(resume_state);
731 }
732
733 // Tell all the plans that we are about to resume in case they need to clear
734 // any state. We distinguish between the plan on the top of the stack and the
735 // lower plans in case a plan needs to do any special business before it
736 // runs.
737
738 bool need_to_resume = false;
739 ThreadPlan *plan_ptr = GetCurrentPlan();
740 if (plan_ptr) {
741 need_to_resume = plan_ptr->WillResume(resume_state, true);
742
743 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
744 plan_ptr->WillResume(resume_state, false);
745 }
746
747 // If the WillResume for the plan says we are faking a resume, then it will
748 // have set an appropriate stop info. In that case, don't reset it here.
749
750 if (need_to_resume && resume_state != eStateSuspended) {
751 m_stop_info_sp.reset();
752 }
753 }
754
755 if (need_to_resume) {
757
758 // Only reset m_stopped_at_unexecuted_bp if the thread is actually being
759 // resumed. Otherwise, the state of a suspended thread may not be restored
760 // correctly at the next stop. For example, this could happen if the thread
761 // is suspended by ThreadPlanStepOverBreakpoint in another thread, which
762 // temporarily disables the breakpoint that the suspended thread has reached
763 // but not yet executed.
764 if (resume_state != eStateSuspended)
766
767 // Let Thread subclasses do any special work they need to prior to resuming
768 WillResume(resume_state);
769 }
770
771 return need_to_resume;
772}
773
776 // This will get recomputed each time when we stop.
778}
779
781
782bool Thread::ShouldStop(Event *event_ptr) {
783 ThreadPlan *current_plan = GetCurrentPlan();
784
785 bool should_stop = true;
786
787 Log *log = GetLog(LLDBLog::Step);
788
790 LLDB_LOGF(log,
791 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
792 ", should_stop = 0 (ignore since thread was suspended)",
793 __FUNCTION__, GetID(), GetProtocolID());
794 return false;
795 }
796
798 LLDB_LOGF(log,
799 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
800 ", should_stop = 0 (ignore since thread was suspended)",
801 __FUNCTION__, GetID(), GetProtocolID());
802 return false;
803 }
804
805 // Based on the current thread plan and process stop info, check if this
806 // thread caused the process to stop. NOTE: this must take place before the
807 // plan is moved from the current plan stack to the completed plan stack.
809 LLDB_LOGF(log,
810 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
811 ", pc = 0x%16.16" PRIx64
812 ", should_stop = 0 (ignore since no stop reason)",
813 __FUNCTION__, GetID(), GetProtocolID(),
816 return false;
817 }
818
819 // Clear the "must run me before stop" if it was set:
821
822 if (log) {
823 LLDB_LOGF(log,
824 "Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
825 ", pc = 0x%16.16" PRIx64,
826 __FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),
829 LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
830 StreamString s;
831 s.IndentMore();
832 GetProcess()->DumpThreadPlansForTID(
833 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
834 false /* condense_trivial */, true /* skip_unreported */);
835 LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());
836 }
837
838 // The top most plan always gets to do the trace log...
839 current_plan->DoTraceLog();
840
841 // First query the stop info's ShouldStopSynchronous. This handles
842 // "synchronous" stop reasons, for example the breakpoint command on internal
843 // breakpoints. If a synchronous stop reason says we should not stop, then
844 // we don't have to do any more work on this stop.
845 StopInfoSP private_stop_info(GetPrivateStopInfo());
846 if (private_stop_info &&
847 !private_stop_info->ShouldStopSynchronous(event_ptr)) {
848 LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "
849 "stop, returning ShouldStop of false.");
850 return false;
851 }
852
853 // If we've already been restarted, don't query the plans since the state
854 // they would examine is not current.
856 return false;
857
858 // Before the plans see the state of the world, calculate the current inlined
859 // depth.
860 GetStackFrameList()->CalculateCurrentInlinedDepth();
861
862 // If the base plan doesn't understand why we stopped, then we have to find a
863 // plan that does. If that plan is still working, then we don't need to do
864 // any more work. If the plan that explains the stop is done, then we should
865 // pop all the plans below it, and pop it, and then let the plans above it
866 // decide whether they still need to do more work.
867
868 bool done_processing_current_plan = false;
869 if (!current_plan->PlanExplainsStop(event_ptr)) {
870 if (current_plan->TracerExplainsStop()) {
871 done_processing_current_plan = true;
872 should_stop = false;
873 } else {
874 // Leaf plan that does not explain the stop should be popped.
875 // The plan should be push itself later again before resuming to stay
876 // as leaf.
877 if (current_plan->IsLeafPlan())
878 PopPlan();
879
880 // If the current plan doesn't explain the stop, then find one that does
881 // and let it handle the situation.
882 ThreadPlan *plan_ptr = current_plan;
883 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
884 if (plan_ptr->PlanExplainsStop(event_ptr)) {
885 LLDB_LOGF(log, "Plan %s explains stop.", plan_ptr->GetName());
886
887 should_stop = plan_ptr->ShouldStop(event_ptr);
888
889 // plan_ptr explains the stop, next check whether plan_ptr is done,
890 // if so, then we should take it and all the plans below it off the
891 // stack.
892
893 if (plan_ptr->MischiefManaged()) {
894 // We're going to pop the plans up to and including the plan that
895 // explains the stop.
896 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
897
898 do {
899 if (should_stop)
900 current_plan->WillStop();
901 PopPlan();
902 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
903 // Now, if the responsible plan was not "Okay to discard" then
904 // we're done, otherwise we forward this to the next plan in the
905 // stack below.
906 done_processing_current_plan =
907 (plan_ptr->IsControllingPlan() && !plan_ptr->OkayToDiscard());
908 } else {
909 bool should_force_run = plan_ptr->ShouldRunBeforePublicStop();
910 if (should_force_run) {
912 should_stop = false;
913 }
914 done_processing_current_plan = true;
915 }
916 break;
917 }
918 }
919 }
920 }
921
922 if (!done_processing_current_plan) {
923 bool override_stop = false;
924
925 // We're starting from the base plan, so just let it decide;
926 if (current_plan->IsBasePlan()) {
927 should_stop = current_plan->ShouldStop(event_ptr);
928 LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);
929 } else {
930 // Otherwise, don't let the base plan override what the other plans say
931 // to do, since presumably if there were other plans they would know what
932 // to do...
933 while (true) {
934 if (current_plan->IsBasePlan())
935 break;
936
937 should_stop = current_plan->ShouldStop(event_ptr);
938 LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),
939 should_stop);
940 if (current_plan->MischiefManaged()) {
941 if (should_stop)
942 current_plan->WillStop();
943
944 if (current_plan->ShouldAutoContinue(event_ptr)) {
945 override_stop = true;
946 LLDB_LOGF(log, "Plan %s auto-continue: true.",
947 current_plan->GetName());
948 // The ShouldAutoContinue contract: subsequent plans are not asked.
949 PopPlan();
950 break;
951 }
952
953 // If a Controlling Plan wants to stop, we let it. Otherwise, see if
954 // the plan's parent wants to stop.
955
956 PopPlan();
957 if (should_stop && current_plan->IsControllingPlan() &&
958 !current_plan->OkayToDiscard()) {
959 break;
960 }
961
962 current_plan = GetCurrentPlan();
963 if (current_plan == nullptr) {
964 break;
965 }
966 } else {
967 break;
968 }
969 }
970 }
971
972 if (override_stop)
973 should_stop = false;
974 }
975
976 // One other potential problem is that we set up a controlling plan, then stop
977 // in before it is complete - for instance by hitting a breakpoint during a
978 // step-over - then do some step/finish/etc operations that wind up past the
979 // end point condition of the initial plan. We don't want to strand the
980 // original plan on the stack, This code clears stale plans off the stack.
981
982 if (should_stop) {
983 ThreadPlan *plan_ptr = GetCurrentPlan();
984
985 // Discard the stale plans and all plans below them in the stack, plus move
986 // the completed plans to the completed plan stack
987 while (!plan_ptr->IsBasePlan()) {
988 bool stale = plan_ptr->IsPlanStale();
989 ThreadPlan *examined_plan = plan_ptr;
990 plan_ptr = GetPreviousPlan(examined_plan);
991
992 if (stale) {
993 LLDB_LOGF(
994 log,
995 "Plan %s being discarded in cleanup, it says it is already done.",
996 examined_plan->GetName());
997 while (GetCurrentPlan() != examined_plan) {
998 DiscardPlan();
999 }
1000 if (examined_plan->IsPlanComplete()) {
1001 // plan is complete but does not explain the stop (example: step to a
1002 // line with breakpoint), let us move the plan to
1003 // completed_plan_stack anyway
1004 PopPlan();
1005 } else
1006 DiscardPlan();
1007 }
1008 }
1009 }
1010
1011 if (log) {
1012 StreamString s;
1013 s.IndentMore();
1014 GetProcess()->DumpThreadPlansForTID(
1015 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
1016 false /* condense_trivial */, true /* skip_unreported */);
1017 LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
1018 LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
1019 should_stop);
1020 }
1021 return should_stop;
1022}
1023
1025 StateType thread_state = GetResumeState();
1026 StateType temp_thread_state = GetTemporaryResumeState();
1027
1028 Log *log = GetLog(LLDBLog::Step);
1029
1030 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1031 LLDB_LOGF(log,
1032 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1033 ": returning vote %i (state was suspended or invalid)",
1035 return eVoteNoOpinion;
1036 }
1037
1038 if (temp_thread_state == eStateSuspended ||
1039 temp_thread_state == eStateInvalid) {
1040 LLDB_LOGF(log,
1041 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1042 ": returning vote %i (temporary state was suspended or invalid)",
1044 return eVoteNoOpinion;
1045 }
1046
1047 if (!ThreadStoppedForAReason()) {
1048 LLDB_LOGF(log,
1049 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1050 ": returning vote %i (thread didn't stop for a reason.)",
1052 return eVoteNoOpinion;
1053 }
1054
1055 if (GetPlans().AnyCompletedPlans()) {
1056 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1057 // the last plan, regardless of whether it is private or not.
1058 LLDB_LOGF(log,
1059 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1060 ": returning vote for complete stack's back plan",
1061 GetID());
1062 return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);
1063 } else {
1064 Vote thread_vote = eVoteNoOpinion;
1065 ThreadPlan *plan_ptr = GetCurrentPlan();
1066 while (true) {
1067 if (plan_ptr->PlanExplainsStop(event_ptr)) {
1068 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1069 break;
1070 }
1071 if (plan_ptr->IsBasePlan())
1072 break;
1073 else
1074 plan_ptr = GetPreviousPlan(plan_ptr);
1075 }
1076 LLDB_LOGF(log,
1077 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1078 ": returning vote %i for current plan",
1079 GetID(), thread_vote);
1080
1081 return thread_vote;
1082 }
1083}
1084
1086 StateType thread_state = GetResumeState();
1087
1088 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1089 return eVoteNoOpinion;
1090 }
1091
1092 Log *log = GetLog(LLDBLog::Step);
1093 if (GetPlans().AnyCompletedPlans()) {
1094 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1095 // the last plan, regardless of whether it is private or not.
1096 ThreadPlanSP plan = GetPlans().GetCompletedPlan(/*skip_private=*/false);
1097
1098 LLDB_LOGF(log,
1099 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1100 ", %s): %s being asked whether we should report run.",
1101 GetIndexID(), static_cast<void *>(this), GetID(),
1102 StateAsCString(GetTemporaryResumeState()), plan->GetName());
1103
1104 return plan->ShouldReportRun(event_ptr);
1105 } else {
1106 LLDB_LOGF(log,
1107 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1108 ", %s): %s being asked whether we should report run.",
1109 GetIndexID(), static_cast<void *>(this), GetID(),
1111 GetCurrentPlan()->GetName());
1112
1113 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1114 }
1115}
1116
1118 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1119}
1120
1122 ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());
1123 if (plans)
1124 return *plans;
1125
1126 // History threads don't have a thread plan, but they do ask get asked to
1127 // describe themselves, which usually involves pulling out the stop reason.
1128 // That in turn will check for a completed plan on the ThreadPlanStack.
1129 // Instead of special-casing at that point, we return a Stack with a
1130 // ThreadPlanNull as its base plan. That will give the right answers to the
1131 // queries GetDescription makes, and only assert if you try to run the thread.
1133 m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true);
1134 return *m_null_plan_stack_up;
1135}
1136
1137void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {
1138 assert(thread_plan_sp && "Don't push an empty thread plan.");
1139
1140 Log *log = GetLog(LLDBLog::Step);
1141 if (log) {
1142 StreamString s;
1143 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1144 LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1145 static_cast<void *>(this), s.GetData(),
1146 thread_plan_sp->GetThread().GetID());
1147 }
1148
1149 GetPlans().PushPlan(std::move(thread_plan_sp));
1150}
1151
1153 Log *log = GetLog(LLDBLog::Step);
1154 ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();
1155 LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1156 popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());
1157}
1158
1160 Log *log = GetLog(LLDBLog::Step);
1161 ThreadPlanSP discarded_plan_sp = GetPlans().DiscardPlan();
1162
1163 LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1164 discarded_plan_sp->GetName(),
1165 discarded_plan_sp->GetThread().GetID());
1166}
1167
1169 const ThreadPlanStack &plans = GetPlans();
1170 if (!plans.AnyPlans())
1171 return;
1172
1173 // Iterate from the second plan (index: 1) to skip the base plan.
1174 ThreadPlanSP p;
1175 uint32_t i = 1;
1176 while ((p = plans.GetPlanByIndex(i, false))) {
1177 StreamString strm;
1178 p->GetDescription(&strm, eDescriptionLevelInitial);
1179 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1180 i++;
1181 }
1182}
1183
1185 return GetPlans().GetCurrentPlan().get();
1186}
1187
1189 for (ThreadPlan *plan = GetCurrentPlan(); plan;
1190 plan = GetPreviousPlan(plan)) {
1191 if (plan->GetKind() == ThreadPlan::eKindCallFunction)
1192 return true;
1193 }
1194 return false;
1195}
1196
1200
1204
1208
1210 return GetPlans().IsPlanDone(plan);
1211}
1212
1214 return GetPlans().WasPlanDiscarded(plan);
1215}
1216
1220
1222 return GetPlans().GetPreviousPlan(current_plan);
1223}
1224
1226 bool abort_other_plans) {
1227 Status status;
1228 StreamString s;
1229 if (!thread_plan_sp->ValidatePlan(&s)) {
1230 DiscardThreadPlansUpToPlan(thread_plan_sp);
1231 thread_plan_sp.reset();
1232 return Status(s.GetString().str());
1233 }
1234
1235 if (abort_other_plans)
1236 DiscardThreadPlans(true);
1237
1238 PushPlan(thread_plan_sp);
1239
1240 // This seems a little funny, but I don't want to have to split up the
1241 // constructor and the DidPush in the scripted plan, that seems annoying.
1242 // That means the constructor has to be in DidPush. So I have to validate the
1243 // plan AFTER pushing it, and then take it off again...
1244 if (!thread_plan_sp->ValidatePlan(&s)) {
1245 DiscardThreadPlansUpToPlan(thread_plan_sp);
1246 thread_plan_sp.reset();
1247 return Status(s.GetString().str());
1248 }
1249
1250 return status;
1251}
1252
1254 // Count the user thread plans from the back end to get the number of the one
1255 // we want to discard:
1256
1257 ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();
1258 if (up_to_plan_ptr == nullptr)
1259 return false;
1260
1261 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1262 return true;
1263}
1264
1266 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1267}
1268
1270 Log *log = GetLog(LLDBLog::Step);
1271 LLDB_LOGF(log,
1272 "Discarding thread plans for thread tid = 0x%4.4" PRIx64
1273 ", up to %p",
1274 GetID(), static_cast<void *>(up_to_plan_ptr));
1275 GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);
1276}
1277
1279 Log *log = GetLog(LLDBLog::Step);
1280 LLDB_LOGF(log,
1281 "Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1282 ", force %d)",
1283 GetID(), force);
1284
1285 if (force) {
1287 return;
1288 }
1290}
1291
1293 Status error;
1294 ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();
1295 if (!innermost_expr_plan) {
1297 "No expressions currently active on this thread");
1298 return error;
1299 }
1300 DiscardThreadPlansUpToPlan(innermost_expr_plan);
1301 return error;
1302}
1303
1304ThreadPlanSP Thread::QueueBasePlan(bool abort_other_plans) {
1305 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1306 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1307 return thread_plan_sp;
1308}
1309
1311 bool step_over, bool abort_other_plans, bool stop_other_threads,
1312 Status &status) {
1313 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1314 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1315 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1316 return thread_plan_sp;
1317}
1318
1320 bool abort_other_plans, const AddressRange &range,
1321 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1322 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1323 ThreadPlanSP thread_plan_sp;
1324 thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
1325 *this, range, addr_context, stop_other_threads,
1326 step_out_avoids_code_withoug_debug_info);
1327
1328 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1329 return thread_plan_sp;
1330}
1331
1332// Call the QueueThreadPlanForStepOverRange method which takes an address
1333// range.
1335 bool abort_other_plans, const LineEntry &line_entry,
1336 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1337 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1338 const bool include_inlined_functions = true;
1339 auto address_range =
1340 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
1342 abort_other_plans, address_range, addr_context, stop_other_threads,
1343 status, step_out_avoids_code_withoug_debug_info);
1344}
1345
1347 bool abort_other_plans, const AddressRange &range,
1348 const SymbolContext &addr_context, llvm::StringRef step_in_target,
1349 lldb::RunMode stop_other_threads, Status &status,
1350 LazyBool step_in_avoids_code_without_debug_info,
1351 LazyBool step_out_avoids_code_without_debug_info) {
1352 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange(
1353 *this, range, addr_context, step_in_target.str(), stop_other_threads,
1354 step_in_avoids_code_without_debug_info,
1355 step_out_avoids_code_without_debug_info));
1356 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1357 return thread_plan_sp;
1358}
1359
1360// Call the QueueThreadPlanForStepInRange method which takes an address range.
1362 bool abort_other_plans, const LineEntry &line_entry,
1363 const SymbolContext &addr_context, llvm::StringRef step_in_target,
1364 lldb::RunMode stop_other_threads, Status &status,
1365 LazyBool step_in_avoids_code_without_debug_info,
1366 LazyBool step_out_avoids_code_without_debug_info) {
1367 const bool include_inlined_functions = false;
1369 abort_other_plans,
1370 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
1371 addr_context, step_in_target, stop_other_threads, status,
1372 step_in_avoids_code_without_debug_info,
1373 step_out_avoids_code_without_debug_info);
1374}
1375
1377 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1378 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1379 uint32_t frame_idx, Status &status,
1380 LazyBool step_out_avoids_code_without_debug_info) {
1381 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1382 *this, addr_context, first_insn, stop_other_threads, report_stop_vote,
1383 report_run_vote, frame_idx, step_out_avoids_code_without_debug_info));
1384
1385 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1386 return thread_plan_sp;
1387}
1388
1390 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1391 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1392 uint32_t frame_idx, Status &status, bool continue_to_next_branch) {
1393 const bool calculate_return_value =
1394 false; // No need to calculate the return value here.
1395 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1396 *this, stop_other_threads, report_stop_vote, report_run_vote, frame_idx,
1397 continue_to_next_branch, calculate_return_value));
1398
1399 ThreadPlanStepOut *new_plan =
1400 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1401 new_plan->ClearShouldStopHereCallbacks();
1402
1403 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1404 return thread_plan_sp;
1405}
1406
1408 bool abort_other_plans,
1409 bool stop_other_threads,
1410 Status &status) {
1411 ThreadPlanSP thread_plan_sp(
1412 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1413 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1414 return ThreadPlanSP();
1415
1416 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1417 return thread_plan_sp;
1418}
1419
1421 Address &target_addr,
1422 bool stop_other_threads,
1423 Status &status) {
1424 ThreadPlanSP thread_plan_sp(
1425 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1426
1427 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1428 return thread_plan_sp;
1429}
1430
1432 bool abort_other_plans, llvm::ArrayRef<addr_t> address_list,
1433 bool stop_other_threads, uint32_t frame_idx, Status &status) {
1434 ThreadPlanSP thread_plan_sp = std::make_shared<ThreadPlanStepUntil>(
1435 *this, address_list, stop_other_threads, frame_idx);
1436
1437 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1438 return thread_plan_sp;
1439}
1440
1442 bool abort_other_plans, const ScriptedMetadata &scripted_metadata,
1443 bool stop_other_threads, Status &status) {
1444
1445 ThreadPlanSP thread_plan_sp(new ScriptedThreadPlan(*this, scripted_metadata));
1446 thread_plan_sp->SetStopOthers(stop_other_threads);
1447 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1448 return thread_plan_sp;
1449}
1450
1451uint32_t Thread::GetIndexID() const { return m_index_id; }
1452
1454 TargetSP target_sp;
1455 ProcessSP process_sp(GetProcess());
1456 if (process_sp)
1457 target_sp = process_sp->CalculateTarget();
1458 return target_sp;
1459}
1460
1462
1463ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1464
1466
1468 exe_ctx.SetContext(shared_from_this());
1469}
1470
1472 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1474 auto &stack = m_active_frame_providers_by_thread[current];
1476 "Thread::PushProviderFrameList: tid = {0:x}, depth = {1} -> {2}",
1477 GetID(), stack.size(), stack.size() + 1);
1478 stack.push_back(std::move(frames));
1479}
1480
1482 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1484 auto it = m_active_frame_providers_by_thread.find(current);
1485 size_t pre_pop_depth =
1486 (it != m_active_frame_providers_by_thread.end()) ? it->second.size() : 0;
1488 "Thread::PopProviderFrameList: tid = {0:x}, depth = {1} -> {2}",
1489 GetID(), pre_pop_depth, pre_pop_depth ? pre_pop_depth - 1 : 0);
1490 assert(it != m_active_frame_providers_by_thread.end() && !it->second.empty());
1491 if (it == m_active_frame_providers_by_thread.end() || it->second.empty())
1492 return;
1493 it->second.pop_back();
1494 if (it->second.empty())
1496}
1497
1499 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1500 return !m_active_frame_providers_by_thread.empty();
1501}
1502
1504 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1505
1506 // Determine if we must return the parent frames instead of the
1507 // provider-augmented frames on this call.
1508 //
1509 // Frame providers are a public illusion layered on top of the private
1510 // reality (the unwinder stack, or a scripted process playing that
1511 // role). The private state thread (PST) manages the stop of that private
1512 // reality, so the correct view for its logic IS the private reality
1513 // -- the public illusion is only applied once the process has settled
1514 // and clients query the stopped state.
1515 //
1516 // When RunThreadPlan spawns an override PST, the original PST changes
1517 // role: it becomes the public event listener for the override, but it is
1518 // still working to manage the private side of the process. So it also should
1519 // see the private reality and not the public illusion. Feeding it the public
1520 // illusion instead of the private reality is incorrect and can lead to
1521 // deadlocks as a side effect, since provider code may try to acquire locks
1522 // already held further up the call stack.
1523 //
1524 // We return parent frames in two situations:
1525 //
1526 // 1. Re-entrancy: a provider is already active on some host thread.
1527 // - Same thread: the provider's get_frame_at_index() calls
1528 // HandleCommand("bt") or accesses input_frames, which re-enters
1529 // GetStackFrameList() -> infinite recursion.
1530 // - Private state thread: the provider called EvaluateExpression()
1531 // which resumed the process via RunThreadPlan; the private state
1532 // thread must process the resulting stop event, but if it tries to
1533 // build the synthetic frame list it will re-enter the provider ->
1534 // deadlock. Detected via the policy capability below rather than
1535 // thread identity, since m_current_private_state_thread_sp may
1536 // already have been reassigned to an override PST by the time this
1537 // runs.
1538 // - Any other thread: would run the provider concurrently with the
1539 // thread that is already mid-construction.
1540 //
1541 // 2. The current policy disallows loading frame providers (expression
1542 // evaluation on a PST), which requires the private reality.
1543 //
1544 // For case 1, if a provider is active we return its input (parent)
1545 // frames. For case (2), we return/create the unwinder frame list
1546 // without caching it in m_curr_frames_sp so that non-private-state
1547 // callers still get the public illusion once the process settles.
1548 ProcessSP process_sp = GetProcess();
1549 Policy policy = PolicyStack::Get().Current();
1550 {
1551 std::lock_guard<std::mutex> pguard(m_provider_frames_mutex);
1553 // Case 1a: current host thread is inside a provider call.
1555 auto it = m_active_frame_providers_by_thread.find(current);
1556 if (it != m_active_frame_providers_by_thread.end() && !it->second.empty())
1557 return it->second.back();
1558
1559 // Case 1b: private state thread while a provider is active elsewhere.
1561 return m_active_frame_providers_by_thread.begin()->second.back();
1562 }
1563 }
1564
1565 if (m_curr_frames_sp)
1566 return m_curr_frames_sp;
1567
1568 // The private state thread must see the raw unwinder frames, not the
1569 // provider-augmented public view, while it is servicing expression
1570 // evaluation. PushPrivateState(RunningExpression) is pushed by
1571 // RunThreadPlan and by RunPrivateStateThread for override PSTs.
1574 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1575 *this, m_prev_unwinder_frames_sp, true, /*provider_id=*/0);
1576 return m_unwinder_frames_sp;
1577 }
1578
1579 // First, try to load frame providers if we don't have any yet.
1580 if (m_frame_providers.empty()) {
1581 if (process_sp) {
1582 Target &target = process_sp->GetTarget();
1583 const auto &descriptors = target.GetScriptedFrameProviderDescriptors();
1584
1585 // Collect all descriptors that apply to this thread.
1586 std::vector<const ScriptedFrameProviderDescriptor *> thread_descriptors;
1587 for (const auto &entry : descriptors) {
1588 const ScriptedFrameProviderDescriptor &descriptor = entry.second;
1589 if (descriptor.IsValid() && descriptor.AppliesToThread(*this))
1590 thread_descriptors.push_back(&descriptor);
1591 }
1592
1593 // Stable sort by priority so equal-priority providers keep
1594 // their registration (insertion) order.
1595 llvm::stable_sort(
1596 thread_descriptors, [](const ScriptedFrameProviderDescriptor *a,
1598 // nullopt (no priority) sorts last (UINT32_MAX).
1599 uint32_t priority_a = a->GetPriority().value_or(UINT32_MAX);
1600 uint32_t priority_b = b->GetPriority().value_or(UINT32_MAX);
1601 return priority_a < priority_b;
1602 });
1603
1604 // Load ALL matching providers in priority order.
1605 for (const auto *descriptor : thread_descriptors) {
1606 if (llvm::Error error = LoadScriptedFrameProvider(*descriptor)) {
1608 "Failed to load scripted frame provider: {0}");
1609 continue; // Try next provider if this one fails.
1610 }
1611 }
1612 }
1613 }
1614
1615 // Create the frame list based on whether we have providers.
1616 if (!m_provider_chain_ids.empty()) {
1617 // We have providers - use the last one in the chain.
1618 // The last provider has already been chained with all previous providers.
1619 auto [last_desc, last_id] = m_provider_chain_ids.back();
1620 auto it = m_frame_providers.find(last_id);
1621 if (it != m_frame_providers.end()) {
1622 SyntheticFrameProviderSP last_provider = it->second;
1623 StackFrameListSP input_frames = last_provider->GetInputFrames();
1624 m_curr_frames_sp = std::make_shared<SyntheticStackFrameList>(
1625 *this, input_frames, m_prev_frames_sp, true, last_provider, last_id);
1626 } else {
1628 "Missing frame provider (id = {0}) in Thread #{1:x}", last_id,
1629 GetID());
1630 }
1631 }
1632
1633 if (!m_curr_frames_sp) {
1634 // No provider - use normal unwinder frames with stable ID = 0.
1635 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1636 *this, m_prev_unwinder_frames_sp, true, /*provider_id=*/0);
1638 } else {
1639 // Register this frame list by its identifier for later lookup.
1640 m_frame_lists_by_id.insert(
1641 {m_curr_frames_sp->GetIdentifier(), m_curr_frames_sp});
1642 }
1643
1644 return m_curr_frames_sp;
1645}
1646
1649 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1650
1651 // ID 0 is reserved for the unwinder frame list. Always return the unwinder
1652 // frame list for ID 0.
1653 if (id == 0) {
1654 return m_unwinder_frames_sp;
1655 }
1656
1657 auto it = m_frame_lists_by_id.find(id);
1658 if (it != m_frame_lists_by_id.end()) {
1659 auto sp = it->second.lock();
1661 "GetFrameListByIdentifier({0}): found={1}, locked={2}", id, true,
1662 sp != nullptr);
1663 return sp;
1664 }
1665 LLDB_LOG(GetLog(LLDBLog::Thread), "GetFrameListByIdentifier({0}): found={1}",
1666 id, false);
1667 return nullptr;
1668}
1669
1671 const ScriptedFrameProviderDescriptor &descriptor) {
1672 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1673
1674 StackFrameListSP input_frames;
1675 if (m_frame_providers.empty()) {
1676 // First provider gets real unwinder frames with stable ID = 0.
1677 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1678 *this, m_prev_unwinder_frames_sp, true, /*provider_id=*/0);
1679 input_frames = m_unwinder_frames_sp;
1680 } else {
1681 // Subsequent providers wrap the previous provider.
1682 auto [last_desc, last_id] = m_provider_chain_ids.back();
1683 auto it = m_frame_providers.find(last_id);
1684 if (it == m_frame_providers.end())
1685 return llvm::createStringError("previous frame provider not found");
1686 SyntheticFrameProviderSP last_provider = it->second;
1687 StackFrameListSP last_provider_frames = last_provider->GetInputFrames();
1688 input_frames = std::make_shared<SyntheticStackFrameList>(
1689 *this, last_provider_frames, m_prev_frames_sp, true, last_provider,
1690 last_id);
1691 // Register this intermediate frame list so 'bt --provider <id>' can
1692 // show each provider's output independently.
1693 m_frame_lists_by_id.insert({last_id, input_frames});
1695 "Registered intermediate frame list for provider id={0}, "
1696 "use_count={1}",
1697 last_id, input_frames.use_count());
1698 }
1699
1700 // Protect provider construction (__init__) from re-entrancy. If the
1701 // provider calls back into the frame machinery (e.g. HandleCommand("bt"))
1702 // during __init__, GetStackFrameList() will find this thread in the
1703 // active-provider map and return input_frames instead of trying to
1704 // build a new synthetic list — preventing infinite recursion.
1705 PushProviderFrameList(input_frames);
1706 auto provider_or_err =
1707 SyntheticFrameProvider::CreateInstance(input_frames, descriptor);
1709 if (!provider_or_err)
1710 return provider_or_err.takeError();
1711
1712 lldb::frame_list_id_t provider_id = descriptor.GetID();
1713
1714 m_frame_providers.insert({provider_id, *provider_or_err});
1715
1716 // Add to the provider chain.
1717 m_provider_chain_ids.push_back({descriptor, provider_id});
1718
1719 return llvm::Error::success();
1720}
1721
1722llvm::Expected<ScriptedFrameProviderDescriptor>
1724 lldb::frame_list_id_t id) const {
1727
1728 auto it = llvm::find_if(
1730 [id](const std::pair<ScriptedFrameProviderDescriptor,
1731 lldb::frame_list_id_t> &provider_id_pair) {
1732 return provider_id_pair.second == id;
1733 });
1734
1735 if (it == m_provider_chain_ids.end())
1736 return llvm::createStringError(
1737 "Couldn't find ScriptedFrameProviderDescriptor for id = %u.", id);
1738
1739 return it->first;
1740}
1741
1743 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1744 m_frame_providers.clear();
1745 m_provider_chain_ids.clear();
1746 m_frame_lists_by_id.clear();
1747 m_unwinder_frames_sp.reset();
1748 m_curr_frames_sp.reset();
1749 m_prev_frames_sp.reset();
1751}
1752
1753std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1754 return m_prev_framezero_pc;
1755}
1756
1758 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1759
1760 // If any host thread is inside a frame provider call (e.g. the provider
1761 // called EvaluateExpression which resumes the process), don't tear down the
1762 // frame state. The synthetic frame list is still being constructed and the
1763 // thread will stop right back where it was after the expression finishes.
1764 // This must be a global check (not per-host-thread) because the frame state
1765 // is shared and clearing it would destroy in-progress provider work.
1766 if (IsAnyProviderActive())
1767 return;
1768
1769 GetUnwinder().Clear();
1770 m_prev_framezero_pc.reset();
1771 if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1772 m_prev_framezero_pc = reg_ctx_sp->GetPC();
1773
1774 // Only store away the old "reference" StackFrameLists if we got all their
1775 // frames:
1776 // FIXME: At some point we can try to splice in the frames we have fetched
1777 // into the new frame as we make it, but let's not try that now.
1778 if (m_curr_frames_sp && m_curr_frames_sp->WereAllFramesFetched())
1780 if (m_unwinder_frames_sp && m_unwinder_frames_sp->WereAllFramesFetched())
1782 m_curr_frames_sp.reset();
1783 m_unwinder_frames_sp.reset();
1784
1785 // Clear the provider instances and reset the ID counter, but keep the
1786 // chain configuration (m_provider_chain_ids) so providers are re-loaded
1787 // with consistent IDs on the next GetStackFrameList() call.
1788 m_frame_providers.clear();
1789 m_frame_lists_by_id.clear();
1790 m_extended_info.reset();
1792}
1793
1795 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1796}
1797
1799 lldb::ValueObjectSP return_value_sp,
1800 bool broadcast) {
1801 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1802 Status return_error;
1803
1804 if (!frame_sp) {
1805 return_error = Status::FromErrorStringWithFormat(
1806 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1807 frame_idx, GetID());
1808 }
1809
1810 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1811}
1812
1814 lldb::ValueObjectSP return_value_sp,
1815 bool broadcast) {
1816 Status return_error;
1817
1818 if (!frame_sp) {
1819 return_error = Status::FromErrorString("Can't return to a null frame.");
1820 return return_error;
1821 }
1822
1823 Thread *thread = frame_sp->GetThread().get();
1824 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1825 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1826 if (!older_frame_sp) {
1827 return_error = Status::FromErrorString("No older frame to return to.");
1828 return return_error;
1829 }
1830
1831 if (return_value_sp) {
1832 lldb::ABISP abi = thread->GetProcess()->GetABI();
1833 if (!abi) {
1834 return_error =
1835 Status::FromErrorString("Could not find ABI to set return value.");
1836 return return_error;
1837 }
1838 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1839
1840 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1841 // for scalars.
1842 // Turn that back on when that works.
1843 if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1844 Type *function_type = sc.function->GetType();
1845 if (function_type) {
1846 CompilerType return_type =
1848 if (return_type) {
1849 StreamString s;
1850 return_type.DumpTypeDescription(&s);
1851 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1852 if (cast_value_sp) {
1853 cast_value_sp->SetFormat(eFormatHex);
1854 return_value_sp = cast_value_sp;
1855 }
1856 }
1857 }
1858 }
1859
1860 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1861 if (!return_error.Success())
1862 return return_error;
1863 }
1864
1865 // Now write the return registers for the chosen frame: Note, we can't use
1866 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1867 // their data
1868
1869 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1870 if (youngest_frame_sp) {
1871 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1872 if (reg_ctx_sp) {
1873 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1874 older_frame_sp->GetRegisterContext());
1875 if (copy_success) {
1876 thread->DiscardThreadPlans(true);
1877 thread->ClearStackFrames();
1879 auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());
1881 }
1882 } else {
1883 return_error =
1884 Status::FromErrorString("Could not reset register values.");
1885 }
1886 } else {
1887 return_error = Status::FromErrorString("Frame has no register context.");
1888 }
1889 } else {
1890 return_error = Status::FromErrorString("Returned past top frame.");
1891 }
1892 return return_error;
1893}
1894
1895static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1896 ExecutionContextScope *exe_scope) {
1897 for (size_t n = 0; n < list.size(); n++) {
1898 s << "\t";
1899 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1901 s << "\n";
1902 }
1903}
1904
1905Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1906 bool can_leave_function, std::string *warnings) {
1908 Target *target = exe_ctx.GetTargetPtr();
1909 TargetSP target_sp = exe_ctx.GetTargetSP();
1910 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1911 StackFrame *frame = exe_ctx.GetFramePtr();
1912 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1913
1914 // Find candidate locations.
1915 std::vector<Address> candidates, within_function, outside_function;
1916 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1917 within_function, outside_function);
1918
1919 // If possible, we try and stay within the current function. Within a
1920 // function, we accept multiple locations (optimized code may do this,
1921 // there's no solution here so we do the best we can). However if we're
1922 // trying to leave the function, we don't know how to pick the right
1923 // location, so if there's more than one then we bail.
1924 if (!within_function.empty())
1925 candidates = within_function;
1926 else if (outside_function.size() == 1 && can_leave_function)
1927 candidates = outside_function;
1928
1929 // Check if we got anything.
1930 if (candidates.empty()) {
1931 if (outside_function.empty()) {
1933 "Cannot locate an address for {0}:{1}.", file.GetFilename(), line);
1934 } else if (outside_function.size() == 1) {
1936 "{0}:{1} is outside the current function.", file.GetFilename(), line);
1937 } else {
1938 StreamString sstr;
1939 DumpAddressList(sstr, outside_function, target);
1941 "{0}:{1} has multiple candidate locations:\n{2}", file.GetFilename(),
1942 line, sstr.GetData());
1943 }
1944 }
1945
1946 // Accept the first location, warn about any others.
1947 Address dest = candidates[0];
1948 if (warnings && candidates.size() > 1) {
1949 StreamString sstr;
1950 sstr.Format(
1951 "{0}:{1} appears multiple times in this function, selecting the "
1952 "first location:\n",
1953 file.GetFilename(), line);
1954 DumpAddressList(sstr, candidates, target);
1955 *warnings = std::string(sstr.GetString().trim('\n'));
1956 }
1957
1958 if (!reg_ctx->SetPC(dest))
1959 return Status::FromErrorString("Cannot change PC to target address.");
1960
1961 return Status();
1962}
1963
1964bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,
1965 const FormatEntity::Entry *format) {
1966 ExecutionContext exe_ctx(shared_from_this());
1967 Process *process = exe_ctx.GetProcessPtr();
1968 if (!process || !format)
1969 return false;
1970
1971 StackFrameSP frame_sp;
1972 SymbolContext frame_sc;
1973 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1974 frame_sp = GetStackFrameAtIndex(frame_idx);
1975 if (frame_sp) {
1976 exe_ctx.SetFrameSP(frame_sp);
1977 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1978 }
1979 }
1980
1981 return FormatEntity::Formatter(frame_sp ? &frame_sc : nullptr, &exe_ctx,
1982 nullptr, false, false)
1983 .Format(*format, strm);
1984}
1985
1986void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1987 bool stop_format) {
1988 ExecutionContext exe_ctx(shared_from_this());
1989
1990 const FormatEntity::Entry *thread_format;
1991 FormatEntity::Entry format_entry;
1992 if (stop_format) {
1993 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1994 thread_format = &format_entry;
1995 } else {
1996 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1997 thread_format = &format_entry;
1998 }
1999
2000 assert(thread_format);
2001
2002 DumpUsingFormat(strm, frame_idx, thread_format);
2003}
2004
2006
2008
2010 if (m_reg_context_sp)
2011 return m_reg_context_sp->GetThreadPointer();
2012 return LLDB_INVALID_ADDRESS;
2013}
2014
2016 lldb::addr_t tls_file_addr) {
2017 // The default implementation is to ask the dynamic loader for it. This can
2018 // be overridden for specific platforms.
2019 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2020 if (loader)
2021 return loader->GetThreadLocalData(module, shared_from_this(),
2022 tls_file_addr);
2023 else
2024 return LLDB_INVALID_ADDRESS;
2025}
2026
2028 Process *process = GetProcess().get();
2029 if (process) {
2030 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2031 if (loader && loader->IsFullyInitialized() == false)
2032 return false;
2033
2034 SystemRuntime *runtime = process->GetSystemRuntime();
2035 if (runtime) {
2036 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
2037 }
2038 }
2039 return true;
2040}
2041
2044 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
2045}
2046
2048 switch (reason) {
2049 case eStopReasonInvalid:
2050 return "invalid";
2051 case eStopReasonNone:
2052 return "none";
2053 case eStopReasonTrace:
2054 return "trace";
2056 return "breakpoint";
2058 return "watchpoint";
2059 case eStopReasonSignal:
2060 return "signal";
2062 return "exception";
2063 case eStopReasonExec:
2064 return "exec";
2065 case eStopReasonFork:
2066 return "fork";
2067 case eStopReasonVFork:
2068 return "vfork";
2070 return "vfork done";
2072 return "plan complete";
2074 return "thread exiting";
2076 return "instrumentation break";
2078 return "processor trace";
2080 return "async interrupt";
2082 return "history boundary";
2083 }
2084
2085 return "StopReason = " + std::to_string(reason);
2086}
2087
2089 switch (mode) {
2090 case eOnlyThisThread:
2091 return "only this thread";
2092 case eAllThreads:
2093 return "all threads";
2095 return "only during stepping";
2096 }
2097
2098 return "RunMode = " + std::to_string(mode);
2099}
2100
2101size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
2102 uint32_t num_frames, uint32_t num_frames_with_source,
2103 bool stop_format, bool show_hidden, bool only_stacks) {
2104
2105 ExecutionContext exe_ctx(shared_from_this());
2106 Target *target = exe_ctx.GetTargetPtr();
2107 if (!only_stacks) {
2108 Process *process = exe_ctx.GetProcessPtr();
2109 strm.Indent();
2110 bool is_selected = false;
2111 if (process) {
2112 if (process->GetThreadList().GetSelectedThread().get() == this)
2113 is_selected = true;
2114 }
2115 strm.Printf("%c ", is_selected ? '*' : ' ');
2116 if (target && target->GetDebugger().GetUseExternalEditor()) {
2117 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2118 if (frame_sp) {
2119 SymbolContext frame_sc(
2120 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
2121 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {
2122 if (llvm::Error e = Host::OpenFileInExternalEditor(
2123 target->GetDebugger().GetExternalEditor(),
2124 frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {
2125 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
2126 "OpenFileInExternalEditor failed: {0}");
2127 }
2128 }
2129 }
2130 }
2131
2132 DumpUsingSettingsFormat(strm, start_frame, stop_format);
2133 }
2134
2135 size_t num_frames_shown = 0;
2136 if (num_frames > 0) {
2137 strm.IndentMore();
2138
2139 const bool show_frame_info = true;
2140 const bool show_frame_unique = only_stacks;
2141 bool show_selected_frame = false;
2142 if (num_frames == 1 || only_stacks ||
2143 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2144 strm.IndentMore();
2145 else
2146 show_selected_frame = true;
2147
2148 bool show_hidden_marker =
2149 target && target->GetDebugger().GetMarkHiddenFrames();
2150 num_frames_shown = GetStackFrameList()->GetStatus(
2151 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
2152 show_frame_unique, show_hidden, show_hidden_marker,
2153 show_selected_frame);
2154 if (num_frames == 1)
2155 strm.IndentLess();
2156 strm.IndentLess();
2157 }
2158 return num_frames_shown;
2159}
2160
2162 bool print_json_thread, bool print_json_stopinfo) {
2163 const bool stop_format = false;
2164 DumpUsingSettingsFormat(strm, 0, stop_format);
2165 strm.PutCString("\n");
2166
2168
2169 if (print_json_thread || print_json_stopinfo) {
2170 if (thread_info && print_json_thread) {
2171 thread_info->Dump(strm);
2172 strm.PutCString("\n");
2173 }
2174
2175 if (print_json_stopinfo && m_stop_info_sp) {
2176 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2177 if (stop_info) {
2178 stop_info->Dump(strm);
2179 strm.PutCString("\n");
2180 }
2181 }
2182
2183 return true;
2184 }
2185
2186 if (thread_info) {
2187 StructuredData::ObjectSP activity =
2188 thread_info->GetObjectForDotSeparatedPath("activity");
2189 StructuredData::ObjectSP breadcrumb =
2190 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2191 StructuredData::ObjectSP messages =
2192 thread_info->GetObjectForDotSeparatedPath("trace_messages");
2193
2194 bool printed_activity = false;
2195 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
2196 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2197 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2198 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2199 if (name && name->GetType() == eStructuredDataTypeString && id &&
2200 id->GetType() == eStructuredDataTypeInteger) {
2201 strm.Format(" Activity '{0}', {1:x}\n",
2202 name->GetAsString()->GetValue(),
2203 id->GetUnsignedIntegerValue());
2204 }
2205 printed_activity = true;
2206 }
2207 bool printed_breadcrumb = false;
2208 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2209 if (printed_activity)
2210 strm.PutCString("\n");
2211 StructuredData::Dictionary *breadcrumb_dict =
2212 breadcrumb->GetAsDictionary();
2213 StructuredData::ObjectSP breadcrumb_text =
2214 breadcrumb_dict->GetValueForKey("name");
2215 if (breadcrumb_text &&
2216 breadcrumb_text->GetType() == eStructuredDataTypeString) {
2217 strm.Format(" Current Breadcrumb: {0}\n",
2218 breadcrumb_text->GetAsString()->GetValue());
2219 }
2220 printed_breadcrumb = true;
2221 }
2222 if (messages && messages->GetType() == eStructuredDataTypeArray) {
2223 if (printed_breadcrumb)
2224 strm.PutCString("\n");
2225 StructuredData::Array *messages_array = messages->GetAsArray();
2226 const size_t msg_count = messages_array->GetSize();
2227 if (msg_count > 0) {
2228 strm.Printf(" %zu trace messages:\n", msg_count);
2229 for (size_t i = 0; i < msg_count; i++) {
2230 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2231 if (message && message->GetType() == eStructuredDataTypeDictionary) {
2232 StructuredData::Dictionary *message_dict =
2233 message->GetAsDictionary();
2234 StructuredData::ObjectSP message_text =
2235 message_dict->GetValueForKey("message");
2236 if (message_text &&
2237 message_text->GetType() == eStructuredDataTypeString) {
2238 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
2239 }
2240 }
2241 }
2242 }
2243 }
2244 }
2245
2246 return true;
2247}
2248
2249size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2250 uint32_t num_frames, bool show_frame_info,
2251 uint32_t num_frames_with_source,
2252 bool show_hidden) {
2253 ExecutionContext exe_ctx(shared_from_this());
2254 Target *target = exe_ctx.GetTargetPtr();
2255 bool show_hidden_marker =
2256 target && target->GetDebugger().GetMarkHiddenFrames();
2257 return GetStackFrameList()->GetStatus(
2258 strm, first_frame, num_frames, show_frame_info, num_frames_with_source,
2259 /*show_unique*/ false, show_hidden, show_hidden_marker);
2260}
2261
2263 if (!m_unwinder_up)
2264 m_unwinder_up = std::make_unique<UnwindLLDB>(*this);
2265 return *m_unwinder_up;
2266}
2267
2273
2275 // If we are currently stopped at a breakpoint, always return that stopinfo
2276 // and don't reset it. This allows threads to maintain their breakpoint
2277 // stopinfo, such as when thread-stepping in multithreaded programs.
2278 if (m_stop_info_sp) {
2279 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2280 if (stop_reason == lldb::eStopReasonBreakpoint) {
2281 uint64_t value = m_stop_info_sp->GetValue();
2283 if (reg_ctx_sp) {
2284 lldb::addr_t pc = reg_ctx_sp->GetPC();
2285 BreakpointSiteSP bp_site_sp =
2286 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2287 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2288 return true;
2289 }
2290 }
2291 }
2292 return false;
2293}
2294
2295Status Thread::StepIn(bool source_step,
2296 LazyBool step_in_avoids_code_without_debug_info,
2297 LazyBool step_out_avoids_code_without_debug_info)
2298
2299{
2300 Status error;
2301 Process *process = GetProcess().get();
2302 if (StateIsStoppedState(process->GetState(), true)) {
2303 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2304 ThreadPlanSP new_plan_sp;
2305 const lldb::RunMode run_mode = eOnlyThisThread;
2306 const bool abort_other_plans = false;
2307
2308 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2309 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2310 new_plan_sp = QueueThreadPlanForStepInRange(
2311 abort_other_plans, sc.line_entry, sc, llvm::StringRef(), run_mode,
2312 error, step_in_avoids_code_without_debug_info,
2313 step_out_avoids_code_without_debug_info);
2314 } else {
2316 false, abort_other_plans, run_mode, error);
2317 }
2318
2319 new_plan_sp->SetIsControllingPlan(true);
2320 new_plan_sp->SetOkayToDiscard(false);
2321
2322 // Why do we need to set the current thread by ID here???
2324 error = process->Resume();
2325 } else {
2326 error = Status::FromErrorString("process not stopped");
2327 }
2328 return error;
2329}
2330
2331Status Thread::StepOver(bool source_step,
2332 LazyBool step_out_avoids_code_without_debug_info) {
2333 Status error;
2334 Process *process = GetProcess().get();
2335 if (StateIsStoppedState(process->GetState(), true)) {
2336 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2337 ThreadPlanSP new_plan_sp;
2338
2339 const lldb::RunMode run_mode = eOnlyThisThread;
2340 const bool abort_other_plans = false;
2341
2342 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2343 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2344 new_plan_sp = QueueThreadPlanForStepOverRange(
2345 abort_other_plans, sc.line_entry, sc, run_mode, error,
2346 step_out_avoids_code_without_debug_info);
2347 } else {
2349 true, abort_other_plans, run_mode, error);
2350 }
2351
2352 new_plan_sp->SetIsControllingPlan(true);
2353 new_plan_sp->SetOkayToDiscard(false);
2354
2355 // Why do we need to set the current thread by ID here???
2357 error = process->Resume();
2358 } else {
2359 error = Status::FromErrorString("process not stopped");
2360 }
2361 return error;
2362}
2363
2364Status Thread::StepOut(uint32_t frame_idx) {
2365 Status error;
2366 Process *process = GetProcess().get();
2367 if (StateIsStoppedState(process->GetState(), true)) {
2368 const bool first_instruction = false;
2369 const bool stop_other_threads = false;
2370 const bool abort_other_plans = false;
2371
2373 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2374 eVoteYes, eVoteNoOpinion, frame_idx, error));
2375
2376 new_plan_sp->SetIsControllingPlan(true);
2377 new_plan_sp->SetOkayToDiscard(false);
2378
2379 // Why do we need to set the current thread by ID here???
2381 error = process->Resume();
2382 } else {
2383 error = Status::FromErrorString("process not stopped");
2384 }
2385 return error;
2386}
2387
2389 if (auto frame_sp = GetStackFrameAtIndex(0))
2390 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2391 if (auto e = recognized_frame->GetExceptionObject())
2392 return e;
2393
2394 // NOTE: Even though this behavior is generalized, only ObjC is actually
2395 // supported at the moment.
2396 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2397 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2398 return e;
2399 }
2400
2401 return ValueObjectSP();
2402}
2403
2405 ValueObjectSP exception = GetCurrentException();
2406 if (!exception)
2407 return ThreadSP();
2408
2409 // NOTE: Even though this behavior is generalized, only ObjC is actually
2410 // supported at the moment.
2411 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2412 if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2413 return bt;
2414 }
2415
2416 return ThreadSP();
2417}
2418
2420 ProcessSP process_sp = GetProcess();
2421 assert(process_sp);
2422 Target &target = process_sp->GetTarget();
2423 PlatformSP platform_sp = target.GetPlatform();
2424 assert(platform_sp);
2425 ArchSpec arch = target.GetArchitecture();
2426
2427 CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());
2428 if (!type.IsValid())
2430 &target, Status::FromErrorString("no siginfo_t for the platform"));
2431
2432 auto type_size_or_err = type.GetByteSize(nullptr);
2433 if (!type_size_or_err)
2435 &target, Status::FromError(type_size_or_err.takeError()));
2436
2437 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
2438 GetSiginfo(*type_size_or_err);
2439 if (!data)
2440 return ValueObjectConstResult::Create(&target,
2441 Status::FromError(data.takeError()));
2442
2443 DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),
2444 process_sp->GetByteOrder(), arch.GetAddressByteSize()};
2445 return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);
2446}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
static void DumpAddressList(Stream &s, const std::vector< Address > &list, ExecutionContextScope *exe_scope)
Definition Thread.cpp:1895
ThreadOptionValueProperties(llvm::StringRef name)
Definition Thread.cpp:86
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx) const override
Definition Thread.cpp:89
A section + offset based address range class.
A section + offset based address class.
Definition Address.h:62
@ DumpStyleSectionNameOffset
Display as the section name + offset.
Definition Address.h:74
@ DumpStyleResolvedDescription
Display the details about what an address resolves to.
Definition Address.h:104
An architecture specification class.
Definition ArchSpec.h:32
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:894
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:547
bool EventTypeHasListeners(uint32_t event_type)
Broadcaster(lldb::BroadcasterManagerSP manager_sp, std::string name)
Construct with a broadcaster with a name.
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
A class that implements CRTP-based "virtual constructor" idiom.
Definition Cloneable.h:40
Generic representation of a type in a programming language.
llvm::Expected< uint64_t > GetByteSize(ExecutionContextScope *exe_scope) const
Return the size of the type in bytes.
CompilerType GetFunctionReturnType() const
void DumpTypeDescription(lldb::DescriptionLevel level=lldb::eDescriptionLevelFull) const
Dump to stdout.
"lldb/Utility/ArgCompletionRequest.h"
void TryCompleteCurrentArg(llvm::StringRef completion, llvm::StringRef description="")
Adds a possible completion string if the completion would complete the current argument.
A uniqued constant string class.
Definition ConstString.h:40
An data extractor class.
A class to manage flag bits.
Definition Debugger.h:103
bool GetUseExternalEditor() const
Definition Debugger.cpp:521
FormatEntity::Entry GetThreadStopFormat() const
Definition Debugger.cpp:453
llvm::StringRef GetExternalEditor() const
Definition Debugger.cpp:532
FormatEntity::Entry GetThreadFormat() const
Definition Debugger.cpp:448
bool GetMarkHiddenFrames() const
Definition Debugger.cpp:712
A plug-in interface definition class for dynamic loaders.
virtual lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, const lldb::ThreadSP thread, lldb::addr_t tls_file_addr)
Retrieves the per-module TLS block for a given thread.
virtual bool IsFullyInitialized()
Return whether the dynamic loader is fully initialized and it's safe to call its APIs.
friend class Event
Definition Event.h:36
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition Event.h:199
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
"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.
const lldb::TargetSP & GetTargetSP() const
Get accessor to get the target shared pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
void SetContext(const lldb::TargetSP &target_sp, bool get_process)
Target * GetTargetPtr() const
Returns a pointer to the target object.
Target & GetTargetRef() const
Returns a reference to the target object.
Process * GetProcessPtr() const
Returns a pointer to the process object.
RegisterContext * GetRegisterContext() const
Thread * GetThreadPtr() const
Returns a pointer to the thread object.
A file collection class.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
bool Format(const Entry &entry, Stream &s, ValueObject *valobj=nullptr)
CompilerType GetCompilerType()
Definition Function.cpp:585
Type * GetType()
Get accessor for the type that describes the function return value type, and parameter types.
Definition Function.cpp:564
static llvm::Error OpenFileInExternalEditor(llvm::StringRef editor, const FileSpec &file_spec, uint32_t line_no, bool foreground=false)
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
void FindAddressesForLine(const lldb::TargetSP target_sp, const FileSpec &file, uint32_t line, Function *function, std::vector< Address > &output_local, std::vector< Address > &output_extern)
Find addresses by file/line.
Property * ProtectedGetPropertyAtIndex(size_t idx)
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
static PolicyStack & Get()
Definition Policy.cpp:21
Policy Current() const
Definition Policy.cpp:26
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4810
A plug-in interface definition class for debugging a process.
Definition Process.h:369
ThreadList & GetThreadList()
Definition Process.h:2370
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1378
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3149
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1319
lldb::OptionValuePropertiesSP m_collection_sp
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual StackID & GetStackID()
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
virtual bool HasDebugInformation()
Determine whether this StackFrame has debug information available or not.
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
static lldb::StopInfoSP CreateStopReasonWithPlan(lldb::ThreadPlanSP &plan, lldb::ValueObjectSP return_valobj_sp, lldb::ExpressionVariableSP expression_variable_sp)
static lldb::StopInfoSP CreateStopReasonWithSignal(Thread &thread, int signo, const char *description=nullptr, std::optional< int > code=std::nullopt)
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
ObjectSP GetItemAtIndex(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
LineEntry line_entry
The LineEntry for a given query.
static llvm::Expected< lldb::SyntheticFrameProviderSP > CreateInstance(lldb::StackFrameListSP input_frames, const ScriptedFrameProviderDescriptor &descriptor)
Try to create a SyntheticFrameProvider instance for the given input frames and descriptor.
A plug-in interface definition class for system runtimes.
virtual bool SafeToCallFunctionsOnThisThread(lldb::ThreadSP thread_sp)
Determine whether it is safe to run an expression on a given thread.
const llvm::MapVector< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3986
Debugger & GetDebugger() const
Definition Target.h:1366
lldb::PlatformSP GetPlatform()
Definition Target.h:2008
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1283
const ArchSpec & GetArchitecture() const
Definition Target.h:1325
lldb::ThreadSP GetSelectedThread()
bool SetSelectedThreadByID(lldb::tid_t tid, bool notify=false)
void DiscardPlansUpToPlan(ThreadPlan *up_to_plan_ptr)
lldb::ThreadPlanSP GetCompletedPlan(bool skip_private=true) const
lldb::ExpressionVariableSP GetExpressionVariable() const
bool IsPlanDone(ThreadPlan *plan) const
void RestoreCompletedPlanCheckpoint(size_t checkpoint)
lldb::ThreadPlanSP GetPlanByIndex(uint32_t plan_idx, bool skip_private=true) const
lldb::ValueObjectSP GetReturnValueObject() const
void PushPlan(lldb::ThreadPlanSP new_plan_sp)
bool WasPlanDiscarded(ThreadPlan *plan) const
ThreadPlan * GetInnermostExpression() const
lldb::ThreadPlanSP GetCurrentPlan() const
ThreadPlan * GetPreviousPlan(ThreadPlan *current_plan) const
virtual bool IsLeafPlan()
Definition ThreadPlan.h:421
virtual Vote ShouldReportStop(Event *event_ptr)
virtual bool OkayToDiscard()
virtual bool ShouldAutoContinue(Event *event_ptr)
Returns whether this thread plan overrides the ShouldStop of subsequently processed plans.
Definition ThreadPlan.h:389
Vote ShouldReportRun(Event *event_ptr)
const char * GetName() const
Returns the name of this thread plan.
Definition ThreadPlan.h:328
ThreadPlanKind GetKind() const
Definition ThreadPlan.h:450
virtual bool ShouldRunBeforePublicStop()
Definition ThreadPlan.h:408
bool PlanExplainsStop(Event *event_ptr)
bool WillResume(lldb::StateType resume_state, bool current_plan)
virtual bool MischiefManaged()
virtual bool IsPlanStale()
Definition ThreadPlan.h:456
virtual bool WillStop()=0
virtual bool ShouldStop(Event *event_ptr)=0
virtual bool IsBasePlan()
Definition ThreadPlan.h:460
bool GetStepInAvoidsNoDebug() const
Definition Thread.cpp:135
const RegularExpression * GetSymbolsToAvoidRegexp()
The regular expression returned determines symbols that this thread won't stop in during "step-in" op...
Definition Thread.cpp:119
bool GetTraceEnabledState() const
Definition Thread.cpp:129
ThreadProperties(bool is_global)
Definition Thread.cpp:108
uint64_t GetMaxBacktraceDepth() const
Definition Thread.cpp:147
FileSpecList GetLibrariesToAvoid() const
Definition Thread.cpp:124
bool GetStepOutAvoidsNoDebug() const
Definition Thread.cpp:141
uint64_t GetSingleThreadPlanTimeout() const
Definition Thread.cpp:153
bool ThreadPassesBasicTests(Thread &thread) const
static const ThreadEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Thread.cpp:179
static lldb::ThreadSP GetThreadFromEvent(const Event *event_ptr)
Definition Thread.cpp:189
void Dump(Stream *s) const override
Definition Thread.cpp:176
static lldb::StackFrameSP GetStackFrameFromEvent(const Event *event_ptr)
Definition Thread.cpp:206
static llvm::StringRef GetFlavorString()
Definition Thread.cpp:161
ThreadEventData(const lldb::ThreadSP thread_sp)
Definition Thread.cpp:165
lldb::ThreadSP GetThread() const
Definition Thread.h:116
static StackID GetStackIDFromEvent(const Event *event_ptr)
Definition Thread.cpp:197
virtual lldb::ThreadPlanSP QueueThreadPlanForStepOut(bool abort_other_plans, SymbolContext *addr_context, bool first_insn, bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote, uint32_t frame_idx, Status &status, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Queue the plan used to step out of the function at the current PC of thread.
Definition Thread.cpp:1376
bool IsThreadPlanDone(ThreadPlan *plan) const
Checks whether the given plan is in the completed plans for this stop.
Definition Thread.cpp:1209
virtual lldb::user_id_t GetProtocolID() const
Definition Thread.h:1169
lldb::ThreadSP GetCurrentExceptionBacktrace()
Definition Thread.cpp:2404
std::optional< lldb::addr_t > GetPreviousFrameZeroPC()
Request the pc value the thread had when previously stopped.
Definition Thread.cpp:1753
void BroadcastSelectedFrameChange(StackID &new_frame_id)
Definition Thread.cpp:279
@ eBroadcastBitSelectedFrameChanged
Definition Thread.h:80
Status UnwindInnermostExpression()
Unwinds the thread stack for the innermost expression plan currently on the thread plan stack.
Definition Thread.cpp:1292
~Thread() override
Definition Thread.cpp:250
llvm::Expected< ScriptedFrameProviderDescriptor > GetScriptedFrameProviderDescriptorForID(lldb::frame_list_id_t id) const
Definition Thread.cpp:1723
const uint32_t m_index_id
A unique 1 based index assigned to each thread for easy UI/command line access.
Definition Thread.h:1434
void SetShouldRunBeforePublicStop(bool newval)
Definition Thread.h:1279
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition Thread.h:435
bool CompletedPlanOverridesBreakpoint() const
Check if we have completed plan to override breakpoint stop reason.
Definition Thread.cpp:1217
lldb::StackFrameListSP m_curr_frames_sp
The stack frames that get lazily populated after a thread stops.
Definition Thread.h:1445
virtual bool SafeToCallFunctions()
Check whether this thread is safe to run functions.
Definition Thread.cpp:2027
void RestoreThreadStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:572
Status QueueThreadPlan(lldb::ThreadPlanSP &plan_sp, bool abort_other_plans)
Queues a generic thread plan.
Definition Thread.cpp:1225
bool WasThreadPlanDiscarded(ThreadPlan *plan) const
Checks whether the given plan is in the discarded plans for this stop.
Definition Thread.cpp:1213
virtual lldb::RegisterContextSP GetRegisterContext()=0
virtual lldb::addr_t GetThreadPointer()
Retrieves the per-thread data area.
Definition Thread.cpp:2009
virtual void DidStop()
Definition Thread.cpp:780
virtual bool RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:550
friend class ThreadPlan
Definition Thread.h:1367
bool SetupToStepOverBreakpointIfNeeded(lldb::RunDirection direction)
Definition Thread.cpp:639
uint32_t m_stop_info_stop_id
Definition Thread.h:1421
void AutoCompleteThreadPlans(CompletionRequest &request) const
Format the thread plan information for auto completion.
Definition Thread.cpp:1168
std::recursive_mutex m_frame_mutex
Multithreaded protection for m_state.
Definition Thread.h:1442
static void SettingsInitialize()
Definition Thread.cpp:2005
void SetShouldReportStop(Vote vote)
Definition Thread.cpp:502
virtual lldb::StopInfoSP GetPrivateStopInfo(bool calculate=true)
Definition Thread.cpp:402
uint32_t GetIndexID() const
Definition Thread.cpp:1451
std::optional< lldb::addr_t > m_prev_framezero_pc
Frame 0's PC the last time this thread was stopped.
Definition Thread.h:1469
Status ReturnFromFrame(lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1813
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Thread.cpp:1467
void DiscardThreadPlans(bool force)
Discards the plans queued on the plan stack of the current thread.
Definition Thread.cpp:1278
void SetStopInfo(const lldb::StopInfoSP &stop_info_sp)
Definition Thread.cpp:480
bool GetDescription(Stream &s, lldb::DescriptionLevel level, bool print_json_thread, bool print_json_stopinfo)
Definition Thread.cpp:2161
static std::string RunModeAsString(lldb::RunMode mode)
Definition Thread.cpp:2088
void PushProviderFrameList(lldb::StackFrameListSP frames)
Push/pop provider input frames for the current host thread.
Definition Thread.cpp:1471
void SetTemporaryResumeState(lldb::StateType new_state)
Definition Thread.h:1407
virtual bool MatchesSpec(const ThreadSpec *spec)
Definition Thread.cpp:1117
lldb::ProcessSP CalculateProcess() override
Definition Thread.cpp:1461
StructuredData::ObjectSP GetExtendedInfo()
Retrieve a dictionary of information about this thread.
Definition Thread.h:282
virtual lldb::addr_t GetThreadLocalData(const lldb::ModuleSP module, lldb::addr_t tls_file_addr)
Retrieves the per-module TLS block for a thread.
Definition Thread.cpp:2015
void SetStopInfoToNothing()
Definition Thread.cpp:513
virtual void DestroyThread()
Definition Thread.cpp:259
virtual lldb::ThreadPlanSP QueueThreadPlanForRunToAddress(bool abort_other_plans, Address &target_addr, bool stop_other_threads, Status &status)
Gets the plan used to continue from the current PC.
Definition Thread.cpp:1420
virtual lldb::ThreadPlanSP QueueThreadPlanForStepThrough(StackID &return_stack_id, bool abort_other_plans, bool stop_other_threads, Status &status)
Gets the plan used to step through the code that steps from a function call site at the current PC in...
Definition Thread.cpp:1407
lldb::StackFrameSP GetSelectedFrame(SelectMostRelevant select_most_relevant)
Definition Thread.cpp:288
virtual bool IsStillAtLastBreakpointHit()
Definition Thread.cpp:2274
std::recursive_mutex m_state_mutex
Multithreaded protection for m_state.
Definition Thread.h:1440
void PopProviderFrameList()
Definition Thread.cpp:1481
ThreadPlan * GetPreviousPlan(ThreadPlan *plan) const
Definition Thread.cpp:1221
virtual const char * GetName()
Definition Thread.h:290
void PushPlan(lldb::ThreadPlanSP plan_sp)
Definition Thread.cpp:1137
lldb::StackFrameListSP m_prev_frames_sp
The previous stack frames from the last time this thread stopped.
Definition Thread.h:1462
virtual void ClearStackFrames()
Definition Thread.cpp:1757
ThreadPlan * GetCurrentPlan() const
Gets the plan which will execute next on the plan stack.
Definition Thread.cpp:1184
virtual Unwind & GetUnwinder()
Definition Thread.cpp:2262
static llvm::StringRef GetStaticBroadcasterClass()
Definition Thread.cpp:221
void SetResumeSignal(int signal)
Definition Thread.h:166
bool IsAnyProviderActive()
Returns true if any host thread is currently inside a provider.
Definition Thread.cpp:1498
lldb::ValueObjectSP GetReturnValueObject() const
Gets the outer-most return value from the completed plans.
Definition Thread.cpp:1201
virtual lldb::ThreadSP GetBackingThread() const
Definition Thread.h:526
bool IsRunningCallFunctionPlan() const
Returns true if this thread has a ThreadPlanCallFunction on its plan stack, indicating it is running ...
Definition Thread.cpp:1188
lldb::ExpressionVariableSP GetExpressionVariable() const
Gets the outer-most expression variable from the completed plans.
Definition Thread.cpp:1205
Vote ShouldReportRun(Event *event_ptr)
Definition Thread.cpp:1085
lldb::TargetSP CalculateTarget() override
Definition Thread.cpp:1453
static std::string StopReasonAsString(lldb::StopReason reason)
Definition Thread.cpp:2047
lldb::StackFrameListSP GetFrameListByIdentifier(lldb::frame_list_id_t id)
Get a frame list by its unique identifier.
Definition Thread.cpp:1648
virtual void WillResume(lldb::StateType resume_state)
Definition Thread.h:220
Thread(Process &process, lldb::tid_t tid, bool use_invalid_index_id=false)
Constructor.
Definition Thread.cpp:226
lldb::addr_t m_stopped_at_unexecuted_bp
Definition Thread.h:1431
bool ThreadStoppedForAReason()
Definition Thread.cpp:521
size_t GetStackFrameStatus(Stream &strm, uint32_t first_frame, uint32_t num_frames, bool show_frame_info, uint32_t num_frames_with_source, bool show_hidden)
Definition Thread.cpp:2249
std::string GetStopDescriptionRaw()
Definition Thread.cpp:615
void ClearScriptedFrameProvider()
Definition Thread.cpp:1742
bool DiscardUserThreadPlansUpToIndex(uint32_t thread_index)
Discards the plans queued on the plan stack of the current thread up to and including the plan in tha...
Definition Thread.cpp:1253
virtual Status StepOver(bool source_step, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Default implementation for stepping over.
Definition Thread.cpp:2331
bool ShouldResume(lldb::StateType resume_state)
Definition Thread.cpp:703
std::unique_ptr< lldb_private::Unwind > m_unwinder_up
It gets set in Thread::ShouldResume.
Definition Thread.h:1481
std::unique_ptr< ThreadPlanStack > m_null_plan_stack_up
Definition Thread.h:1485
lldb::StateType GetTemporaryResumeState() const
Definition Thread.h:1269
virtual bool CheckpointThreadState(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:523
void SetState(lldb::StateType state)
Definition Thread.cpp:590
llvm::Error LoadScriptedFrameProvider(const ScriptedFrameProviderDescriptor &descriptor)
Definition Thread.cpp:1670
lldb::ProcessSP GetProcess() const
Definition Thread.h:162
lldb::StackFrameSP CalculateStackFrame() override
Definition Thread.cpp:1465
lldb::StateType GetResumeState() const
Gets the USER resume state for this thread.
Definition Thread.h:206
friend class StackFrame
Definition Thread.h:1371
uint32_t SetSelectedFrame(lldb_private::StackFrame *frame, bool broadcast=false)
Definition Thread.cpp:296
virtual lldb::ThreadPlanSP QueueThreadPlanForStepUntil(bool abort_other_plans, llvm::ArrayRef< lldb::addr_t > address_list, bool stop_others, uint32_t frame_idx, Status &status)
Definition Thread.cpp:1431
lldb::StopInfoSP m_stop_info_sp
The private stop reason for this thread.
Definition Thread.h:1420
std::mutex m_provider_frames_mutex
Per-host-thread stack of active provider input frames.
Definition Thread.h:1459
lldb::ProcessWP m_process_wp
The process that owns this thread.
Definition Thread.h:1419
lldb::StackFrameListSP m_prev_unwinder_frames_sp
The unwinder frame list from the last time this thread stopped.
Definition Thread.h:1467
void DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, bool stop_format)
Definition Thread.cpp:1986
LazyBool m_override_should_notify
Definition Thread.h:1484
lldb::ThreadSP CalculateThread() override
Definition Thread.cpp:1463
Status ReturnFromFrameWithIndex(uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1798
virtual Status StepOut(uint32_t frame_idx=0)
Default implementation for stepping out.
Definition Thread.cpp:2364
virtual llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > GetSiginfo(size_t max_size) const
Definition Thread.h:1414
lldb::StateType GetState() const
Definition Thread.cpp:584
lldb::StateType m_state
The state of our process.
Definition Thread.h:1438
bool m_extended_info_fetched
Definition Thread.h:1505
void CalculatePublicStopInfo()
Definition Thread.cpp:397
static void SettingsTerminate()
Definition Thread.cpp:2007
bool SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast=false)
Definition Thread.cpp:305
lldb::StopReason GetStopReason()
Definition Thread.cpp:458
ThreadPlanStack & GetPlans() const
Definition Thread.cpp:1121
lldb::ValueObjectSP GetSiginfoValue()
Definition Thread.cpp:2419
virtual lldb::ThreadPlanSP QueueThreadPlanForStepSingleInstruction(bool step_over, bool abort_other_plans, bool stop_other_threads, Status &status)
Queues the plan used to step one instruction from the current PC of thread.
Definition Thread.cpp:1310
uint32_t m_stop_info_override_stop_id
Definition Thread.h:1425
int m_resume_signal
The signal that should be used when continuing this thread.
Definition Thread.h:1471
virtual void DidResume()
Definition Thread.cpp:774
bool StopInfoIsUpToDate() const
Definition Thread.cpp:465
lldb::StackFrameSP GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr)
Definition Thread.cpp:2043
llvm::DenseMap< lldb::frame_list_id_t, lldb::SyntheticFrameProviderSP > m_frame_providers
Map from frame list ID to its frame provider.
Definition Thread.h:1493
lldb::ThreadPlanSP GetCompletedPlan() const
Gets the outer-most plan that was popped off the plan stack in the most recent stop.
Definition Thread.cpp:1197
lldb::ValueObjectSP GetCurrentException()
Definition Thread.cpp:2388
virtual lldb::ThreadPlanSP QueueThreadPlanForStepOutNoShouldStop(bool abort_other_plans, SymbolContext *addr_context, bool first_insn, bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote, uint32_t frame_idx, Status &status, bool continue_to_next_branch=false)
Queue the plan used to step out of the function at the current PC of a thread.
Definition Thread.cpp:1389
virtual lldb::StackFrameSP GetFrameWithConcreteFrameIndex(uint32_t unwind_idx)
Definition Thread.cpp:1794
bool ShouldStop(Event *event_ptr)
Definition Thread.cpp:782
Status JumpToLine(const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings=nullptr)
Definition Thread.cpp:1905
bool DumpUsingFormat(Stream &strm, uint32_t frame_idx, const FormatEntity::Entry *format)
Print a description of this thread using the provided thread format.
Definition Thread.cpp:1964
void DiscardThreadPlansUpToPlan(lldb::ThreadPlanSP &up_to_plan_sp)
Discards the plans queued on the plan stack of the current thread up to and including up_to_plan_sp.
Definition Thread.cpp:1265
void FrameSelectedCallback(lldb_private::StackFrame *frame)
Definition Thread.cpp:350
lldb::ThreadPlanSP QueueBasePlan(bool abort_other_plans)
Queues the base plan for a thread.
Definition Thread.cpp:1304
static ThreadProperties & GetGlobalProperties()
Definition Thread.cpp:68
uint32_t GetCurrentInlinedDepth()
Definition Thread.h:446
llvm::DenseMap< HostThread, std::vector< lldb::StackFrameListSP > > m_active_frame_providers_by_thread
Definition Thread.h:1461
virtual lldb::ThreadPlanSP QueueThreadPlanForStepOverRange(bool abort_other_plans, const AddressRange &range, const SymbolContext &addr_context, lldb::RunMode stop_other_threads, Status &status, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Queues the plan used to step through an address range, stepping over function calls.
Definition Thread.cpp:1319
std::string GetStopDescription()
Definition Thread.cpp:595
virtual lldb::ThreadPlanSP QueueThreadPlanForStepScripted(bool abort_other_plans, const ScriptedMetadata &scripted_metadata, bool stop_other_threads, Status &status)
Definition Thread.cpp:1441
StructuredData::ObjectSP m_extended_info
Definition Thread.h:1507
lldb::StopInfoSP GetStopInfo()
Definition Thread.cpp:364
virtual lldb::ThreadPlanSP QueueThreadPlanForStepInRange(bool abort_other_plans, const AddressRange &range, const SymbolContext &addr_context, llvm::StringRef step_in_target, lldb::RunMode stop_other_threads, Status &status, LazyBool step_in_avoids_code_without_debug_info=eLazyBoolCalculate, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Queues the plan used to step through an address range, stepping into functions.
Definition Thread.cpp:1346
llvm::DenseMap< lldb::frame_list_id_t, lldb::StackFrameListWP > m_frame_lists_by_id
Map from frame list identifier to frame list weak pointer.
Definition Thread.h:1502
lldb::StateType m_temporary_resume_state
This state records what the thread was told to do by the thread plan logic for the current resume.
Definition Thread.h:1476
lldb::StackFrameListSP GetStackFrameList()
Definition Thread.cpp:1503
bool m_should_run_before_public_stop
Definition Thread.h:1428
Vote ShouldReportStop(Event *event_ptr)
Definition Thread.cpp:1024
bool SetSelectedFrameByIndexNoisily(uint32_t frame_idx, Stream &output_stream)
Definition Thread.cpp:317
virtual bool CalculateStopInfo()=0
Ask the thread subclass to set its stop info.
std::vector< std::pair< ScriptedFrameProviderDescriptor, lldb::frame_list_id_t > > m_provider_chain_ids
Ordered chain of provider IDs.
Definition Thread.h:1498
lldb::StateType m_resume_state
This state is used to force a thread to be suspended from outside the ThreadPlan logic.
Definition Thread.h:1473
virtual Status StepIn(bool source_step, LazyBool step_in_avoids_code_without_debug_info=eLazyBoolCalculate, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Default implementation for stepping into.
Definition Thread.cpp:2295
size_t GetStatus(Stream &strm, uint32_t start_frame, uint32_t num_frames, uint32_t num_frames_with_source, bool stop_format, bool show_hidden, bool only_stacks=false)
Definition Thread.cpp:2101
lldb::RegisterContextSP m_reg_context_sp
The register context for this thread's current register state.
Definition Thread.h:1436
lldb::StackFrameListSP m_unwinder_frames_sp
The unwinder frame list (ID 0).
Definition Thread.h:1444
static lldb::ValueObjectSP Create(ExecutionContextScope *exe_scope, lldb::ByteOrder byte_order, uint32_t addr_byte_size, lldb::addr_t address=LLDB_INVALID_ADDRESS, ValueObjectManager *manager=nullptr)
These routines create ValueObjectConstResult ValueObjects from various data sources.
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_INDEX32
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_UNWINDER_FRAME_LIST_ID
#define LLDB_INVALID_FRAME_ID
@ DoNoSelectMostRelevantFrame
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:338
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
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
std::shared_ptr< lldb_private::SyntheticFrameProvider > SyntheticFrameProviderSP
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
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelInitial
@ eDescriptionLevelFull
@ eDescriptionLevelVerbose
RunDirection
Execution directions.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
std::shared_ptr< lldb_private::Platform > PlatformSP
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ 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.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
int32_t break_id_t
Definition lldb-types.h:88
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
uint64_t addr_t
Definition lldb-types.h:80
StopReason
Thread stop reasons.
@ eStopReasonInstrumentation
@ eStopReasonPlanComplete
@ eStopReasonHistoryBoundary
@ eStopReasonBreakpoint
@ eStopReasonExec
Program was re-exec'ed.
@ eStopReasonVForkDone
@ eStopReasonInterrupt
Thread requested interrupt.
@ eStopReasonProcessorTrace
@ eStopReasonThreadExiting
@ eStopReasonException
@ eStopReasonWatchpoint
std::shared_ptr< lldb_private::Target > TargetSP
@ eStructuredDataTypeDictionary
@ eStructuredDataTypeInteger
@ eStructuredDataTypeArray
@ eStructuredDataTypeString
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
RunMode
Thread Run Modes.
@ eOnlyDuringStepping
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::RegisterCheckpoint > RegisterCheckpointSP
std::shared_ptr< lldb_private::StackFrameList > StackFrameListSP
uint32_t frame_list_id_t
Definition lldb-types.h:87
A line table entry class.
Definition LineEntry.h:21
AddressRange GetSameLineContiguousAddressRange(bool include_inlined_functions) const
Give the range for this LineEntry + any additional LineEntries for this same source line that are con...
uint32_t line
The source line number, or LLDB_INVALID_LINE_NUMBER if there is no line number information.
Definition LineEntry.h:151
const FileSpec & GetFile() const
Helper to access the file.
Definition LineEntry.h:134
Describes what view of the process a thread should see and what operations it is allowed to perform.
Definition Policy.h:33
Capabilities capabilities
Definition Policy.h:67
This struct contains the metadata needed to instantiate a frame provider and optional filters to cont...
uint32_t GetID() const
Get a unique identifier for this descriptor.
bool AppliesToThread(Thread &thread) const
Check if this descriptor applies to the given thread.
bool IsValid() const
Check if this descriptor has valid metadata for script-based providers.
std::optional< uint32_t > GetPriority() const
Get the priority of this frame provider.
lldb::RegisterCheckpointSP register_backup_sp
Definition Thread.h:135
UserID(lldb::user_id_t uid=LLDB_INVALID_UID)
Construct with optional user ID.
Definition UserID.h:33
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47