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();
267 m_unwinder_frames_sp.reset();
268 m_frame_providers.clear();
269 m_provider_chain_ids.clear();
270 m_frame_lists_by_id.clear();
271 {
272 std::lock_guard<std::mutex> pguard(m_provider_frames_mutex);
274 }
275 m_prev_framezero_pc.reset();
276}
277
280 auto data_sp =
281 std::make_shared<ThreadEventData>(shared_from_this(), new_frame_id);
283 }
284}
285
288 StackFrameListSP stack_frame_list_sp(GetStackFrameList());
289 StackFrameSP frame_sp = stack_frame_list_sp->GetFrameAtIndex(
290 stack_frame_list_sp->GetSelectedFrameIndex(select_most_relevant));
291 FrameSelectedCallback(frame_sp.get());
292 return frame_sp;
293}
294
296 bool broadcast) {
297 uint32_t ret_value = GetStackFrameList()->SetSelectedFrame(frame);
298 if (broadcast)
301 return ret_value;
302}
303
304bool Thread::SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast) {
305 StackFrameSP frame_sp(GetStackFrameList()->GetFrameAtIndex(frame_idx));
306 if (frame_sp) {
307 GetStackFrameList()->SetSelectedFrame(frame_sp.get());
308 if (broadcast)
309 BroadcastSelectedFrameChange(frame_sp->GetStackID());
310 FrameSelectedCallback(frame_sp.get());
311 return true;
312 } else
313 return false;
314}
315
317 Stream &output_stream) {
318 const bool broadcast = true;
319 bool success = SetSelectedFrameByIndex(frame_idx, broadcast);
320 if (success) {
322 if (frame_sp) {
323 bool already_shown = false;
324 SymbolContext frame_sc(
325 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
326 const Debugger &debugger = GetProcess()->GetTarget().GetDebugger();
327 if (debugger.GetUseExternalEditor() && frame_sc.line_entry.GetFile() &&
328 frame_sc.line_entry.line != 0) {
329 if (llvm::Error e = Host::OpenFileInExternalEditor(
330 debugger.GetExternalEditor(), frame_sc.line_entry.GetFile(),
331 frame_sc.line_entry.line)) {
332 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
333 "OpenFileInExternalEditor failed: {0}");
334 } else {
335 already_shown = true;
336 }
337 }
338
339 bool show_frame_info = true;
340 bool show_source = !already_shown;
341 FrameSelectedCallback(frame_sp.get());
342 return frame_sp->GetStatus(output_stream, show_frame_info, show_source);
343 }
344 return false;
345 } else
346 return false;
347}
348
350 if (!frame)
351 return;
352
353 if (frame->HasDebugInformation() &&
354 (GetProcess()->GetWarningsOptimization() ||
355 GetProcess()->GetWarningsUnsupportedLanguage())) {
356 SymbolContext sc =
357 frame->GetSymbolContext(eSymbolContextFunction | eSymbolContextModule);
358 GetProcess()->PrintWarningOptimization(sc);
359 GetProcess()->PrintWarningUnsupportedLanguage(sc);
360 }
361}
362
365 return m_stop_info_sp;
366
367 ThreadPlanSP completed_plan_sp(GetCompletedPlan());
368 ProcessSP process_sp(GetProcess());
369 const uint32_t stop_id = process_sp ? process_sp->GetStopID() : UINT32_MAX;
370
371 // Here we select the stop info according to priorirty: - m_stop_info_sp (if
372 // not trace) - preset value - completed plan stop info - new value with plan
373 // from completed plan stack - m_stop_info_sp (trace stop reason is OK now) -
374 // ask GetPrivateStopInfo to set stop info
375
376 bool have_valid_stop_info = m_stop_info_sp &&
377 m_stop_info_sp ->IsValid() &&
378 m_stop_info_stop_id == stop_id;
379 bool have_valid_completed_plan = completed_plan_sp && completed_plan_sp->PlanSucceeded();
380 bool plan_failed = completed_plan_sp && !completed_plan_sp->PlanSucceeded();
381 bool plan_overrides_trace =
382 have_valid_stop_info && have_valid_completed_plan
383 && (m_stop_info_sp->GetStopReason() == eStopReasonTrace);
384
385 if (have_valid_stop_info && !plan_overrides_trace && !plan_failed) {
386 return m_stop_info_sp;
387 } else if (completed_plan_sp) {
389 completed_plan_sp, GetReturnValueObject(), GetExpressionVariable());
390 } else {
392 return m_stop_info_sp;
393 }
394}
395
400
402 if (!calculate)
403 return m_stop_info_sp;
404
406 return m_stop_info_sp;
407
408 ProcessSP process_sp(GetProcess());
409 if (process_sp) {
410 const uint32_t process_stop_id = process_sp->GetStopID();
411 if (m_stop_info_stop_id != process_stop_id) {
412 // We preserve the old stop info for a variety of reasons:
413 // 1) Someone has already updated it by the time we get here
414 // 2) We didn't get to execute the breakpoint instruction we stopped at
415 // 3) This is a virtual step so we didn't actually run
416 // 4) If this thread wasn't allowed to run the last time round.
417 if (m_stop_info_sp) {
418 if (m_stop_info_sp->IsValid() || IsStillAtLastBreakpointHit() ||
419 GetCurrentPlan()->IsVirtualStep()
422 else
423 m_stop_info_sp.reset();
424 }
425
426 if (!m_stop_info_sp) {
427 if (!CalculateStopInfo())
429 }
430 }
431
432 // The stop info can be manually set by calling Thread::SetStopInfo() prior
433 // to this function ever getting called, so we can't rely on
434 // "m_stop_info_stop_id != process_stop_id" as the condition for the if
435 // statement below, we must also check the stop info to see if we need to
436 // override it. See the header documentation in
437 // Architecture::OverrideStopInfo() for more information on the stop
438 // info override callback.
439 if (m_stop_info_override_stop_id != process_stop_id) {
440 m_stop_info_override_stop_id = process_stop_id;
441 if (m_stop_info_sp) {
442 if (const Architecture *arch =
443 process_sp->GetTarget().GetArchitecturePlugin())
444 arch->OverrideStopInfo(*this);
445 }
446 }
447 }
448
449 // If we were resuming the process and it was interrupted,
450 // return no stop reason. This thread would like to resume.
451 if (m_stop_info_sp && m_stop_info_sp->WasContinueInterrupted(*this))
452 return {};
453
454 return m_stop_info_sp;
455}
456
458 lldb::StopInfoSP stop_info_sp(GetStopInfo());
459 if (stop_info_sp)
460 return stop_info_sp->GetStopReason();
461 return eStopReasonNone;
462}
463
465 ProcessSP process_sp(GetProcess());
466 if (process_sp)
467 return m_stop_info_stop_id == process_sp->GetStopID();
468 else
469 return true; // Process is no longer around so stop info is always up to
470 // date...
471}
472
474 if (m_stop_info_sp) {
475 m_stop_info_sp.reset();
476 }
477}
478
479void Thread::SetStopInfo(const lldb::StopInfoSP &stop_info_sp) {
480 m_stop_info_sp = stop_info_sp;
481 if (m_stop_info_sp) {
482 m_stop_info_sp->MakeStopInfoValid();
483 // If we are overriding the ShouldReportStop, do that here:
485 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
487 }
488
489 ProcessSP process_sp(GetProcess());
490 if (process_sp)
491 m_stop_info_stop_id = process_sp->GetStopID();
492 else
494 Log *log = GetLog(LLDBLog::Thread);
495 LLDB_LOGF(log, "%p: tid = 0x%" PRIx64 ": stop info = %s (stop_id = %u)",
496 static_cast<void *>(this), GetID(),
497 stop_info_sp ? stop_info_sp->GetDescription() : "<NULL>",
499}
500
502 if (vote == eVoteNoOpinion)
503 return;
504 else {
506 if (m_stop_info_sp)
507 m_stop_info_sp->OverrideShouldNotify(m_override_should_notify ==
509 }
510}
511
513 // Note, we can't just NULL out the private reason, or the native thread
514 // implementation will try to go calculate it again. For now, just set it to
515 // a Unix Signal with an invalid signal number.
518}
519
521
523 saved_state.register_backup_sp.reset();
525 if (frame_sp) {
526 lldb::RegisterCheckpointSP reg_checkpoint_sp(
528 if (reg_checkpoint_sp) {
529 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
530 if (reg_ctx_sp && reg_ctx_sp->ReadAllRegisterValues(*reg_checkpoint_sp))
531 saved_state.register_backup_sp = reg_checkpoint_sp;
532 }
533 }
534 if (!saved_state.register_backup_sp)
535 return false;
536
537 saved_state.stop_info_sp = GetStopInfo();
538 ProcessSP process_sp(GetProcess());
539 if (process_sp)
540 saved_state.orig_stop_id = process_sp->GetStopID();
542 saved_state.m_completed_plan_checkpoint =
545
546 return true;
547}
548
550 ThreadStateCheckpoint &saved_state) {
551 if (saved_state.register_backup_sp) {
553 if (frame_sp) {
554 lldb::RegisterContextSP reg_ctx_sp(frame_sp->GetRegisterContext());
555 if (reg_ctx_sp) {
556 bool ret =
557 reg_ctx_sp->WriteAllRegisterValues(*saved_state.register_backup_sp);
558
559 // Clear out all stack frames as our world just changed.
561 reg_ctx_sp->InvalidateIfNeeded(true);
562 if (m_unwinder_up)
563 m_unwinder_up->Clear();
564 return ret;
565 }
566 }
567 }
568 return false;
569}
570
572 ThreadStateCheckpoint &saved_state) {
573 if (saved_state.stop_info_sp)
574 saved_state.stop_info_sp->MakeStopInfoValid();
575 SetStopInfo(saved_state.stop_info_sp);
576 GetStackFrameList()->SetCurrentInlinedDepth(
577 saved_state.current_inlined_depth);
579 saved_state.m_completed_plan_checkpoint);
581}
582
584 // If any other threads access this we will need a mutex for it
585 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
586 return m_state;
587}
588
590 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);
591 m_state = state;
592}
593
596
597 if (!frame_sp)
598 return GetStopDescriptionRaw();
599
600 auto recognized_frame_sp = frame_sp->GetRecognizedFrame();
601
602 if (!recognized_frame_sp)
603 return GetStopDescriptionRaw();
604
605 std::string recognized_stop_description =
606 recognized_frame_sp->GetStopDescription();
607
608 if (!recognized_stop_description.empty())
609 return recognized_stop_description;
610
611 return GetStopDescriptionRaw();
612}
613
615 StopInfoSP stop_info_sp = GetStopInfo();
616 std::string raw_stop_description;
617 if (stop_info_sp && stop_info_sp->IsValid()) {
618 raw_stop_description = stop_info_sp->GetDescription();
619 assert((!raw_stop_description.empty() ||
620 stop_info_sp->GetStopReason() == eStopReasonNone) &&
621 "StopInfo returned an empty description.");
622 }
623 return raw_stop_description;
624}
625
627 ThreadPlan *current_plan = GetCurrentPlan();
628
629 // FIXME: I may decide to disallow threads with no plans. In which
630 // case this should go to an assert.
631
632 if (!current_plan)
633 return;
634
635 current_plan->WillStop();
636}
637
640 // First check whether this thread is going to "actually" resume at all.
641 // For instance, if we're stepping from one level to the next of an
642 // virtual inlined call stack, we just change the inlined call stack index
643 // without actually running this thread. In that case, for this thread we
644 // shouldn't push a step over breakpoint plan or do that work.
645 if (GetCurrentPlan()->IsVirtualStep())
646 return false;
647
648 // If we're at a breakpoint push the step-over breakpoint plan. Do this
649 // before telling the current plan it will resume, since we might change
650 // what the current plan is.
651
653 ProcessSP process_sp(GetProcess());
654 if (reg_ctx_sp && process_sp && direction == eRunForward) {
655 const addr_t thread_pc = reg_ctx_sp->GetPC();
656 BreakpointSiteSP bp_site_sp =
657 process_sp->GetBreakpointSiteList().FindByAddress(thread_pc);
658 // If we're at a BreakpointSite which we have either
659 // 1. already triggered/hit, or
660 // 2. the Breakpoint was added while stopped, or the pc was moved
661 // to this BreakpointSite
662 // Step past the breakpoint before resuming.
663 // If we stopped at a breakpoint instruction/BreakpointSite location
664 // without hitting it, and we're still at that same address on
665 // resuming, then we want to hit the BreakpointSite when we resume.
666 if (bp_site_sp && m_stopped_at_unexecuted_bp != thread_pc) {
667 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the
668 // target may not require anything special to step over a breakpoint.
669
670 ThreadPlan *cur_plan = GetCurrentPlan();
671
672 bool push_step_over_bp_plan = false;
673 if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint) {
676 if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
677 push_step_over_bp_plan = true;
678 } else
679 push_step_over_bp_plan = true;
680
681 if (push_step_over_bp_plan) {
682 ThreadPlanSP step_bp_plan_sp(new ThreadPlanStepOverBreakpoint(*this));
683 if (step_bp_plan_sp) {
684 step_bp_plan_sp->SetPrivate(true);
685
686 if (GetCurrentPlan()->RunState() != eStateStepping) {
687 ThreadPlanStepOverBreakpoint *step_bp_plan =
688 static_cast<ThreadPlanStepOverBreakpoint *>(
689 step_bp_plan_sp.get());
690 step_bp_plan->SetAutoContinue(true);
691 }
692 QueueThreadPlan(step_bp_plan_sp, false);
693 return true;
694 }
695 }
696 }
697 }
698 }
699 return false;
700}
701
702bool Thread::ShouldResume(StateType resume_state) {
703 // At this point clear the completed plan stack.
706
707 StateType prev_resume_state = GetTemporaryResumeState();
708
709 SetTemporaryResumeState(resume_state);
710
711 lldb::ThreadSP backing_thread_sp(GetBackingThread());
712 if (backing_thread_sp)
713 backing_thread_sp->SetTemporaryResumeState(resume_state);
714
715 // Make sure m_stop_info_sp is valid. Don't do this for threads we suspended
716 // in the previous run.
717 if (prev_resume_state != eStateSuspended)
719
720 // This is a little dubious, but we are trying to limit how often we actually
721 // fetch stop info from the target, 'cause that slows down single stepping.
722 // So assume that if we got to the point where we're about to resume, and we
723 // haven't yet had to fetch the stop reason, then it doesn't need to know
724 // about the fact that we are resuming...
725 const uint32_t process_stop_id = GetProcess()->GetStopID();
726 if (m_stop_info_stop_id == process_stop_id &&
727 (m_stop_info_sp && m_stop_info_sp->IsValid())) {
728 if (StopInfoSP stop_info_sp = GetPrivateStopInfo())
729 stop_info_sp->WillResume(resume_state);
730 }
731
732 // Tell all the plans that we are about to resume in case they need to clear
733 // any state. We distinguish between the plan on the top of the stack and the
734 // lower plans in case a plan needs to do any special business before it
735 // runs.
736
737 bool need_to_resume = false;
738 ThreadPlan *plan_ptr = GetCurrentPlan();
739 if (plan_ptr) {
740 need_to_resume = plan_ptr->WillResume(resume_state, true);
741
742 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
743 plan_ptr->WillResume(resume_state, false);
744 }
745
746 // If the WillResume for the plan says we are faking a resume, then it will
747 // have set an appropriate stop info. In that case, don't reset it here.
748
749 if (need_to_resume && resume_state != eStateSuspended) {
750 m_stop_info_sp.reset();
751 }
752 }
753
754 if (need_to_resume) {
756
757 // Only reset m_stopped_at_unexecuted_bp if the thread is actually being
758 // resumed. Otherwise, the state of a suspended thread may not be restored
759 // correctly at the next stop. For example, this could happen if the thread
760 // is suspended by ThreadPlanStepOverBreakpoint in another thread, which
761 // temporarily disables the breakpoint that the suspended thread has reached
762 // but not yet executed.
763 if (resume_state != eStateSuspended)
765
766 // Let Thread subclasses do any special work they need to prior to resuming
767 WillResume(resume_state);
768 }
769
770 return need_to_resume;
771}
772
775 // This will get recomputed each time when we stop.
777}
778
780
781bool Thread::ShouldStop(Event *event_ptr) {
782 ThreadPlan *current_plan = GetCurrentPlan();
783
784 bool should_stop = true;
785
786 Log *log = GetLog(LLDBLog::Step);
787
789 LLDB_LOGF(log,
790 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
791 ", should_stop = 0 (ignore since thread was suspended)",
792 __FUNCTION__, GetID(), GetProtocolID());
793 return false;
794 }
795
797 LLDB_LOGF(log,
798 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
799 ", should_stop = 0 (ignore since thread was suspended)",
800 __FUNCTION__, GetID(), GetProtocolID());
801 return false;
802 }
803
804 // Based on the current thread plan and process stop info, check if this
805 // thread caused the process to stop. NOTE: this must take place before the
806 // plan is moved from the current plan stack to the completed plan stack.
808 LLDB_LOGF(log,
809 "Thread::%s for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
810 ", pc = 0x%16.16" PRIx64
811 ", should_stop = 0 (ignore since no stop reason)",
812 __FUNCTION__, GetID(), GetProtocolID(),
815 return false;
816 }
817
818 // Clear the "must run me before stop" if it was set:
820
821 if (log) {
822 LLDB_LOGF(log,
823 "Thread::%s(%p) for tid = 0x%4.4" PRIx64 " 0x%4.4" PRIx64
824 ", pc = 0x%16.16" PRIx64,
825 __FUNCTION__, static_cast<void *>(this), GetID(), GetProtocolID(),
828 LLDB_LOGF(log, "^^^^^^^^ Thread::ShouldStop Begin ^^^^^^^^");
829 StreamString s;
830 s.IndentMore();
831 GetProcess()->DumpThreadPlansForTID(
832 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
833 false /* condense_trivial */, true /* skip_unreported */);
834 LLDB_LOGF(log, "Plan stack initial state:\n%s", s.GetData());
835 }
836
837 // The top most plan always gets to do the trace log...
838 current_plan->DoTraceLog();
839
840 // First query the stop info's ShouldStopSynchronous. This handles
841 // "synchronous" stop reasons, for example the breakpoint command on internal
842 // breakpoints. If a synchronous stop reason says we should not stop, then
843 // we don't have to do any more work on this stop.
844 StopInfoSP private_stop_info(GetPrivateStopInfo());
845 if (private_stop_info &&
846 !private_stop_info->ShouldStopSynchronous(event_ptr)) {
847 LLDB_LOGF(log, "StopInfo::ShouldStop async callback says we should not "
848 "stop, returning ShouldStop of false.");
849 return false;
850 }
851
852 // If we've already been restarted, don't query the plans since the state
853 // they would examine is not current.
855 return false;
856
857 // Before the plans see the state of the world, calculate the current inlined
858 // depth.
859 GetStackFrameList()->CalculateCurrentInlinedDepth();
860
861 // If the base plan doesn't understand why we stopped, then we have to find a
862 // plan that does. If that plan is still working, then we don't need to do
863 // any more work. If the plan that explains the stop is done, then we should
864 // pop all the plans below it, and pop it, and then let the plans above it
865 // decide whether they still need to do more work.
866
867 bool done_processing_current_plan = false;
868 if (!current_plan->PlanExplainsStop(event_ptr)) {
869 if (current_plan->TracerExplainsStop()) {
870 done_processing_current_plan = true;
871 should_stop = false;
872 } else {
873 // Leaf plan that does not explain the stop should be popped.
874 // The plan should be push itself later again before resuming to stay
875 // as leaf.
876 if (current_plan->IsLeafPlan())
877 PopPlan();
878
879 // If the current plan doesn't explain the stop, then find one that does
880 // and let it handle the situation.
881 ThreadPlan *plan_ptr = current_plan;
882 while ((plan_ptr = GetPreviousPlan(plan_ptr)) != nullptr) {
883 if (plan_ptr->PlanExplainsStop(event_ptr)) {
884 LLDB_LOGF(log, "Plan %s explains stop.", plan_ptr->GetName());
885
886 should_stop = plan_ptr->ShouldStop(event_ptr);
887
888 // plan_ptr explains the stop, next check whether plan_ptr is done,
889 // if so, then we should take it and all the plans below it off the
890 // stack.
891
892 if (plan_ptr->MischiefManaged()) {
893 // We're going to pop the plans up to and including the plan that
894 // explains the stop.
895 ThreadPlan *prev_plan_ptr = GetPreviousPlan(plan_ptr);
896
897 do {
898 if (should_stop)
899 current_plan->WillStop();
900 PopPlan();
901 } while ((current_plan = GetCurrentPlan()) != prev_plan_ptr);
902 // Now, if the responsible plan was not "Okay to discard" then
903 // we're done, otherwise we forward this to the next plan in the
904 // stack below.
905 done_processing_current_plan =
906 (plan_ptr->IsControllingPlan() && !plan_ptr->OkayToDiscard());
907 } else {
908 bool should_force_run = plan_ptr->ShouldRunBeforePublicStop();
909 if (should_force_run) {
911 should_stop = false;
912 }
913 done_processing_current_plan = true;
914 }
915 break;
916 }
917 }
918 }
919 }
920
921 if (!done_processing_current_plan) {
922 bool override_stop = false;
923
924 // We're starting from the base plan, so just let it decide;
925 if (current_plan->IsBasePlan()) {
926 should_stop = current_plan->ShouldStop(event_ptr);
927 LLDB_LOGF(log, "Base plan says should stop: %i.", should_stop);
928 } else {
929 // Otherwise, don't let the base plan override what the other plans say
930 // to do, since presumably if there were other plans they would know what
931 // to do...
932 while (true) {
933 if (current_plan->IsBasePlan())
934 break;
935
936 should_stop = current_plan->ShouldStop(event_ptr);
937 LLDB_LOGF(log, "Plan %s should stop: %d.", current_plan->GetName(),
938 should_stop);
939 if (current_plan->MischiefManaged()) {
940 if (should_stop)
941 current_plan->WillStop();
942
943 if (current_plan->ShouldAutoContinue(event_ptr)) {
944 override_stop = true;
945 LLDB_LOGF(log, "Plan %s auto-continue: true.",
946 current_plan->GetName());
947 // The ShouldAutoContinue contract: subsequent plans are not asked.
948 PopPlan();
949 break;
950 }
951
952 // If a Controlling Plan wants to stop, we let it. Otherwise, see if
953 // the plan's parent wants to stop.
954
955 PopPlan();
956 if (should_stop && current_plan->IsControllingPlan() &&
957 !current_plan->OkayToDiscard()) {
958 break;
959 }
960
961 current_plan = GetCurrentPlan();
962 if (current_plan == nullptr) {
963 break;
964 }
965 } else {
966 break;
967 }
968 }
969 }
970
971 if (override_stop)
972 should_stop = false;
973 }
974
975 // One other potential problem is that we set up a controlling plan, then stop
976 // in before it is complete - for instance by hitting a breakpoint during a
977 // step-over - then do some step/finish/etc operations that wind up past the
978 // end point condition of the initial plan. We don't want to strand the
979 // original plan on the stack, This code clears stale plans off the stack.
980
981 if (should_stop) {
982 ThreadPlan *plan_ptr = GetCurrentPlan();
983
984 // Discard the stale plans and all plans below them in the stack, plus move
985 // the completed plans to the completed plan stack
986 while (!plan_ptr->IsBasePlan()) {
987 bool stale = plan_ptr->IsPlanStale();
988 ThreadPlan *examined_plan = plan_ptr;
989 plan_ptr = GetPreviousPlan(examined_plan);
990
991 if (stale) {
992 LLDB_LOGF(
993 log,
994 "Plan %s being discarded in cleanup, it says it is already done.",
995 examined_plan->GetName());
996 while (GetCurrentPlan() != examined_plan) {
997 DiscardPlan();
998 }
999 if (examined_plan->IsPlanComplete()) {
1000 // plan is complete but does not explain the stop (example: step to a
1001 // line with breakpoint), let us move the plan to
1002 // completed_plan_stack anyway
1003 PopPlan();
1004 } else
1005 DiscardPlan();
1006 }
1007 }
1008 }
1009
1010 if (log) {
1011 StreamString s;
1012 s.IndentMore();
1013 GetProcess()->DumpThreadPlansForTID(
1014 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
1015 false /* condense_trivial */, true /* skip_unreported */);
1016 LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
1017 LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
1018 should_stop);
1019 }
1020 return should_stop;
1021}
1022
1024 StateType thread_state = GetResumeState();
1025 StateType temp_thread_state = GetTemporaryResumeState();
1026
1027 Log *log = GetLog(LLDBLog::Step);
1028
1029 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1030 LLDB_LOGF(log,
1031 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1032 ": returning vote %i (state was suspended or invalid)",
1034 return eVoteNoOpinion;
1035 }
1036
1037 if (temp_thread_state == eStateSuspended ||
1038 temp_thread_state == eStateInvalid) {
1039 LLDB_LOGF(log,
1040 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1041 ": returning vote %i (temporary state was suspended or invalid)",
1043 return eVoteNoOpinion;
1044 }
1045
1046 if (!ThreadStoppedForAReason()) {
1047 LLDB_LOGF(log,
1048 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1049 ": returning vote %i (thread didn't stop for a reason.)",
1051 return eVoteNoOpinion;
1052 }
1053
1054 if (GetPlans().AnyCompletedPlans()) {
1055 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1056 // the last plan, regardless of whether it is private or not.
1057 LLDB_LOGF(log,
1058 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1059 ": returning vote for complete stack's back plan",
1060 GetID());
1061 return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);
1062 } else {
1063 Vote thread_vote = eVoteNoOpinion;
1064 ThreadPlan *plan_ptr = GetCurrentPlan();
1065 while (true) {
1066 if (plan_ptr->PlanExplainsStop(event_ptr)) {
1067 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1068 break;
1069 }
1070 if (plan_ptr->IsBasePlan())
1071 break;
1072 else
1073 plan_ptr = GetPreviousPlan(plan_ptr);
1074 }
1075 LLDB_LOGF(log,
1076 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1077 ": returning vote %i for current plan",
1078 GetID(), thread_vote);
1079
1080 return thread_vote;
1081 }
1082}
1083
1085 StateType thread_state = GetResumeState();
1086
1087 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1088 return eVoteNoOpinion;
1089 }
1090
1091 Log *log = GetLog(LLDBLog::Step);
1092 if (GetPlans().AnyCompletedPlans()) {
1093 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1094 // the last plan, regardless of whether it is private or not.
1095 ThreadPlanSP plan = GetPlans().GetCompletedPlan(/*skip_private=*/false);
1096
1097 LLDB_LOGF(log,
1098 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1099 ", %s): %s being asked whether we should report run.",
1100 GetIndexID(), static_cast<void *>(this), GetID(),
1101 StateAsCString(GetTemporaryResumeState()), plan->GetName());
1102
1103 return plan->ShouldReportRun(event_ptr);
1104 } else {
1105 LLDB_LOGF(log,
1106 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1107 ", %s): %s being asked whether we should report run.",
1108 GetIndexID(), static_cast<void *>(this), GetID(),
1110 GetCurrentPlan()->GetName());
1111
1112 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1113 }
1114}
1115
1117 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1118}
1119
1121 ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());
1122 if (plans)
1123 return *plans;
1124
1125 // History threads don't have a thread plan, but they do ask get asked to
1126 // describe themselves, which usually involves pulling out the stop reason.
1127 // That in turn will check for a completed plan on the ThreadPlanStack.
1128 // Instead of special-casing at that point, we return a Stack with a
1129 // ThreadPlanNull as its base plan. That will give the right answers to the
1130 // queries GetDescription makes, and only assert if you try to run the thread.
1132 m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true);
1133 return *m_null_plan_stack_up;
1134}
1135
1136void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {
1137 assert(thread_plan_sp && "Don't push an empty thread plan.");
1138
1139 Log *log = GetLog(LLDBLog::Step);
1140 if (log) {
1141 StreamString s;
1142 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1143 LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1144 static_cast<void *>(this), s.GetData(),
1145 thread_plan_sp->GetThread().GetID());
1146 }
1147
1148 GetPlans().PushPlan(std::move(thread_plan_sp));
1149}
1150
1152 Log *log = GetLog(LLDBLog::Step);
1153 ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();
1154 LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1155 popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());
1156}
1157
1159 Log *log = GetLog(LLDBLog::Step);
1160 ThreadPlanSP discarded_plan_sp = GetPlans().DiscardPlan();
1161
1162 LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1163 discarded_plan_sp->GetName(),
1164 discarded_plan_sp->GetThread().GetID());
1165}
1166
1168 const ThreadPlanStack &plans = GetPlans();
1169 if (!plans.AnyPlans())
1170 return;
1171
1172 // Iterate from the second plan (index: 1) to skip the base plan.
1173 ThreadPlanSP p;
1174 uint32_t i = 1;
1175 while ((p = plans.GetPlanByIndex(i, false))) {
1176 StreamString strm;
1177 p->GetDescription(&strm, eDescriptionLevelInitial);
1178 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1179 i++;
1180 }
1181}
1182
1184 return GetPlans().GetCurrentPlan().get();
1185}
1186
1188 for (ThreadPlan *plan = GetCurrentPlan(); plan;
1189 plan = GetPreviousPlan(plan)) {
1190 if (plan->GetKind() == ThreadPlan::eKindCallFunction)
1191 return true;
1192 }
1193 return false;
1194}
1195
1199
1203
1207
1209 return GetPlans().IsPlanDone(plan);
1210}
1211
1213 return GetPlans().WasPlanDiscarded(plan);
1214}
1215
1219
1221 return GetPlans().GetPreviousPlan(current_plan);
1222}
1223
1225 bool abort_other_plans) {
1226 Status status;
1227 StreamString s;
1228 if (!thread_plan_sp->ValidatePlan(&s)) {
1229 DiscardThreadPlansUpToPlan(thread_plan_sp);
1230 thread_plan_sp.reset();
1231 return Status(s.GetString().str());
1232 }
1233
1234 if (abort_other_plans)
1235 DiscardThreadPlans(true);
1236
1237 PushPlan(thread_plan_sp);
1238
1239 // This seems a little funny, but I don't want to have to split up the
1240 // constructor and the DidPush in the scripted plan, that seems annoying.
1241 // That means the constructor has to be in DidPush. So I have to validate the
1242 // plan AFTER pushing it, and then take it off again...
1243 if (!thread_plan_sp->ValidatePlan(&s)) {
1244 DiscardThreadPlansUpToPlan(thread_plan_sp);
1245 thread_plan_sp.reset();
1246 return Status(s.GetString().str());
1247 }
1248
1249 return status;
1250}
1251
1253 // Count the user thread plans from the back end to get the number of the one
1254 // we want to discard:
1255
1256 ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();
1257 if (up_to_plan_ptr == nullptr)
1258 return false;
1259
1260 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1261 return true;
1262}
1263
1265 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1266}
1267
1269 Log *log = GetLog(LLDBLog::Step);
1270 LLDB_LOGF(log,
1271 "Discarding thread plans for thread tid = 0x%4.4" PRIx64
1272 ", up to %p",
1273 GetID(), static_cast<void *>(up_to_plan_ptr));
1274 GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);
1275}
1276
1278 Log *log = GetLog(LLDBLog::Step);
1279 LLDB_LOGF(log,
1280 "Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1281 ", force %d)",
1282 GetID(), force);
1283
1284 if (force) {
1286 return;
1287 }
1289}
1290
1292 Status error;
1293 ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();
1294 if (!innermost_expr_plan) {
1296 "No expressions currently active on this thread");
1297 return error;
1298 }
1299 DiscardThreadPlansUpToPlan(innermost_expr_plan);
1300 return error;
1301}
1302
1303ThreadPlanSP Thread::QueueBasePlan(bool abort_other_plans) {
1304 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1305 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1306 return thread_plan_sp;
1307}
1308
1310 bool step_over, bool abort_other_plans, bool stop_other_threads,
1311 Status &status) {
1312 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1313 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1314 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1315 return thread_plan_sp;
1316}
1317
1319 bool abort_other_plans, const AddressRange &range,
1320 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1321 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1322 ThreadPlanSP thread_plan_sp;
1323 thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
1324 *this, range, addr_context, stop_other_threads,
1325 step_out_avoids_code_withoug_debug_info);
1326
1327 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1328 return thread_plan_sp;
1329}
1330
1331// Call the QueueThreadPlanForStepOverRange method which takes an address
1332// range.
1334 bool abort_other_plans, const LineEntry &line_entry,
1335 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1336 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1337 const bool include_inlined_functions = true;
1338 auto address_range =
1339 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
1341 abort_other_plans, address_range, addr_context, stop_other_threads,
1342 status, step_out_avoids_code_withoug_debug_info);
1343}
1344
1346 bool abort_other_plans, const AddressRange &range,
1347 const SymbolContext &addr_context, llvm::StringRef step_in_target,
1348 lldb::RunMode stop_other_threads, Status &status,
1349 LazyBool step_in_avoids_code_without_debug_info,
1350 LazyBool step_out_avoids_code_without_debug_info) {
1351 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange(
1352 *this, range, addr_context, step_in_target.str(), stop_other_threads,
1353 step_in_avoids_code_without_debug_info,
1354 step_out_avoids_code_without_debug_info));
1355 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1356 return thread_plan_sp;
1357}
1358
1359// Call the QueueThreadPlanForStepInRange method which takes an address range.
1361 bool abort_other_plans, const LineEntry &line_entry,
1362 const SymbolContext &addr_context, llvm::StringRef step_in_target,
1363 lldb::RunMode stop_other_threads, Status &status,
1364 LazyBool step_in_avoids_code_without_debug_info,
1365 LazyBool step_out_avoids_code_without_debug_info) {
1366 const bool include_inlined_functions = false;
1368 abort_other_plans,
1369 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
1370 addr_context, step_in_target, stop_other_threads, status,
1371 step_in_avoids_code_without_debug_info,
1372 step_out_avoids_code_without_debug_info);
1373}
1374
1376 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1377 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1378 uint32_t frame_idx, Status &status,
1379 LazyBool step_out_avoids_code_without_debug_info) {
1380 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1381 *this, addr_context, first_insn, stop_other_threads, report_stop_vote,
1382 report_run_vote, frame_idx, step_out_avoids_code_without_debug_info));
1383
1384 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1385 return thread_plan_sp;
1386}
1387
1389 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1390 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1391 uint32_t frame_idx, Status &status, bool continue_to_next_branch) {
1392 const bool calculate_return_value =
1393 false; // No need to calculate the return value here.
1394 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1395 *this, stop_other_threads, report_stop_vote, report_run_vote, frame_idx,
1396 continue_to_next_branch, calculate_return_value));
1397
1398 ThreadPlanStepOut *new_plan =
1399 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1400 new_plan->ClearShouldStopHereCallbacks();
1401
1402 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1403 return thread_plan_sp;
1404}
1405
1407 bool abort_other_plans,
1408 bool stop_other_threads,
1409 Status &status) {
1410 ThreadPlanSP thread_plan_sp(
1411 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1412 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1413 return ThreadPlanSP();
1414
1415 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1416 return thread_plan_sp;
1417}
1418
1420 Address &target_addr,
1421 bool stop_other_threads,
1422 Status &status) {
1423 ThreadPlanSP thread_plan_sp(
1424 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1425
1426 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1427 return thread_plan_sp;
1428}
1429
1431 bool abort_other_plans, llvm::ArrayRef<addr_t> address_list,
1432 bool stop_other_threads, uint32_t frame_idx, Status &status) {
1433 ThreadPlanSP thread_plan_sp = std::make_shared<ThreadPlanStepUntil>(
1434 *this, address_list, stop_other_threads, frame_idx);
1435
1436 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1437 return thread_plan_sp;
1438}
1439
1441 bool abort_other_plans, const ScriptedMetadata &scripted_metadata,
1442 bool stop_other_threads, Status &status) {
1443
1444 ThreadPlanSP thread_plan_sp(new ScriptedThreadPlan(*this, scripted_metadata));
1445 thread_plan_sp->SetStopOthers(stop_other_threads);
1446 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1447 return thread_plan_sp;
1448}
1449
1450uint32_t Thread::GetIndexID() const { return m_index_id; }
1451
1453 TargetSP target_sp;
1454 ProcessSP process_sp(GetProcess());
1455 if (process_sp)
1456 target_sp = process_sp->CalculateTarget();
1457 return target_sp;
1458}
1459
1461
1462ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1463
1465
1467 exe_ctx.SetContext(shared_from_this());
1468}
1469
1471 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1473 auto &stack = m_active_frame_providers_by_thread[current];
1475 "Thread::PushProviderFrameList: tid = {0:x}, depth = {1} -> {2}",
1476 GetID(), stack.size(), stack.size() + 1);
1477 stack.push_back(std::move(frames));
1478}
1479
1481 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1483 auto it = m_active_frame_providers_by_thread.find(current);
1484 size_t pre_pop_depth =
1485 (it != m_active_frame_providers_by_thread.end()) ? it->second.size() : 0;
1487 "Thread::PopProviderFrameList: tid = {0:x}, depth = {1} -> {2}",
1488 GetID(), pre_pop_depth, pre_pop_depth ? pre_pop_depth - 1 : 0);
1489 assert(it != m_active_frame_providers_by_thread.end() && !it->second.empty());
1490 if (it == m_active_frame_providers_by_thread.end() || it->second.empty())
1491 return;
1492 it->second.pop_back();
1493 if (it->second.empty())
1495}
1496
1498 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1499 return !m_active_frame_providers_by_thread.empty();
1500}
1501
1503 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1504
1505 // Determine if we must return the parent frames instead of the
1506 // provider-augmented frames on this call.
1507 //
1508 // Frame providers are a public illusion layered on top of the private
1509 // reality (the unwinder stack, or a scripted process playing that
1510 // role). The private state thread (PST) manages the stop of that private
1511 // reality, so the correct view for its logic IS the private reality
1512 // -- the public illusion is only applied once the process has settled
1513 // and clients query the stopped state.
1514 //
1515 // When RunThreadPlan spawns an override PST, the original PST changes
1516 // role: it becomes the public event listener for the override, but it is
1517 // still working to manage the private side of the process. So it also should
1518 // see the private reality and not the public illusion. Feeding it the public
1519 // illusion instead of the private reality is incorrect and can lead to
1520 // deadlocks as a side effect, since provider code may try to acquire locks
1521 // already held further up the call stack.
1522 //
1523 // We return parent frames in two situations:
1524 //
1525 // 1. Re-entrancy: a provider is already active on some host thread.
1526 // - Same thread: the provider's get_frame_at_index() calls
1527 // HandleCommand("bt") or accesses input_frames, which re-enters
1528 // GetStackFrameList() -> infinite recursion.
1529 // - Private state thread: the provider called EvaluateExpression()
1530 // which resumed the process via RunThreadPlan; the private state
1531 // thread must process the resulting stop event, but if it tries to
1532 // build the synthetic frame list it will re-enter the provider ->
1533 // deadlock. Detected via the policy capability below rather than
1534 // thread identity, since m_current_private_state_thread_sp may
1535 // already have been reassigned to an override PST by the time this
1536 // runs.
1537 // - Any other thread: would run the provider concurrently with the
1538 // thread that is already mid-construction.
1539 //
1540 // 2. The current policy disallows loading frame providers (expression
1541 // evaluation on a PST), which requires the private reality.
1542 //
1543 // For case 1, if a provider is active we return its input (parent)
1544 // frames. For case (2), we return/create the unwinder frame list
1545 // without caching it in m_curr_frames_sp so that non-private-state
1546 // callers still get the public illusion once the process settles.
1547 ProcessSP process_sp = GetProcess();
1548 Policy policy = PolicyStack::Get().Current();
1549 {
1550 std::lock_guard<std::mutex> pguard(m_provider_frames_mutex);
1552 // Case 1a: current host thread is inside a provider call.
1554 auto it = m_active_frame_providers_by_thread.find(current);
1555 if (it != m_active_frame_providers_by_thread.end() && !it->second.empty())
1556 return it->second.back();
1557
1558 // Case 1b: private state thread while a provider is active elsewhere.
1560 return m_active_frame_providers_by_thread.begin()->second.back();
1561 }
1562 }
1563
1564 if (m_curr_frames_sp)
1565 return m_curr_frames_sp;
1566
1567 // The private state thread must see the raw unwinder frames, not the
1568 // provider-augmented public view, while it is servicing expression
1569 // evaluation. PushPrivateState(RunningExpression) is pushed by
1570 // RunThreadPlan and by RunPrivateStateThread for override PSTs.
1573 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1574 *this, m_prev_frames_sp, true, /*provider_id=*/0);
1575 return m_unwinder_frames_sp;
1576 }
1577
1578 // First, try to load frame providers if we don't have any yet.
1579 if (m_frame_providers.empty()) {
1580 if (process_sp) {
1581 Target &target = process_sp->GetTarget();
1582 const auto &descriptors = target.GetScriptedFrameProviderDescriptors();
1583
1584 // Collect all descriptors that apply to this thread.
1585 std::vector<const ScriptedFrameProviderDescriptor *> thread_descriptors;
1586 for (const auto &entry : descriptors) {
1587 const ScriptedFrameProviderDescriptor &descriptor = entry.second;
1588 if (descriptor.IsValid() && descriptor.AppliesToThread(*this))
1589 thread_descriptors.push_back(&descriptor);
1590 }
1591
1592 // Stable sort by priority so equal-priority providers keep
1593 // their registration (insertion) order.
1594 llvm::stable_sort(
1595 thread_descriptors, [](const ScriptedFrameProviderDescriptor *a,
1597 // nullopt (no priority) sorts last (UINT32_MAX).
1598 uint32_t priority_a = a->GetPriority().value_or(UINT32_MAX);
1599 uint32_t priority_b = b->GetPriority().value_or(UINT32_MAX);
1600 return priority_a < priority_b;
1601 });
1602
1603 // Load ALL matching providers in priority order.
1604 for (const auto *descriptor : thread_descriptors) {
1605 if (llvm::Error error = LoadScriptedFrameProvider(*descriptor)) {
1607 "Failed to load scripted frame provider: {0}");
1608 continue; // Try next provider if this one fails.
1609 }
1610 }
1611 }
1612 }
1613
1614 // Create the frame list based on whether we have providers.
1615 if (!m_provider_chain_ids.empty()) {
1616 // We have providers - use the last one in the chain.
1617 // The last provider has already been chained with all previous providers.
1618 auto [last_desc, last_id] = m_provider_chain_ids.back();
1619 auto it = m_frame_providers.find(last_id);
1620 if (it != m_frame_providers.end()) {
1621 SyntheticFrameProviderSP last_provider = it->second;
1622 StackFrameListSP input_frames = last_provider->GetInputFrames();
1623 m_curr_frames_sp = std::make_shared<SyntheticStackFrameList>(
1624 *this, input_frames, m_prev_frames_sp, true, last_provider, last_id);
1625 } else {
1627 "Missing frame provider (id = {0}) in Thread #{1:x}", last_id,
1628 GetID());
1629 }
1630 }
1631
1632 if (!m_curr_frames_sp) {
1633 // No provider - use normal unwinder frames with stable ID = 0.
1634 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1635 *this, m_prev_frames_sp, true, /*provider_id=*/0);
1637 } else {
1638 // Register this frame list by its identifier for later lookup.
1639 m_frame_lists_by_id.insert(
1640 {m_curr_frames_sp->GetIdentifier(), m_curr_frames_sp});
1641 }
1642
1643 return m_curr_frames_sp;
1644}
1645
1648 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1649
1650 // ID 0 is reserved for the unwinder frame list. Always return the unwinder
1651 // frame list for ID 0.
1652 if (id == 0) {
1653 return m_unwinder_frames_sp;
1654 }
1655
1656 auto it = m_frame_lists_by_id.find(id);
1657 if (it != m_frame_lists_by_id.end()) {
1658 auto sp = it->second.lock();
1660 "GetFrameListByIdentifier({0}): found={1}, locked={2}", id, true,
1661 sp != nullptr);
1662 return sp;
1663 }
1664 LLDB_LOG(GetLog(LLDBLog::Thread), "GetFrameListByIdentifier({0}): found={1}",
1665 id, false);
1666 return nullptr;
1667}
1668
1670 const ScriptedFrameProviderDescriptor &descriptor) {
1671 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1672
1673 StackFrameListSP input_frames;
1674 if (m_frame_providers.empty()) {
1675 // First provider gets real unwinder frames with stable ID = 0.
1677 std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true,
1678 /*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();
1750}
1751
1752std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1753 return m_prev_framezero_pc;
1754}
1755
1757 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1758
1759 // If any host thread is inside a frame provider call (e.g. the provider
1760 // called EvaluateExpression which resumes the process), don't tear down the
1761 // frame state. The synthetic frame list is still being constructed and the
1762 // thread will stop right back where it was after the expression finishes.
1763 // This must be a global check (not per-host-thread) because the frame state
1764 // is shared and clearing it would destroy in-progress provider work.
1765 if (IsAnyProviderActive())
1766 return;
1767
1768 GetUnwinder().Clear();
1769 m_prev_framezero_pc.reset();
1770 if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1771 m_prev_framezero_pc = reg_ctx_sp->GetPC();
1772
1773 // Only store away the old "reference" StackFrameList if we got all its
1774 // frames:
1775 // FIXME: At some point we can try to splice in the frames we have fetched
1776 // into the new frame as we make it, but let's not try that now.
1777 if (m_curr_frames_sp && m_curr_frames_sp->WereAllFramesFetched())
1779 m_curr_frames_sp.reset();
1780 m_unwinder_frames_sp.reset();
1781
1782 // Clear the provider instances and reset the ID counter, but keep the
1783 // chain configuration (m_provider_chain_ids) so providers are re-loaded
1784 // with consistent IDs on the next GetStackFrameList() call.
1785 m_frame_providers.clear();
1786 m_frame_lists_by_id.clear();
1787 m_extended_info.reset();
1789}
1790
1792 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1793}
1794
1796 lldb::ValueObjectSP return_value_sp,
1797 bool broadcast) {
1798 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1799 Status return_error;
1800
1801 if (!frame_sp) {
1802 return_error = Status::FromErrorStringWithFormat(
1803 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1804 frame_idx, GetID());
1805 }
1806
1807 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1808}
1809
1811 lldb::ValueObjectSP return_value_sp,
1812 bool broadcast) {
1813 Status return_error;
1814
1815 if (!frame_sp) {
1816 return_error = Status::FromErrorString("Can't return to a null frame.");
1817 return return_error;
1818 }
1819
1820 Thread *thread = frame_sp->GetThread().get();
1821 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1822 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1823 if (!older_frame_sp) {
1824 return_error = Status::FromErrorString("No older frame to return to.");
1825 return return_error;
1826 }
1827
1828 if (return_value_sp) {
1829 lldb::ABISP abi = thread->GetProcess()->GetABI();
1830 if (!abi) {
1831 return_error =
1832 Status::FromErrorString("Could not find ABI to set return value.");
1833 return return_error;
1834 }
1835 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1836
1837 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1838 // for scalars.
1839 // Turn that back on when that works.
1840 if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1841 Type *function_type = sc.function->GetType();
1842 if (function_type) {
1843 CompilerType return_type =
1845 if (return_type) {
1846 StreamString s;
1847 return_type.DumpTypeDescription(&s);
1848 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1849 if (cast_value_sp) {
1850 cast_value_sp->SetFormat(eFormatHex);
1851 return_value_sp = cast_value_sp;
1852 }
1853 }
1854 }
1855 }
1856
1857 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1858 if (!return_error.Success())
1859 return return_error;
1860 }
1861
1862 // Now write the return registers for the chosen frame: Note, we can't use
1863 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1864 // their data
1865
1866 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1867 if (youngest_frame_sp) {
1868 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1869 if (reg_ctx_sp) {
1870 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1871 older_frame_sp->GetRegisterContext());
1872 if (copy_success) {
1873 thread->DiscardThreadPlans(true);
1874 thread->ClearStackFrames();
1876 auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());
1878 }
1879 } else {
1880 return_error =
1881 Status::FromErrorString("Could not reset register values.");
1882 }
1883 } else {
1884 return_error = Status::FromErrorString("Frame has no register context.");
1885 }
1886 } else {
1887 return_error = Status::FromErrorString("Returned past top frame.");
1888 }
1889 return return_error;
1890}
1891
1892static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1893 ExecutionContextScope *exe_scope) {
1894 for (size_t n = 0; n < list.size(); n++) {
1895 s << "\t";
1896 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1898 s << "\n";
1899 }
1900}
1901
1902Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1903 bool can_leave_function, std::string *warnings) {
1905 Target *target = exe_ctx.GetTargetPtr();
1906 TargetSP target_sp = exe_ctx.GetTargetSP();
1907 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1908 StackFrame *frame = exe_ctx.GetFramePtr();
1909 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1910
1911 // Find candidate locations.
1912 std::vector<Address> candidates, within_function, outside_function;
1913 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1914 within_function, outside_function);
1915
1916 // If possible, we try and stay within the current function. Within a
1917 // function, we accept multiple locations (optimized code may do this,
1918 // there's no solution here so we do the best we can). However if we're
1919 // trying to leave the function, we don't know how to pick the right
1920 // location, so if there's more than one then we bail.
1921 if (!within_function.empty())
1922 candidates = within_function;
1923 else if (outside_function.size() == 1 && can_leave_function)
1924 candidates = outside_function;
1925
1926 // Check if we got anything.
1927 if (candidates.empty()) {
1928 if (outside_function.empty()) {
1930 "Cannot locate an address for {0}:{1}.", file.GetFilename(), line);
1931 } else if (outside_function.size() == 1) {
1933 "{0}:{1} is outside the current function.", file.GetFilename(), line);
1934 } else {
1935 StreamString sstr;
1936 DumpAddressList(sstr, outside_function, target);
1938 "{0}:{1} has multiple candidate locations:\n{2}", file.GetFilename(),
1939 line, sstr.GetData());
1940 }
1941 }
1942
1943 // Accept the first location, warn about any others.
1944 Address dest = candidates[0];
1945 if (warnings && candidates.size() > 1) {
1946 StreamString sstr;
1947 sstr.Format(
1948 "{0}:{1} appears multiple times in this function, selecting the "
1949 "first location:\n",
1950 file.GetFilename(), line);
1951 DumpAddressList(sstr, candidates, target);
1952 *warnings = std::string(sstr.GetString().trim('\n'));
1953 }
1954
1955 if (!reg_ctx->SetPC(dest))
1956 return Status::FromErrorString("Cannot change PC to target address.");
1957
1958 return Status();
1959}
1960
1961bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,
1962 const FormatEntity::Entry *format) {
1963 ExecutionContext exe_ctx(shared_from_this());
1964 Process *process = exe_ctx.GetProcessPtr();
1965 if (!process || !format)
1966 return false;
1967
1968 StackFrameSP frame_sp;
1969 SymbolContext frame_sc;
1970 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1971 frame_sp = GetStackFrameAtIndex(frame_idx);
1972 if (frame_sp) {
1973 exe_ctx.SetFrameSP(frame_sp);
1974 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1975 }
1976 }
1977
1978 return FormatEntity::Formatter(frame_sp ? &frame_sc : nullptr, &exe_ctx,
1979 nullptr, false, false)
1980 .Format(*format, strm);
1981}
1982
1983void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1984 bool stop_format) {
1985 ExecutionContext exe_ctx(shared_from_this());
1986
1987 const FormatEntity::Entry *thread_format;
1988 FormatEntity::Entry format_entry;
1989 if (stop_format) {
1990 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1991 thread_format = &format_entry;
1992 } else {
1993 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1994 thread_format = &format_entry;
1995 }
1996
1997 assert(thread_format);
1998
1999 DumpUsingFormat(strm, frame_idx, thread_format);
2000}
2001
2003
2005
2007 if (m_reg_context_sp)
2008 return m_reg_context_sp->GetThreadPointer();
2009 return LLDB_INVALID_ADDRESS;
2010}
2011
2013 lldb::addr_t tls_file_addr) {
2014 // The default implementation is to ask the dynamic loader for it. This can
2015 // be overridden for specific platforms.
2016 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2017 if (loader)
2018 return loader->GetThreadLocalData(module, shared_from_this(),
2019 tls_file_addr);
2020 else
2021 return LLDB_INVALID_ADDRESS;
2022}
2023
2025 Process *process = GetProcess().get();
2026 if (process) {
2027 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2028 if (loader && loader->IsFullyInitialized() == false)
2029 return false;
2030
2031 SystemRuntime *runtime = process->GetSystemRuntime();
2032 if (runtime) {
2033 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
2034 }
2035 }
2036 return true;
2037}
2038
2041 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
2042}
2043
2045 switch (reason) {
2046 case eStopReasonInvalid:
2047 return "invalid";
2048 case eStopReasonNone:
2049 return "none";
2050 case eStopReasonTrace:
2051 return "trace";
2053 return "breakpoint";
2055 return "watchpoint";
2056 case eStopReasonSignal:
2057 return "signal";
2059 return "exception";
2060 case eStopReasonExec:
2061 return "exec";
2062 case eStopReasonFork:
2063 return "fork";
2064 case eStopReasonVFork:
2065 return "vfork";
2067 return "vfork done";
2069 return "plan complete";
2071 return "thread exiting";
2073 return "instrumentation break";
2075 return "processor trace";
2077 return "async interrupt";
2079 return "history boundary";
2080 }
2081
2082 return "StopReason = " + std::to_string(reason);
2083}
2084
2086 switch (mode) {
2087 case eOnlyThisThread:
2088 return "only this thread";
2089 case eAllThreads:
2090 return "all threads";
2092 return "only during stepping";
2093 }
2094
2095 return "RunMode = " + std::to_string(mode);
2096}
2097
2098size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
2099 uint32_t num_frames, uint32_t num_frames_with_source,
2100 bool stop_format, bool show_hidden, bool only_stacks) {
2101
2102 ExecutionContext exe_ctx(shared_from_this());
2103 Target *target = exe_ctx.GetTargetPtr();
2104 if (!only_stacks) {
2105 Process *process = exe_ctx.GetProcessPtr();
2106 strm.Indent();
2107 bool is_selected = false;
2108 if (process) {
2109 if (process->GetThreadList().GetSelectedThread().get() == this)
2110 is_selected = true;
2111 }
2112 strm.Printf("%c ", is_selected ? '*' : ' ');
2113 if (target && target->GetDebugger().GetUseExternalEditor()) {
2114 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2115 if (frame_sp) {
2116 SymbolContext frame_sc(
2117 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
2118 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {
2119 if (llvm::Error e = Host::OpenFileInExternalEditor(
2120 target->GetDebugger().GetExternalEditor(),
2121 frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {
2122 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
2123 "OpenFileInExternalEditor failed: {0}");
2124 }
2125 }
2126 }
2127 }
2128
2129 DumpUsingSettingsFormat(strm, start_frame, stop_format);
2130 }
2131
2132 size_t num_frames_shown = 0;
2133 if (num_frames > 0) {
2134 strm.IndentMore();
2135
2136 const bool show_frame_info = true;
2137 const bool show_frame_unique = only_stacks;
2138 bool show_selected_frame = false;
2139 if (num_frames == 1 || only_stacks ||
2140 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2141 strm.IndentMore();
2142 else
2143 show_selected_frame = true;
2144
2145 bool show_hidden_marker =
2146 target && target->GetDebugger().GetMarkHiddenFrames();
2147 num_frames_shown = GetStackFrameList()->GetStatus(
2148 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
2149 show_frame_unique, show_hidden, show_hidden_marker,
2150 show_selected_frame);
2151 if (num_frames == 1)
2152 strm.IndentLess();
2153 strm.IndentLess();
2154 }
2155 return num_frames_shown;
2156}
2157
2159 bool print_json_thread, bool print_json_stopinfo) {
2160 const bool stop_format = false;
2161 DumpUsingSettingsFormat(strm, 0, stop_format);
2162 strm.PutCString("\n");
2163
2165
2166 if (print_json_thread || print_json_stopinfo) {
2167 if (thread_info && print_json_thread) {
2168 thread_info->Dump(strm);
2169 strm.PutCString("\n");
2170 }
2171
2172 if (print_json_stopinfo && m_stop_info_sp) {
2173 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2174 if (stop_info) {
2175 stop_info->Dump(strm);
2176 strm.PutCString("\n");
2177 }
2178 }
2179
2180 return true;
2181 }
2182
2183 if (thread_info) {
2184 StructuredData::ObjectSP activity =
2185 thread_info->GetObjectForDotSeparatedPath("activity");
2186 StructuredData::ObjectSP breadcrumb =
2187 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2188 StructuredData::ObjectSP messages =
2189 thread_info->GetObjectForDotSeparatedPath("trace_messages");
2190
2191 bool printed_activity = false;
2192 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
2193 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2194 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2195 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2196 if (name && name->GetType() == eStructuredDataTypeString && id &&
2197 id->GetType() == eStructuredDataTypeInteger) {
2198 strm.Format(" Activity '{0}', {1:x}\n",
2199 name->GetAsString()->GetValue(),
2200 id->GetUnsignedIntegerValue());
2201 }
2202 printed_activity = true;
2203 }
2204 bool printed_breadcrumb = false;
2205 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2206 if (printed_activity)
2207 strm.PutCString("\n");
2208 StructuredData::Dictionary *breadcrumb_dict =
2209 breadcrumb->GetAsDictionary();
2210 StructuredData::ObjectSP breadcrumb_text =
2211 breadcrumb_dict->GetValueForKey("name");
2212 if (breadcrumb_text &&
2213 breadcrumb_text->GetType() == eStructuredDataTypeString) {
2214 strm.Format(" Current Breadcrumb: {0}\n",
2215 breadcrumb_text->GetAsString()->GetValue());
2216 }
2217 printed_breadcrumb = true;
2218 }
2219 if (messages && messages->GetType() == eStructuredDataTypeArray) {
2220 if (printed_breadcrumb)
2221 strm.PutCString("\n");
2222 StructuredData::Array *messages_array = messages->GetAsArray();
2223 const size_t msg_count = messages_array->GetSize();
2224 if (msg_count > 0) {
2225 strm.Printf(" %zu trace messages:\n", msg_count);
2226 for (size_t i = 0; i < msg_count; i++) {
2227 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2228 if (message && message->GetType() == eStructuredDataTypeDictionary) {
2229 StructuredData::Dictionary *message_dict =
2230 message->GetAsDictionary();
2231 StructuredData::ObjectSP message_text =
2232 message_dict->GetValueForKey("message");
2233 if (message_text &&
2234 message_text->GetType() == eStructuredDataTypeString) {
2235 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
2236 }
2237 }
2238 }
2239 }
2240 }
2241 }
2242
2243 return true;
2244}
2245
2246size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2247 uint32_t num_frames, bool show_frame_info,
2248 uint32_t num_frames_with_source,
2249 bool show_hidden) {
2250 ExecutionContext exe_ctx(shared_from_this());
2251 Target *target = exe_ctx.GetTargetPtr();
2252 bool show_hidden_marker =
2253 target && target->GetDebugger().GetMarkHiddenFrames();
2254 return GetStackFrameList()->GetStatus(
2255 strm, first_frame, num_frames, show_frame_info, num_frames_with_source,
2256 /*show_unique*/ false, show_hidden, show_hidden_marker);
2257}
2258
2260 if (!m_unwinder_up)
2261 m_unwinder_up = std::make_unique<UnwindLLDB>(*this);
2262 return *m_unwinder_up;
2263}
2264
2270
2272 // If we are currently stopped at a breakpoint, always return that stopinfo
2273 // and don't reset it. This allows threads to maintain their breakpoint
2274 // stopinfo, such as when thread-stepping in multithreaded programs.
2275 if (m_stop_info_sp) {
2276 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2277 if (stop_reason == lldb::eStopReasonBreakpoint) {
2278 uint64_t value = m_stop_info_sp->GetValue();
2280 if (reg_ctx_sp) {
2281 lldb::addr_t pc = reg_ctx_sp->GetPC();
2282 BreakpointSiteSP bp_site_sp =
2283 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2284 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2285 return true;
2286 }
2287 }
2288 }
2289 return false;
2290}
2291
2292Status Thread::StepIn(bool source_step,
2293 LazyBool step_in_avoids_code_without_debug_info,
2294 LazyBool step_out_avoids_code_without_debug_info)
2295
2296{
2297 Status error;
2298 Process *process = GetProcess().get();
2299 if (StateIsStoppedState(process->GetState(), true)) {
2300 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2301 ThreadPlanSP new_plan_sp;
2302 const lldb::RunMode run_mode = eOnlyThisThread;
2303 const bool abort_other_plans = false;
2304
2305 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2306 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2307 new_plan_sp = QueueThreadPlanForStepInRange(
2308 abort_other_plans, sc.line_entry, sc, llvm::StringRef(), run_mode,
2309 error, step_in_avoids_code_without_debug_info,
2310 step_out_avoids_code_without_debug_info);
2311 } else {
2313 false, abort_other_plans, run_mode, error);
2314 }
2315
2316 new_plan_sp->SetIsControllingPlan(true);
2317 new_plan_sp->SetOkayToDiscard(false);
2318
2319 // Why do we need to set the current thread by ID here???
2321 error = process->Resume();
2322 } else {
2323 error = Status::FromErrorString("process not stopped");
2324 }
2325 return error;
2326}
2327
2328Status Thread::StepOver(bool source_step,
2329 LazyBool step_out_avoids_code_without_debug_info) {
2330 Status error;
2331 Process *process = GetProcess().get();
2332 if (StateIsStoppedState(process->GetState(), true)) {
2333 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2334 ThreadPlanSP new_plan_sp;
2335
2336 const lldb::RunMode run_mode = eOnlyThisThread;
2337 const bool abort_other_plans = false;
2338
2339 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2340 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2341 new_plan_sp = QueueThreadPlanForStepOverRange(
2342 abort_other_plans, sc.line_entry, sc, run_mode, error,
2343 step_out_avoids_code_without_debug_info);
2344 } else {
2346 true, abort_other_plans, run_mode, error);
2347 }
2348
2349 new_plan_sp->SetIsControllingPlan(true);
2350 new_plan_sp->SetOkayToDiscard(false);
2351
2352 // Why do we need to set the current thread by ID here???
2354 error = process->Resume();
2355 } else {
2356 error = Status::FromErrorString("process not stopped");
2357 }
2358 return error;
2359}
2360
2361Status Thread::StepOut(uint32_t frame_idx) {
2362 Status error;
2363 Process *process = GetProcess().get();
2364 if (StateIsStoppedState(process->GetState(), true)) {
2365 const bool first_instruction = false;
2366 const bool stop_other_threads = false;
2367 const bool abort_other_plans = false;
2368
2370 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2371 eVoteYes, eVoteNoOpinion, frame_idx, error));
2372
2373 new_plan_sp->SetIsControllingPlan(true);
2374 new_plan_sp->SetOkayToDiscard(false);
2375
2376 // Why do we need to set the current thread by ID here???
2378 error = process->Resume();
2379 } else {
2380 error = Status::FromErrorString("process not stopped");
2381 }
2382 return error;
2383}
2384
2386 if (auto frame_sp = GetStackFrameAtIndex(0))
2387 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2388 if (auto e = recognized_frame->GetExceptionObject())
2389 return e;
2390
2391 // NOTE: Even though this behavior is generalized, only ObjC is actually
2392 // supported at the moment.
2393 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2394 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2395 return e;
2396 }
2397
2398 return ValueObjectSP();
2399}
2400
2402 ValueObjectSP exception = GetCurrentException();
2403 if (!exception)
2404 return ThreadSP();
2405
2406 // NOTE: Even though this behavior is generalized, only ObjC is actually
2407 // supported at the moment.
2408 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2409 if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2410 return bt;
2411 }
2412
2413 return ThreadSP();
2414}
2415
2417 ProcessSP process_sp = GetProcess();
2418 assert(process_sp);
2419 Target &target = process_sp->GetTarget();
2420 PlatformSP platform_sp = target.GetPlatform();
2421 assert(platform_sp);
2422 ArchSpec arch = target.GetArchitecture();
2423
2424 CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());
2425 if (!type.IsValid())
2427 &target, Status::FromErrorString("no siginfo_t for the platform"));
2428
2429 auto type_size_or_err = type.GetByteSize(nullptr);
2430 if (!type_size_or_err)
2432 &target, Status::FromError(type_size_or_err.takeError()));
2433
2434 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
2435 GetSiginfo(*type_size_or_err);
2436 if (!data)
2437 return ValueObjectConstResult::Create(&target,
2438 Status::FromError(data.takeError()));
2439
2440 DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),
2441 process_sp->GetByteOrder(), arch.GetAddressByteSize()};
2442 return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);
2443}
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:1892
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:891
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:545
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:100
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:4786
A plug-in interface definition class for debugging a process.
Definition Process.h:368
ThreadList & GetThreadList()
Definition Process.h:2367
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1374
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3145
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1315
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:3966
Debugger & GetDebugger() const
Definition Target.h:1356
lldb::PlatformSP GetPlatform()
Definition Target.h:1998
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1273
const ArchSpec & GetArchitecture() const
Definition Target.h:1315
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:1375
bool IsThreadPlanDone(ThreadPlan *plan) const
Checks whether the given plan is in the completed plans for this stop.
Definition Thread.cpp:1208
virtual lldb::user_id_t GetProtocolID() const
Definition Thread.h:1169
lldb::ThreadSP GetCurrentExceptionBacktrace()
Definition Thread.cpp:2401
std::optional< lldb::addr_t > GetPreviousFrameZeroPC()
Request the pc value the thread had when previously stopped.
Definition Thread.cpp:1752
void BroadcastSelectedFrameChange(StackID &new_frame_id)
Definition Thread.cpp:278
@ 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:1291
~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:1216
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:2024
void RestoreThreadStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:571
Status QueueThreadPlan(lldb::ThreadPlanSP &plan_sp, bool abort_other_plans)
Queues a generic thread plan.
Definition Thread.cpp:1224
bool WasThreadPlanDiscarded(ThreadPlan *plan) const
Checks whether the given plan is in the discarded plans for this stop.
Definition Thread.cpp:1212
virtual lldb::RegisterContextSP GetRegisterContext()=0
virtual lldb::addr_t GetThreadPointer()
Retrieves the per-thread data area.
Definition Thread.cpp:2006
virtual void DidStop()
Definition Thread.cpp:779
virtual bool RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:549
friend class ThreadPlan
Definition Thread.h:1367
bool SetupToStepOverBreakpointIfNeeded(lldb::RunDirection direction)
Definition Thread.cpp:638
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:1167
std::recursive_mutex m_frame_mutex
Multithreaded protection for m_state.
Definition Thread.h:1442
static void SettingsInitialize()
Definition Thread.cpp:2002
void SetShouldReportStop(Vote vote)
Definition Thread.cpp:501
virtual lldb::StopInfoSP GetPrivateStopInfo(bool calculate=true)
Definition Thread.cpp:401
uint32_t GetIndexID() const
Definition Thread.cpp:1450
std::optional< lldb::addr_t > m_prev_framezero_pc
Frame 0's PC the last time this thread was stopped.
Definition Thread.h:1465
Status ReturnFromFrame(lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1810
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Thread.cpp:1466
void DiscardThreadPlans(bool force)
Discards the plans queued on the plan stack of the current thread.
Definition Thread.cpp:1277
void SetStopInfo(const lldb::StopInfoSP &stop_info_sp)
Definition Thread.cpp:479
bool GetDescription(Stream &s, lldb::DescriptionLevel level, bool print_json_thread, bool print_json_stopinfo)
Definition Thread.cpp:2158
static std::string RunModeAsString(lldb::RunMode mode)
Definition Thread.cpp:2085
void PushProviderFrameList(lldb::StackFrameListSP frames)
Push/pop provider input frames for the current host thread.
Definition Thread.cpp:1470
void SetTemporaryResumeState(lldb::StateType new_state)
Definition Thread.h:1407
virtual bool MatchesSpec(const ThreadSpec *spec)
Definition Thread.cpp:1116
lldb::ProcessSP CalculateProcess() override
Definition Thread.cpp:1460
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:2012
void SetStopInfoToNothing()
Definition Thread.cpp:512
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:1419
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:1406
lldb::StackFrameSP GetSelectedFrame(SelectMostRelevant select_most_relevant)
Definition Thread.cpp:287
virtual bool IsStillAtLastBreakpointHit()
Definition Thread.cpp:2271
std::recursive_mutex m_state_mutex
Multithreaded protection for m_state.
Definition Thread.h:1440
void PopProviderFrameList()
Definition Thread.cpp:1480
ThreadPlan * GetPreviousPlan(ThreadPlan *plan) const
Definition Thread.cpp:1220
virtual const char * GetName()
Definition Thread.h:290
void PushPlan(lldb::ThreadPlanSP plan_sp)
Definition Thread.cpp:1136
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:1756
ThreadPlan * GetCurrentPlan() const
Gets the plan which will execute next on the plan stack.
Definition Thread.cpp:1183
virtual Unwind & GetUnwinder()
Definition Thread.cpp:2259
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:1497
lldb::ValueObjectSP GetReturnValueObject() const
Gets the outer-most return value from the completed plans.
Definition Thread.cpp:1200
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:1187
lldb::ExpressionVariableSP GetExpressionVariable() const
Gets the outer-most expression variable from the completed plans.
Definition Thread.cpp:1204
Vote ShouldReportRun(Event *event_ptr)
Definition Thread.cpp:1084
lldb::TargetSP CalculateTarget() override
Definition Thread.cpp:1452
static std::string StopReasonAsString(lldb::StopReason reason)
Definition Thread.cpp:2044
lldb::StackFrameListSP GetFrameListByIdentifier(lldb::frame_list_id_t id)
Get a frame list by its unique identifier.
Definition Thread.cpp:1647
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:520
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:2246
std::string GetStopDescriptionRaw()
Definition Thread.cpp:614
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:1252
virtual Status StepOver(bool source_step, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Default implementation for stepping over.
Definition Thread.cpp:2328
bool ShouldResume(lldb::StateType resume_state)
Definition Thread.cpp:702
std::unique_ptr< lldb_private::Unwind > m_unwinder_up
It gets set in Thread::ShouldResume.
Definition Thread.h:1477
std::unique_ptr< ThreadPlanStack > m_null_plan_stack_up
Definition Thread.h:1481
lldb::StateType GetTemporaryResumeState() const
Definition Thread.h:1269
virtual bool CheckpointThreadState(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:522
void SetState(lldb::StateType state)
Definition Thread.cpp:589
llvm::Error LoadScriptedFrameProvider(const ScriptedFrameProviderDescriptor &descriptor)
Definition Thread.cpp:1669
lldb::ProcessSP GetProcess() const
Definition Thread.h:162
lldb::StackFrameSP CalculateStackFrame() override
Definition Thread.cpp:1464
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:295
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:1430
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
void DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, bool stop_format)
Definition Thread.cpp:1983
LazyBool m_override_should_notify
Definition Thread.h:1480
lldb::ThreadSP CalculateThread() override
Definition Thread.cpp:1462
Status ReturnFromFrameWithIndex(uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1795
virtual Status StepOut(uint32_t frame_idx=0)
Default implementation for stepping out.
Definition Thread.cpp:2361
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:583
lldb::StateType m_state
The state of our process.
Definition Thread.h:1438
bool m_extended_info_fetched
Definition Thread.h:1501
void CalculatePublicStopInfo()
Definition Thread.cpp:396
static void SettingsTerminate()
Definition Thread.cpp:2004
bool SetSelectedFrameByIndex(uint32_t frame_idx, bool broadcast=false)
Definition Thread.cpp:304
lldb::StopReason GetStopReason()
Definition Thread.cpp:457
ThreadPlanStack & GetPlans() const
Definition Thread.cpp:1120
lldb::ValueObjectSP GetSiginfoValue()
Definition Thread.cpp:2416
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:1309
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:1467
virtual void DidResume()
Definition Thread.cpp:773
bool StopInfoIsUpToDate() const
Definition Thread.cpp:464
lldb::StackFrameSP GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr)
Definition Thread.cpp:2040
llvm::DenseMap< lldb::frame_list_id_t, lldb::SyntheticFrameProviderSP > m_frame_providers
Map from frame list ID to its frame provider.
Definition Thread.h:1489
lldb::ThreadPlanSP GetCompletedPlan() const
Gets the outer-most plan that was popped off the plan stack in the most recent stop.
Definition Thread.cpp:1196
lldb::ValueObjectSP GetCurrentException()
Definition Thread.cpp:2385
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:1388
virtual lldb::StackFrameSP GetFrameWithConcreteFrameIndex(uint32_t unwind_idx)
Definition Thread.cpp:1791
bool ShouldStop(Event *event_ptr)
Definition Thread.cpp:781
Status JumpToLine(const FileSpec &file, uint32_t line, bool can_leave_function, std::string *warnings=nullptr)
Definition Thread.cpp:1902
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:1961
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:1264
void FrameSelectedCallback(lldb_private::StackFrame *frame)
Definition Thread.cpp:349
lldb::ThreadPlanSP QueueBasePlan(bool abort_other_plans)
Queues the base plan for a thread.
Definition Thread.cpp:1303
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:1318
std::string GetStopDescription()
Definition Thread.cpp:594
virtual lldb::ThreadPlanSP QueueThreadPlanForStepScripted(bool abort_other_plans, const ScriptedMetadata &scripted_metadata, bool stop_other_threads, Status &status)
Definition Thread.cpp:1440
StructuredData::ObjectSP m_extended_info
Definition Thread.h:1503
lldb::StopInfoSP GetStopInfo()
Definition Thread.cpp:363
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:1345
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:1498
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:1472
lldb::StackFrameListSP GetStackFrameList()
Definition Thread.cpp:1502
bool m_should_run_before_public_stop
Definition Thread.h:1428
Vote ShouldReportStop(Event *event_ptr)
Definition Thread.cpp:1023
bool SetSelectedFrameByIndexNoisily(uint32_t frame_idx, Stream &output_stream)
Definition Thread.cpp:316
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:1494
lldb::StateType m_resume_state
This state is used to force a thread to be suspended from outside the ThreadPlan logic.
Definition Thread.h:1469
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:2292
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:2098
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