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/Policy.h"
28#include "lldb/Target/Process.h"
34#include "lldb/Target/Target.h"
50#include "lldb/Utility/Log.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 }
948
949 // If a Controlling Plan wants to stop, we let it. Otherwise, see if
950 // the plan's parent wants to stop.
951
952 PopPlan();
953 if (should_stop && current_plan->IsControllingPlan() &&
954 !current_plan->OkayToDiscard()) {
955 break;
956 }
957
958 current_plan = GetCurrentPlan();
959 if (current_plan == nullptr) {
960 break;
961 }
962 } else {
963 break;
964 }
965 }
966 }
967
968 if (override_stop)
969 should_stop = false;
970 }
971
972 // One other potential problem is that we set up a controlling plan, then stop
973 // in before it is complete - for instance by hitting a breakpoint during a
974 // step-over - then do some step/finish/etc operations that wind up past the
975 // end point condition of the initial plan. We don't want to strand the
976 // original plan on the stack, This code clears stale plans off the stack.
977
978 if (should_stop) {
979 ThreadPlan *plan_ptr = GetCurrentPlan();
980
981 // Discard the stale plans and all plans below them in the stack, plus move
982 // the completed plans to the completed plan stack
983 while (!plan_ptr->IsBasePlan()) {
984 bool stale = plan_ptr->IsPlanStale();
985 ThreadPlan *examined_plan = plan_ptr;
986 plan_ptr = GetPreviousPlan(examined_plan);
987
988 if (stale) {
989 LLDB_LOGF(
990 log,
991 "Plan %s being discarded in cleanup, it says it is already done.",
992 examined_plan->GetName());
993 while (GetCurrentPlan() != examined_plan) {
994 DiscardPlan();
995 }
996 if (examined_plan->IsPlanComplete()) {
997 // plan is complete but does not explain the stop (example: step to a
998 // line with breakpoint), let us move the plan to
999 // completed_plan_stack anyway
1000 PopPlan();
1001 } else
1002 DiscardPlan();
1003 }
1004 }
1005 }
1006
1007 if (log) {
1008 StreamString s;
1009 s.IndentMore();
1010 GetProcess()->DumpThreadPlansForTID(
1011 s, GetID(), eDescriptionLevelVerbose, true /* internal */,
1012 false /* condense_trivial */, true /* skip_unreported */);
1013 LLDB_LOGF(log, "Plan stack final state:\n%s", s.GetData());
1014 LLDB_LOGF(log, "vvvvvvvv Thread::ShouldStop End (returning %i) vvvvvvvv",
1015 should_stop);
1016 }
1017 return should_stop;
1018}
1019
1021 StateType thread_state = GetResumeState();
1022 StateType temp_thread_state = GetTemporaryResumeState();
1023
1024 Log *log = GetLog(LLDBLog::Step);
1025
1026 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1027 LLDB_LOGF(log,
1028 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1029 ": returning vote %i (state was suspended or invalid)",
1031 return eVoteNoOpinion;
1032 }
1033
1034 if (temp_thread_state == eStateSuspended ||
1035 temp_thread_state == eStateInvalid) {
1036 LLDB_LOGF(log,
1037 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1038 ": returning vote %i (temporary state was suspended or invalid)",
1040 return eVoteNoOpinion;
1041 }
1042
1043 if (!ThreadStoppedForAReason()) {
1044 LLDB_LOGF(log,
1045 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1046 ": returning vote %i (thread didn't stop for a reason.)",
1048 return eVoteNoOpinion;
1049 }
1050
1051 if (GetPlans().AnyCompletedPlans()) {
1052 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1053 // the last plan, regardless of whether it is private or not.
1054 LLDB_LOGF(log,
1055 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1056 ": returning vote for complete stack's back plan",
1057 GetID());
1058 return GetPlans().GetCompletedPlan(false)->ShouldReportStop(event_ptr);
1059 } else {
1060 Vote thread_vote = eVoteNoOpinion;
1061 ThreadPlan *plan_ptr = GetCurrentPlan();
1062 while (true) {
1063 if (plan_ptr->PlanExplainsStop(event_ptr)) {
1064 thread_vote = plan_ptr->ShouldReportStop(event_ptr);
1065 break;
1066 }
1067 if (plan_ptr->IsBasePlan())
1068 break;
1069 else
1070 plan_ptr = GetPreviousPlan(plan_ptr);
1071 }
1072 LLDB_LOGF(log,
1073 "Thread::ShouldReportStop() tid = 0x%4.4" PRIx64
1074 ": returning vote %i for current plan",
1075 GetID(), thread_vote);
1076
1077 return thread_vote;
1078 }
1079}
1080
1082 StateType thread_state = GetResumeState();
1083
1084 if (thread_state == eStateSuspended || thread_state == eStateInvalid) {
1085 return eVoteNoOpinion;
1086 }
1087
1088 Log *log = GetLog(LLDBLog::Step);
1089 if (GetPlans().AnyCompletedPlans()) {
1090 // Pass skip_private = false to GetCompletedPlan, since we want to ask
1091 // the last plan, regardless of whether it is private or not.
1092 ThreadPlanSP plan = GetPlans().GetCompletedPlan(/*skip_private=*/false);
1093
1094 LLDB_LOGF(log,
1095 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1096 ", %s): %s being asked whether we should report run.",
1097 GetIndexID(), static_cast<void *>(this), GetID(),
1098 StateAsCString(GetTemporaryResumeState()), plan->GetName());
1099
1100 return plan->ShouldReportRun(event_ptr);
1101 } else {
1102 LLDB_LOGF(log,
1103 "Current Plan for thread %d(%p) (0x%4.4" PRIx64
1104 ", %s): %s being asked whether we should report run.",
1105 GetIndexID(), static_cast<void *>(this), GetID(),
1107 GetCurrentPlan()->GetName());
1108
1109 return GetCurrentPlan()->ShouldReportRun(event_ptr);
1110 }
1111}
1112
1114 return (spec == nullptr) ? true : spec->ThreadPassesBasicTests(*this);
1115}
1116
1118 ThreadPlanStack *plans = GetProcess()->FindThreadPlans(GetID());
1119 if (plans)
1120 return *plans;
1121
1122 // History threads don't have a thread plan, but they do ask get asked to
1123 // describe themselves, which usually involves pulling out the stop reason.
1124 // That in turn will check for a completed plan on the ThreadPlanStack.
1125 // Instead of special-casing at that point, we return a Stack with a
1126 // ThreadPlanNull as its base plan. That will give the right answers to the
1127 // queries GetDescription makes, and only assert if you try to run the thread.
1129 m_null_plan_stack_up = std::make_unique<ThreadPlanStack>(*this, true);
1130 return *m_null_plan_stack_up;
1131}
1132
1133void Thread::PushPlan(ThreadPlanSP thread_plan_sp) {
1134 assert(thread_plan_sp && "Don't push an empty thread plan.");
1135
1136 Log *log = GetLog(LLDBLog::Step);
1137 if (log) {
1138 StreamString s;
1139 thread_plan_sp->GetDescription(&s, lldb::eDescriptionLevelFull);
1140 LLDB_LOGF(log, "Thread::PushPlan(0x%p): \"%s\", tid = 0x%4.4" PRIx64 ".",
1141 static_cast<void *>(this), s.GetData(),
1142 thread_plan_sp->GetThread().GetID());
1143 }
1144
1145 GetPlans().PushPlan(std::move(thread_plan_sp));
1146}
1147
1149 Log *log = GetLog(LLDBLog::Step);
1150 ThreadPlanSP popped_plan_sp = GetPlans().PopPlan();
1151 LLDB_LOGF(log, "Popping plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1152 popped_plan_sp->GetName(), popped_plan_sp->GetThread().GetID());
1153}
1154
1156 Log *log = GetLog(LLDBLog::Step);
1157 ThreadPlanSP discarded_plan_sp = GetPlans().DiscardPlan();
1158
1159 LLDB_LOGF(log, "Discarding plan: \"%s\", tid = 0x%4.4" PRIx64 ".",
1160 discarded_plan_sp->GetName(),
1161 discarded_plan_sp->GetThread().GetID());
1162}
1163
1165 const ThreadPlanStack &plans = GetPlans();
1166 if (!plans.AnyPlans())
1167 return;
1168
1169 // Iterate from the second plan (index: 1) to skip the base plan.
1170 ThreadPlanSP p;
1171 uint32_t i = 1;
1172 while ((p = plans.GetPlanByIndex(i, false))) {
1173 StreamString strm;
1174 p->GetDescription(&strm, eDescriptionLevelInitial);
1175 request.TryCompleteCurrentArg(std::to_string(i), strm.GetString());
1176 i++;
1177 }
1178}
1179
1181 return GetPlans().GetCurrentPlan().get();
1182}
1183
1185 for (ThreadPlan *plan = GetCurrentPlan(); plan;
1186 plan = GetPreviousPlan(plan)) {
1187 if (plan->GetKind() == ThreadPlan::eKindCallFunction)
1188 return true;
1189 }
1190 return false;
1191}
1192
1196
1200
1204
1206 return GetPlans().IsPlanDone(plan);
1207}
1208
1210 return GetPlans().WasPlanDiscarded(plan);
1211}
1212
1216
1218 return GetPlans().GetPreviousPlan(current_plan);
1219}
1220
1222 bool abort_other_plans) {
1223 Status status;
1224 StreamString s;
1225 if (!thread_plan_sp->ValidatePlan(&s)) {
1226 DiscardThreadPlansUpToPlan(thread_plan_sp);
1227 thread_plan_sp.reset();
1228 return Status(s.GetString().str());
1229 }
1230
1231 if (abort_other_plans)
1232 DiscardThreadPlans(true);
1233
1234 PushPlan(thread_plan_sp);
1235
1236 // This seems a little funny, but I don't want to have to split up the
1237 // constructor and the DidPush in the scripted plan, that seems annoying.
1238 // That means the constructor has to be in DidPush. So I have to validate the
1239 // plan AFTER pushing it, and then take it off again...
1240 if (!thread_plan_sp->ValidatePlan(&s)) {
1241 DiscardThreadPlansUpToPlan(thread_plan_sp);
1242 thread_plan_sp.reset();
1243 return Status(s.GetString().str());
1244 }
1245
1246 return status;
1247}
1248
1250 // Count the user thread plans from the back end to get the number of the one
1251 // we want to discard:
1252
1253 ThreadPlan *up_to_plan_ptr = GetPlans().GetPlanByIndex(plan_index).get();
1254 if (up_to_plan_ptr == nullptr)
1255 return false;
1256
1257 DiscardThreadPlansUpToPlan(up_to_plan_ptr);
1258 return true;
1259}
1260
1262 DiscardThreadPlansUpToPlan(up_to_plan_sp.get());
1263}
1264
1266 Log *log = GetLog(LLDBLog::Step);
1267 LLDB_LOGF(log,
1268 "Discarding thread plans for thread tid = 0x%4.4" PRIx64
1269 ", up to %p",
1270 GetID(), static_cast<void *>(up_to_plan_ptr));
1271 GetPlans().DiscardPlansUpToPlan(up_to_plan_ptr);
1272}
1273
1275 Log *log = GetLog(LLDBLog::Step);
1276 LLDB_LOGF(log,
1277 "Discarding thread plans for thread (tid = 0x%4.4" PRIx64
1278 ", force %d)",
1279 GetID(), force);
1280
1281 if (force) {
1283 return;
1284 }
1286}
1287
1289 Status error;
1290 ThreadPlan *innermost_expr_plan = GetPlans().GetInnermostExpression();
1291 if (!innermost_expr_plan) {
1293 "No expressions currently active on this thread");
1294 return error;
1295 }
1296 DiscardThreadPlansUpToPlan(innermost_expr_plan);
1297 return error;
1298}
1299
1300ThreadPlanSP Thread::QueueBasePlan(bool abort_other_plans) {
1301 ThreadPlanSP thread_plan_sp(new ThreadPlanBase(*this));
1302 QueueThreadPlan(thread_plan_sp, abort_other_plans);
1303 return thread_plan_sp;
1304}
1305
1307 bool step_over, bool abort_other_plans, bool stop_other_threads,
1308 Status &status) {
1309 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInstruction(
1310 *this, step_over, stop_other_threads, eVoteNoOpinion, eVoteNoOpinion));
1311 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1312 return thread_plan_sp;
1313}
1314
1316 bool abort_other_plans, const AddressRange &range,
1317 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1318 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1319 ThreadPlanSP thread_plan_sp;
1320 thread_plan_sp = std::make_shared<ThreadPlanStepOverRange>(
1321 *this, range, addr_context, stop_other_threads,
1322 step_out_avoids_code_withoug_debug_info);
1323
1324 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1325 return thread_plan_sp;
1326}
1327
1328// Call the QueueThreadPlanForStepOverRange method which takes an address
1329// range.
1331 bool abort_other_plans, const LineEntry &line_entry,
1332 const SymbolContext &addr_context, lldb::RunMode stop_other_threads,
1333 Status &status, LazyBool step_out_avoids_code_withoug_debug_info) {
1334 const bool include_inlined_functions = true;
1335 auto address_range =
1336 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions);
1338 abort_other_plans, address_range, addr_context, stop_other_threads,
1339 status, step_out_avoids_code_withoug_debug_info);
1340}
1341
1343 bool abort_other_plans, const AddressRange &range,
1344 const SymbolContext &addr_context, const char *step_in_target,
1345 lldb::RunMode stop_other_threads, Status &status,
1346 LazyBool step_in_avoids_code_without_debug_info,
1347 LazyBool step_out_avoids_code_without_debug_info) {
1348 ThreadPlanSP thread_plan_sp(new ThreadPlanStepInRange(
1349 *this, range, addr_context, step_in_target, stop_other_threads,
1350 step_in_avoids_code_without_debug_info,
1351 step_out_avoids_code_without_debug_info));
1352 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1353 return thread_plan_sp;
1354}
1355
1356// Call the QueueThreadPlanForStepInRange method which takes an address range.
1358 bool abort_other_plans, const LineEntry &line_entry,
1359 const SymbolContext &addr_context, const char *step_in_target,
1360 lldb::RunMode stop_other_threads, Status &status,
1361 LazyBool step_in_avoids_code_without_debug_info,
1362 LazyBool step_out_avoids_code_without_debug_info) {
1363 const bool include_inlined_functions = false;
1365 abort_other_plans,
1366 line_entry.GetSameLineContiguousAddressRange(include_inlined_functions),
1367 addr_context, step_in_target, stop_other_threads, status,
1368 step_in_avoids_code_without_debug_info,
1369 step_out_avoids_code_without_debug_info);
1370}
1371
1373 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1374 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1375 uint32_t frame_idx, Status &status,
1376 LazyBool step_out_avoids_code_without_debug_info) {
1377 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1378 *this, addr_context, first_insn, stop_other_threads, report_stop_vote,
1379 report_run_vote, frame_idx, step_out_avoids_code_without_debug_info));
1380
1381 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1382 return thread_plan_sp;
1383}
1384
1386 bool abort_other_plans, SymbolContext *addr_context, bool first_insn,
1387 bool stop_other_threads, Vote report_stop_vote, Vote report_run_vote,
1388 uint32_t frame_idx, Status &status, bool continue_to_next_branch) {
1389 const bool calculate_return_value =
1390 false; // No need to calculate the return value here.
1391 ThreadPlanSP thread_plan_sp(new ThreadPlanStepOut(
1392 *this, stop_other_threads, report_stop_vote, report_run_vote, frame_idx,
1393 continue_to_next_branch, calculate_return_value));
1394
1395 ThreadPlanStepOut *new_plan =
1396 static_cast<ThreadPlanStepOut *>(thread_plan_sp.get());
1397 new_plan->ClearShouldStopHereCallbacks();
1398
1399 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1400 return thread_plan_sp;
1401}
1402
1404 bool abort_other_plans,
1405 bool stop_other_threads,
1406 Status &status) {
1407 ThreadPlanSP thread_plan_sp(
1408 new ThreadPlanStepThrough(*this, return_stack_id, stop_other_threads));
1409 if (!thread_plan_sp || !thread_plan_sp->ValidatePlan(nullptr))
1410 return ThreadPlanSP();
1411
1412 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1413 return thread_plan_sp;
1414}
1415
1417 Address &target_addr,
1418 bool stop_other_threads,
1419 Status &status) {
1420 ThreadPlanSP thread_plan_sp(
1421 new ThreadPlanRunToAddress(*this, target_addr, stop_other_threads));
1422
1423 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1424 return thread_plan_sp;
1425}
1426
1428 bool abort_other_plans, llvm::ArrayRef<addr_t> address_list,
1429 bool stop_other_threads, uint32_t frame_idx, Status &status) {
1430 ThreadPlanSP thread_plan_sp = std::make_shared<ThreadPlanStepUntil>(
1431 *this, address_list, stop_other_threads, frame_idx);
1432
1433 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1434 return thread_plan_sp;
1435}
1436
1438 bool abort_other_plans, const char *class_name,
1439 StructuredData::ObjectSP extra_args_sp, bool stop_other_threads,
1440 Status &status) {
1441
1442 ThreadPlanSP thread_plan_sp(new ScriptedThreadPlan(
1443 *this, class_name, StructuredDataImpl(extra_args_sp)));
1444 thread_plan_sp->SetStopOthers(stop_other_threads);
1445 status = QueueThreadPlan(thread_plan_sp, abort_other_plans);
1446 return thread_plan_sp;
1447}
1448
1449uint32_t Thread::GetIndexID() const { return m_index_id; }
1450
1452 TargetSP target_sp;
1453 ProcessSP process_sp(GetProcess());
1454 if (process_sp)
1455 target_sp = process_sp->CalculateTarget();
1456 return target_sp;
1457}
1458
1460
1461ThreadSP Thread::CalculateThread() { return shared_from_this(); }
1462
1464
1466 exe_ctx.SetContext(shared_from_this());
1467}
1468
1470 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1472 auto &stack = m_active_frame_providers_by_thread[current];
1474 "Thread::PushProviderFrameList: tid = 0x{0:x}, depth = {1} -> {2}",
1475 GetID(), stack.size(), stack.size() + 1);
1476 stack.push_back(std::move(frames));
1477}
1478
1480 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1482 auto it = m_active_frame_providers_by_thread.find(current);
1483 size_t pre_pop_depth =
1484 (it != m_active_frame_providers_by_thread.end()) ? it->second.size() : 0;
1486 "Thread::PopProviderFrameList: tid = 0x{0:x}, depth = {1} -> {2}",
1487 GetID(), pre_pop_depth, pre_pop_depth ? pre_pop_depth - 1 : 0);
1488 assert(it != m_active_frame_providers_by_thread.end() && !it->second.empty());
1489 if (it == m_active_frame_providers_by_thread.end() || it->second.empty())
1490 return;
1491 it->second.pop_back();
1492 if (it->second.empty())
1494}
1495
1497 std::lock_guard<std::mutex> guard(m_provider_frames_mutex);
1498 return !m_active_frame_providers_by_thread.empty();
1499}
1500
1502 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1503
1504 // Determine if we must return the parent frames instead of the
1505 // provider-augmented frames on this call.
1506 //
1507 // Frame providers are a public illusion layered on top of the private
1508 // reality (the unwinder stack, or a scripted process playing that
1509 // role). The private state thread (PST) manages the stop of that private
1510 // reality, so the correct view for its logic IS the private reality
1511 // -- the public illusion is only applied once the process has settled
1512 // and clients query the stopped state.
1513 //
1514 // When RunThreadPlan spawns an override PST, the original PST changes
1515 // role: it becomes the public event listener for the override, but it is
1516 // still working to manage the private side of the process. So it also should
1517 // see the private reality and not the public illusion. Feeding it the public
1518 // illusion instead of the private reality is incorrect and can lead to
1519 // deadlocks as a side effect, since provider code may try to acquire locks
1520 // already held further up the call stack.
1521 //
1522 // We return parent frames in two situations:
1523 //
1524 // 1. Re-entrancy: a provider is already active on some host thread.
1525 // - Same thread: the provider's get_frame_at_index() calls
1526 // HandleCommand("bt") or accesses input_frames, which re-enters
1527 // GetStackFrameList() -> infinite recursion.
1528 // - Private state thread: the provider called EvaluateExpression()
1529 // which resumed the process via RunThreadPlan; the private state
1530 // thread must process the resulting stop event, but if it tries to
1531 // build the synthetic frame list it will re-enter the provider ->
1532 // deadlock.
1533 // - Any other thread: would run the provider concurrently with the
1534 // thread that is already mid-construction.
1535 //
1536 // 2. Current thread is a private state thread that should see the
1537 // private reality (Policy::View::Private).
1538 //
1539 // For case 1, if a provider is active we return its input (parent)
1540 // frames. For case (2), we return/create the unwinder frame list
1541 // without caching it in m_curr_frames_sp so that non-private-state
1542 // callers still get the public illusion once the process settles.
1543 ProcessSP process_sp = GetProcess();
1544 {
1545 std::lock_guard<std::mutex> pguard(m_provider_frames_mutex);
1547 // Case 1a: current host thread is inside a provider call.
1549 auto it = m_active_frame_providers_by_thread.find(current);
1550 if (it != m_active_frame_providers_by_thread.end() && !it->second.empty())
1551 return it->second.back();
1552
1553 // Case 1b: private state thread while a provider is active elsewhere.
1554 if (process_sp && process_sp->CurrentThreadIsPrivateStateThread())
1555 return m_active_frame_providers_by_thread.begin()->second.back();
1556 }
1557 }
1558
1559 if (m_curr_frames_sp)
1560 return m_curr_frames_sp;
1561
1562 // The private state thread must see the raw unwinder frames, not the
1563 // provider-augmented public view. Policy::PrivateState is pushed by
1564 // RunThreadPlan and RunPrivateStateThread.
1565 Policy policy = PolicyStack::Get().Current();
1566 if (policy.view == Policy::View::Private) {
1568 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1569 *this, m_prev_frames_sp, true, /*provider_id=*/0);
1570 return m_unwinder_frames_sp;
1571 }
1572
1573 // First, try to load frame providers if we don't have any yet.
1574 if (m_frame_providers.empty()) {
1575 if (process_sp) {
1576 Target &target = process_sp->GetTarget();
1577 const auto &descriptors = target.GetScriptedFrameProviderDescriptors();
1578
1579 // Collect all descriptors that apply to this thread.
1580 std::vector<const ScriptedFrameProviderDescriptor *> thread_descriptors;
1581 for (const auto &entry : descriptors) {
1582 const ScriptedFrameProviderDescriptor &descriptor = entry.second;
1583 if (descriptor.IsValid() && descriptor.AppliesToThread(*this))
1584 thread_descriptors.push_back(&descriptor);
1585 }
1586
1587 // Stable sort by priority so equal-priority providers keep
1588 // their registration (insertion) order.
1589 llvm::stable_sort(
1590 thread_descriptors, [](const ScriptedFrameProviderDescriptor *a,
1592 // nullopt (no priority) sorts last (UINT32_MAX).
1593 uint32_t priority_a = a->GetPriority().value_or(UINT32_MAX);
1594 uint32_t priority_b = b->GetPriority().value_or(UINT32_MAX);
1595 return priority_a < priority_b;
1596 });
1597
1598 // Load ALL matching providers in priority order.
1599 for (const auto *descriptor : thread_descriptors) {
1600 if (llvm::Error error = LoadScriptedFrameProvider(*descriptor)) {
1602 "Failed to load scripted frame provider: {0}");
1603 continue; // Try next provider if this one fails.
1604 }
1605 }
1606 }
1607 }
1608
1609 // Create the frame list based on whether we have providers.
1610 if (!m_provider_chain_ids.empty()) {
1611 // We have providers - use the last one in the chain.
1612 // The last provider has already been chained with all previous providers.
1613 auto [last_desc, last_id] = m_provider_chain_ids.back();
1614 auto it = m_frame_providers.find(last_id);
1615 if (it != m_frame_providers.end()) {
1616 SyntheticFrameProviderSP last_provider = it->second;
1617 StackFrameListSP input_frames = last_provider->GetInputFrames();
1618 m_curr_frames_sp = std::make_shared<SyntheticStackFrameList>(
1619 *this, input_frames, m_prev_frames_sp, true, last_provider, last_id);
1620 } else {
1622 "Missing frame provider (id = {0}) in Thread #{1:x}}", last_id,
1623 GetID());
1624 }
1625 }
1626
1627 if (!m_curr_frames_sp) {
1628 // No provider - use normal unwinder frames with stable ID = 0.
1629 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1630 *this, m_prev_frames_sp, true, /*provider_id=*/0);
1632 } else {
1633 // Register this frame list by its identifier for later lookup.
1634 m_frame_lists_by_id.insert(
1635 {m_curr_frames_sp->GetIdentifier(), m_curr_frames_sp});
1636 }
1637
1638 return m_curr_frames_sp;
1639}
1640
1643 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1644
1645 // ID 0 is reserved for the unwinder frame list. Always return the unwinder
1646 // frame list for ID 0.
1647 if (id == 0) {
1648 return m_unwinder_frames_sp;
1649 }
1650
1651 auto it = m_frame_lists_by_id.find(id);
1652 if (it != m_frame_lists_by_id.end()) {
1653 auto sp = it->second.lock();
1655 "GetFrameListByIdentifier({0}): found={1}, locked={2}", id, true,
1656 sp != nullptr);
1657 return sp;
1658 }
1659 LLDB_LOG(GetLog(LLDBLog::Thread), "GetFrameListByIdentifier({0}): found={1}",
1660 id, false);
1661 return nullptr;
1662}
1663
1665 const ScriptedFrameProviderDescriptor &descriptor) {
1666 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1667
1668 StackFrameListSP input_frames;
1669 if (m_frame_providers.empty()) {
1670 // First provider gets real unwinder frames with stable ID = 0.
1672 std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true,
1673 /*provider_id=*/0);
1674 input_frames = m_unwinder_frames_sp;
1675 } else {
1676 // Subsequent providers wrap the previous provider.
1677 auto [last_desc, last_id] = m_provider_chain_ids.back();
1678 auto it = m_frame_providers.find(last_id);
1679 if (it == m_frame_providers.end())
1680 return llvm::createStringError("previous frame provider not found");
1681 SyntheticFrameProviderSP last_provider = it->second;
1682 StackFrameListSP last_provider_frames = last_provider->GetInputFrames();
1683 input_frames = std::make_shared<SyntheticStackFrameList>(
1684 *this, last_provider_frames, m_prev_frames_sp, true, last_provider,
1685 last_id);
1686 // Register this intermediate frame list so 'bt --provider <id>' can
1687 // show each provider's output independently.
1688 m_frame_lists_by_id.insert({last_id, input_frames});
1690 "Registered intermediate frame list for provider id={0}, "
1691 "use_count={1}",
1692 last_id, input_frames.use_count());
1693 }
1694
1695 // Protect provider construction (__init__) from re-entrancy. If the
1696 // provider calls back into the frame machinery (e.g. HandleCommand("bt"))
1697 // during __init__, GetStackFrameList() will find this thread in the
1698 // active-provider map and return input_frames instead of trying to
1699 // build a new synthetic list — preventing infinite recursion.
1700 PushProviderFrameList(input_frames);
1701 auto provider_or_err =
1702 SyntheticFrameProvider::CreateInstance(input_frames, descriptor);
1704 if (!provider_or_err)
1705 return provider_or_err.takeError();
1706
1707 lldb::frame_list_id_t provider_id = descriptor.GetID();
1708
1709 m_frame_providers.insert({provider_id, *provider_or_err});
1710
1711 // Add to the provider chain.
1712 m_provider_chain_ids.push_back({descriptor, provider_id});
1713
1714 return llvm::Error::success();
1715}
1716
1717llvm::Expected<ScriptedFrameProviderDescriptor>
1719 lldb::frame_list_id_t id) const {
1722
1723 auto it = llvm::find_if(
1725 [id](const std::pair<ScriptedFrameProviderDescriptor,
1726 lldb::frame_list_id_t> &provider_id_pair) {
1727 return provider_id_pair.second == id;
1728 });
1729
1730 if (it == m_provider_chain_ids.end())
1731 return llvm::createStringError(
1732 "Couldn't find ScriptedFrameProviderDescriptor for id = %u.", id);
1733
1734 return it->first;
1735}
1736
1738 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1739 m_frame_providers.clear();
1740 m_provider_chain_ids.clear();
1741 m_frame_lists_by_id.clear();
1742 m_unwinder_frames_sp.reset();
1743 m_curr_frames_sp.reset();
1744 m_prev_frames_sp.reset();
1745}
1746
1747std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1748 return m_prev_framezero_pc;
1749}
1750
1752 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1753
1754 // If any host thread is inside a frame provider call (e.g. the provider
1755 // called EvaluateExpression which resumes the process), don't tear down the
1756 // frame state. The synthetic frame list is still being constructed and the
1757 // thread will stop right back where it was after the expression finishes.
1758 // This must be a global check (not per-host-thread) because the frame state
1759 // is shared and clearing it would destroy in-progress provider work.
1760 if (IsAnyProviderActive())
1761 return;
1762
1763 GetUnwinder().Clear();
1764 m_prev_framezero_pc.reset();
1765 if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1766 m_prev_framezero_pc = reg_ctx_sp->GetPC();
1767
1768 // Only store away the old "reference" StackFrameList if we got all its
1769 // frames:
1770 // FIXME: At some point we can try to splice in the frames we have fetched
1771 // into the new frame as we make it, but let's not try that now.
1772 if (m_curr_frames_sp && m_curr_frames_sp->WereAllFramesFetched())
1774 m_curr_frames_sp.reset();
1775 m_unwinder_frames_sp.reset();
1776
1777 // Clear the provider instances and reset the ID counter, but keep the
1778 // chain configuration (m_provider_chain_ids) so providers are re-loaded
1779 // with consistent IDs on the next GetStackFrameList() call.
1780 m_frame_providers.clear();
1781 m_frame_lists_by_id.clear();
1782 m_extended_info.reset();
1784}
1785
1787 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1788}
1789
1791 lldb::ValueObjectSP return_value_sp,
1792 bool broadcast) {
1793 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1794 Status return_error;
1795
1796 if (!frame_sp) {
1797 return_error = Status::FromErrorStringWithFormat(
1798 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1799 frame_idx, GetID());
1800 }
1801
1802 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1803}
1804
1806 lldb::ValueObjectSP return_value_sp,
1807 bool broadcast) {
1808 Status return_error;
1809
1810 if (!frame_sp) {
1811 return_error = Status::FromErrorString("Can't return to a null frame.");
1812 return return_error;
1813 }
1814
1815 Thread *thread = frame_sp->GetThread().get();
1816 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1817 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1818 if (!older_frame_sp) {
1819 return_error = Status::FromErrorString("No older frame to return to.");
1820 return return_error;
1821 }
1822
1823 if (return_value_sp) {
1824 lldb::ABISP abi = thread->GetProcess()->GetABI();
1825 if (!abi) {
1826 return_error =
1827 Status::FromErrorString("Could not find ABI to set return value.");
1828 return return_error;
1829 }
1830 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1831
1832 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1833 // for scalars.
1834 // Turn that back on when that works.
1835 if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1836 Type *function_type = sc.function->GetType();
1837 if (function_type) {
1838 CompilerType return_type =
1840 if (return_type) {
1841 StreamString s;
1842 return_type.DumpTypeDescription(&s);
1843 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1844 if (cast_value_sp) {
1845 cast_value_sp->SetFormat(eFormatHex);
1846 return_value_sp = cast_value_sp;
1847 }
1848 }
1849 }
1850 }
1851
1852 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1853 if (!return_error.Success())
1854 return return_error;
1855 }
1856
1857 // Now write the return registers for the chosen frame: Note, we can't use
1858 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1859 // their data
1860
1861 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1862 if (youngest_frame_sp) {
1863 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1864 if (reg_ctx_sp) {
1865 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1866 older_frame_sp->GetRegisterContext());
1867 if (copy_success) {
1868 thread->DiscardThreadPlans(true);
1869 thread->ClearStackFrames();
1871 auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());
1873 }
1874 } else {
1875 return_error =
1876 Status::FromErrorString("Could not reset register values.");
1877 }
1878 } else {
1879 return_error = Status::FromErrorString("Frame has no register context.");
1880 }
1881 } else {
1882 return_error = Status::FromErrorString("Returned past top frame.");
1883 }
1884 return return_error;
1885}
1886
1887static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1888 ExecutionContextScope *exe_scope) {
1889 for (size_t n = 0; n < list.size(); n++) {
1890 s << "\t";
1891 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1893 s << "\n";
1894 }
1895}
1896
1897Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1898 bool can_leave_function, std::string *warnings) {
1900 Target *target = exe_ctx.GetTargetPtr();
1901 TargetSP target_sp = exe_ctx.GetTargetSP();
1902 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1903 StackFrame *frame = exe_ctx.GetFramePtr();
1904 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1905
1906 // Find candidate locations.
1907 std::vector<Address> candidates, within_function, outside_function;
1908 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1909 within_function, outside_function);
1910
1911 // If possible, we try and stay within the current function. Within a
1912 // function, we accept multiple locations (optimized code may do this,
1913 // there's no solution here so we do the best we can). However if we're
1914 // trying to leave the function, we don't know how to pick the right
1915 // location, so if there's more than one then we bail.
1916 if (!within_function.empty())
1917 candidates = within_function;
1918 else if (outside_function.size() == 1 && can_leave_function)
1919 candidates = outside_function;
1920
1921 // Check if we got anything.
1922 if (candidates.empty()) {
1923 if (outside_function.empty()) {
1925 "Cannot locate an address for {0}:{1}.", file.GetFilename(), line);
1926 } else if (outside_function.size() == 1) {
1928 "{0}:{1} is outside the current function.", file.GetFilename(), line);
1929 } else {
1930 StreamString sstr;
1931 DumpAddressList(sstr, outside_function, target);
1933 "{0}:{1} has multiple candidate locations:\n{2}", file.GetFilename(),
1934 line, sstr.GetData());
1935 }
1936 }
1937
1938 // Accept the first location, warn about any others.
1939 Address dest = candidates[0];
1940 if (warnings && candidates.size() > 1) {
1941 StreamString sstr;
1942 sstr.Format(
1943 "{0}:{1} appears multiple times in this function, selecting the "
1944 "first location:\n",
1945 file.GetFilename(), line);
1946 DumpAddressList(sstr, candidates, target);
1947 *warnings = std::string(sstr.GetString().trim('\n'));
1948 }
1949
1950 if (!reg_ctx->SetPC(dest))
1951 return Status::FromErrorString("Cannot change PC to target address.");
1952
1953 return Status();
1954}
1955
1956bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,
1957 const FormatEntity::Entry *format) {
1958 ExecutionContext exe_ctx(shared_from_this());
1959 Process *process = exe_ctx.GetProcessPtr();
1960 if (!process || !format)
1961 return false;
1962
1963 StackFrameSP frame_sp;
1964 SymbolContext frame_sc;
1965 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1966 frame_sp = GetStackFrameAtIndex(frame_idx);
1967 if (frame_sp) {
1968 exe_ctx.SetFrameSP(frame_sp);
1969 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1970 }
1971 }
1972
1973 return FormatEntity::Formatter(frame_sp ? &frame_sc : nullptr, &exe_ctx,
1974 nullptr, false, false)
1975 .Format(*format, strm);
1976}
1977
1978void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1979 bool stop_format) {
1980 ExecutionContext exe_ctx(shared_from_this());
1981
1982 const FormatEntity::Entry *thread_format;
1983 FormatEntity::Entry format_entry;
1984 if (stop_format) {
1985 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1986 thread_format = &format_entry;
1987 } else {
1988 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1989 thread_format = &format_entry;
1990 }
1991
1992 assert(thread_format);
1993
1994 DumpUsingFormat(strm, frame_idx, thread_format);
1995}
1996
1998
2000
2002 if (m_reg_context_sp)
2003 return m_reg_context_sp->GetThreadPointer();
2004 return LLDB_INVALID_ADDRESS;
2005}
2006
2008 lldb::addr_t tls_file_addr) {
2009 // The default implementation is to ask the dynamic loader for it. This can
2010 // be overridden for specific platforms.
2011 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2012 if (loader)
2013 return loader->GetThreadLocalData(module, shared_from_this(),
2014 tls_file_addr);
2015 else
2016 return LLDB_INVALID_ADDRESS;
2017}
2018
2020 Process *process = GetProcess().get();
2021 if (process) {
2022 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
2023 if (loader && loader->IsFullyInitialized() == false)
2024 return false;
2025
2026 SystemRuntime *runtime = process->GetSystemRuntime();
2027 if (runtime) {
2028 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
2029 }
2030 }
2031 return true;
2032}
2033
2036 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
2037}
2038
2040 switch (reason) {
2041 case eStopReasonInvalid:
2042 return "invalid";
2043 case eStopReasonNone:
2044 return "none";
2045 case eStopReasonTrace:
2046 return "trace";
2048 return "breakpoint";
2050 return "watchpoint";
2051 case eStopReasonSignal:
2052 return "signal";
2054 return "exception";
2055 case eStopReasonExec:
2056 return "exec";
2057 case eStopReasonFork:
2058 return "fork";
2059 case eStopReasonVFork:
2060 return "vfork";
2062 return "vfork done";
2064 return "plan complete";
2066 return "thread exiting";
2068 return "instrumentation break";
2070 return "processor trace";
2072 return "async interrupt";
2074 return "history boundary";
2075 }
2076
2077 return "StopReason = " + std::to_string(reason);
2078}
2079
2081 switch (mode) {
2082 case eOnlyThisThread:
2083 return "only this thread";
2084 case eAllThreads:
2085 return "all threads";
2087 return "only during stepping";
2088 }
2089
2090 return "RunMode = " + std::to_string(mode);
2091}
2092
2093size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
2094 uint32_t num_frames, uint32_t num_frames_with_source,
2095 bool stop_format, bool show_hidden, bool only_stacks) {
2096
2097 ExecutionContext exe_ctx(shared_from_this());
2098 Target *target = exe_ctx.GetTargetPtr();
2099 if (!only_stacks) {
2100 Process *process = exe_ctx.GetProcessPtr();
2101 strm.Indent();
2102 bool is_selected = false;
2103 if (process) {
2104 if (process->GetThreadList().GetSelectedThread().get() == this)
2105 is_selected = true;
2106 }
2107 strm.Printf("%c ", is_selected ? '*' : ' ');
2108 if (target && target->GetDebugger().GetUseExternalEditor()) {
2109 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2110 if (frame_sp) {
2111 SymbolContext frame_sc(
2112 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
2113 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {
2114 if (llvm::Error e = Host::OpenFileInExternalEditor(
2115 target->GetDebugger().GetExternalEditor(),
2116 frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {
2117 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
2118 "OpenFileInExternalEditor failed: {0}");
2119 }
2120 }
2121 }
2122 }
2123
2124 DumpUsingSettingsFormat(strm, start_frame, stop_format);
2125 }
2126
2127 size_t num_frames_shown = 0;
2128 if (num_frames > 0) {
2129 strm.IndentMore();
2130
2131 const bool show_frame_info = true;
2132 const bool show_frame_unique = only_stacks;
2133 bool show_selected_frame = false;
2134 if (num_frames == 1 || only_stacks ||
2135 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2136 strm.IndentMore();
2137 else
2138 show_selected_frame = true;
2139
2140 bool show_hidden_marker =
2141 target && target->GetDebugger().GetMarkHiddenFrames();
2142 num_frames_shown = GetStackFrameList()->GetStatus(
2143 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
2144 show_frame_unique, show_hidden, show_hidden_marker,
2145 show_selected_frame);
2146 if (num_frames == 1)
2147 strm.IndentLess();
2148 strm.IndentLess();
2149 }
2150 return num_frames_shown;
2151}
2152
2154 bool print_json_thread, bool print_json_stopinfo) {
2155 const bool stop_format = false;
2156 DumpUsingSettingsFormat(strm, 0, stop_format);
2157 strm.Printf("\n");
2158
2160
2161 if (print_json_thread || print_json_stopinfo) {
2162 if (thread_info && print_json_thread) {
2163 thread_info->Dump(strm);
2164 strm.Printf("\n");
2165 }
2166
2167 if (print_json_stopinfo && m_stop_info_sp) {
2168 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2169 if (stop_info) {
2170 stop_info->Dump(strm);
2171 strm.Printf("\n");
2172 }
2173 }
2174
2175 return true;
2176 }
2177
2178 if (thread_info) {
2179 StructuredData::ObjectSP activity =
2180 thread_info->GetObjectForDotSeparatedPath("activity");
2181 StructuredData::ObjectSP breadcrumb =
2182 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2183 StructuredData::ObjectSP messages =
2184 thread_info->GetObjectForDotSeparatedPath("trace_messages");
2185
2186 bool printed_activity = false;
2187 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
2188 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2189 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2190 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2191 if (name && name->GetType() == eStructuredDataTypeString && id &&
2192 id->GetType() == eStructuredDataTypeInteger) {
2193 strm.Format(" Activity '{0}', {1:x}\n",
2194 name->GetAsString()->GetValue(),
2195 id->GetUnsignedIntegerValue());
2196 }
2197 printed_activity = true;
2198 }
2199 bool printed_breadcrumb = false;
2200 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2201 if (printed_activity)
2202 strm.Printf("\n");
2203 StructuredData::Dictionary *breadcrumb_dict =
2204 breadcrumb->GetAsDictionary();
2205 StructuredData::ObjectSP breadcrumb_text =
2206 breadcrumb_dict->GetValueForKey("name");
2207 if (breadcrumb_text &&
2208 breadcrumb_text->GetType() == eStructuredDataTypeString) {
2209 strm.Format(" Current Breadcrumb: {0}\n",
2210 breadcrumb_text->GetAsString()->GetValue());
2211 }
2212 printed_breadcrumb = true;
2213 }
2214 if (messages && messages->GetType() == eStructuredDataTypeArray) {
2215 if (printed_breadcrumb)
2216 strm.Printf("\n");
2217 StructuredData::Array *messages_array = messages->GetAsArray();
2218 const size_t msg_count = messages_array->GetSize();
2219 if (msg_count > 0) {
2220 strm.Printf(" %zu trace messages:\n", msg_count);
2221 for (size_t i = 0; i < msg_count; i++) {
2222 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2223 if (message && message->GetType() == eStructuredDataTypeDictionary) {
2224 StructuredData::Dictionary *message_dict =
2225 message->GetAsDictionary();
2226 StructuredData::ObjectSP message_text =
2227 message_dict->GetValueForKey("message");
2228 if (message_text &&
2229 message_text->GetType() == eStructuredDataTypeString) {
2230 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
2231 }
2232 }
2233 }
2234 }
2235 }
2236 }
2237
2238 return true;
2239}
2240
2241size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2242 uint32_t num_frames, bool show_frame_info,
2243 uint32_t num_frames_with_source,
2244 bool show_hidden) {
2245 ExecutionContext exe_ctx(shared_from_this());
2246 Target *target = exe_ctx.GetTargetPtr();
2247 bool show_hidden_marker =
2248 target && target->GetDebugger().GetMarkHiddenFrames();
2249 return GetStackFrameList()->GetStatus(
2250 strm, first_frame, num_frames, show_frame_info, num_frames_with_source,
2251 /*show_unique*/ false, show_hidden, show_hidden_marker);
2252}
2253
2255 if (!m_unwinder_up)
2256 m_unwinder_up = std::make_unique<UnwindLLDB>(*this);
2257 return *m_unwinder_up;
2258}
2259
2265
2267 // If we are currently stopped at a breakpoint, always return that stopinfo
2268 // and don't reset it. This allows threads to maintain their breakpoint
2269 // stopinfo, such as when thread-stepping in multithreaded programs.
2270 if (m_stop_info_sp) {
2271 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2272 if (stop_reason == lldb::eStopReasonBreakpoint) {
2273 uint64_t value = m_stop_info_sp->GetValue();
2275 if (reg_ctx_sp) {
2276 lldb::addr_t pc = reg_ctx_sp->GetPC();
2277 BreakpointSiteSP bp_site_sp =
2278 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2279 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2280 return true;
2281 }
2282 }
2283 }
2284 return false;
2285}
2286
2287Status Thread::StepIn(bool source_step,
2288 LazyBool step_in_avoids_code_without_debug_info,
2289 LazyBool step_out_avoids_code_without_debug_info)
2290
2291{
2292 Status error;
2293 Process *process = GetProcess().get();
2294 if (StateIsStoppedState(process->GetState(), true)) {
2295 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2296 ThreadPlanSP new_plan_sp;
2297 const lldb::RunMode run_mode = eOnlyThisThread;
2298 const bool abort_other_plans = false;
2299
2300 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2301 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2302 new_plan_sp = QueueThreadPlanForStepInRange(
2303 abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
2304 step_in_avoids_code_without_debug_info,
2305 step_out_avoids_code_without_debug_info);
2306 } else {
2308 false, abort_other_plans, run_mode, error);
2309 }
2310
2311 new_plan_sp->SetIsControllingPlan(true);
2312 new_plan_sp->SetOkayToDiscard(false);
2313
2314 // Why do we need to set the current thread by ID here???
2316 error = process->Resume();
2317 } else {
2318 error = Status::FromErrorString("process not stopped");
2319 }
2320 return error;
2321}
2322
2323Status Thread::StepOver(bool source_step,
2324 LazyBool step_out_avoids_code_without_debug_info) {
2325 Status error;
2326 Process *process = GetProcess().get();
2327 if (StateIsStoppedState(process->GetState(), true)) {
2328 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2329 ThreadPlanSP new_plan_sp;
2330
2331 const lldb::RunMode run_mode = eOnlyThisThread;
2332 const bool abort_other_plans = false;
2333
2334 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2335 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2336 new_plan_sp = QueueThreadPlanForStepOverRange(
2337 abort_other_plans, sc.line_entry, sc, run_mode, error,
2338 step_out_avoids_code_without_debug_info);
2339 } else {
2341 true, abort_other_plans, run_mode, error);
2342 }
2343
2344 new_plan_sp->SetIsControllingPlan(true);
2345 new_plan_sp->SetOkayToDiscard(false);
2346
2347 // Why do we need to set the current thread by ID here???
2349 error = process->Resume();
2350 } else {
2351 error = Status::FromErrorString("process not stopped");
2352 }
2353 return error;
2354}
2355
2356Status Thread::StepOut(uint32_t frame_idx) {
2357 Status error;
2358 Process *process = GetProcess().get();
2359 if (StateIsStoppedState(process->GetState(), true)) {
2360 const bool first_instruction = false;
2361 const bool stop_other_threads = false;
2362 const bool abort_other_plans = false;
2363
2365 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2366 eVoteYes, eVoteNoOpinion, frame_idx, error));
2367
2368 new_plan_sp->SetIsControllingPlan(true);
2369 new_plan_sp->SetOkayToDiscard(false);
2370
2371 // Why do we need to set the current thread by ID here???
2373 error = process->Resume();
2374 } else {
2375 error = Status::FromErrorString("process not stopped");
2376 }
2377 return error;
2378}
2379
2381 if (auto frame_sp = GetStackFrameAtIndex(0))
2382 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2383 if (auto e = recognized_frame->GetExceptionObject())
2384 return e;
2385
2386 // NOTE: Even though this behavior is generalized, only ObjC is actually
2387 // supported at the moment.
2388 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2389 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2390 return e;
2391 }
2392
2393 return ValueObjectSP();
2394}
2395
2397 ValueObjectSP exception = GetCurrentException();
2398 if (!exception)
2399 return ThreadSP();
2400
2401 // NOTE: Even though this behavior is generalized, only ObjC is actually
2402 // supported at the moment.
2403 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2404 if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2405 return bt;
2406 }
2407
2408 return ThreadSP();
2409}
2410
2412 ProcessSP process_sp = GetProcess();
2413 assert(process_sp);
2414 Target &target = process_sp->GetTarget();
2415 PlatformSP platform_sp = target.GetPlatform();
2416 assert(platform_sp);
2417 ArchSpec arch = target.GetArchitecture();
2418
2419 CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());
2420 if (!type.IsValid())
2422 &target, Status::FromErrorString("no siginfo_t for the platform"));
2423
2424 auto type_size_or_err = type.GetByteSize(nullptr);
2425 if (!type_size_or_err)
2427 &target, Status::FromError(type_size_or_err.takeError()));
2428
2429 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
2430 GetSiginfo(*type_size_or_err);
2431 if (!data)
2432 return ValueObjectConstResult::Create(&target,
2433 Status::FromError(data.takeError()));
2434
2435 DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),
2436 process_sp->GetByteOrder(), arch.GetAddressByteSize()};
2437 return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);
2438}
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:364
#define LLDB_LOGF(log,...)
Definition Log.h:378
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:394
static void DumpAddressList(Stream &s, const std::vector< Address > &list, ExecutionContextScope *exe_scope)
Definition Thread.cpp:1887
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:690
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:460
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:503
FormatEntity::Entry GetThreadStopFormat() const
Definition Debugger.cpp:432
llvm::StringRef GetExternalEditor() const
Definition Debugger.cpp:514
FormatEntity::Entry GetThreadFormat() const
Definition Debugger.cpp:427
bool GetMarkHiddenFrames() const
Definition Debugger.cpp:657
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:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:250
bool Format(const Entry &entry, Stream &s, ValueObject *valobj=nullptr)
CompilerType GetCompilerType()
Definition Function.cpp:576
Type * GetType()
Get accessor for the type that describes the function return value type, and parameter types.
Definition Function.cpp:555
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
static llvm::Error OpenFileInExternalEditor(llvm::StringRef editor, const FileSpec &file_spec, uint32_t line_no)
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.h:87
Policy Current() const
Definition Policy.cpp:17
static bool GetRestartedFromEvent(const Event *event_ptr)
Definition Process.cpp:4738
A plug-in interface definition class for debugging a process.
Definition Process.h:356
ThreadList & GetThreadList()
Definition Process.h:2347
Status Resume()
Resumes all of a process's threads as configured using the Thread run control functions.
Definition Process.cpp:1332
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3102
lldb::StateType GetState()
Get accessor for the current process state.
Definition Process.cpp:1278
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
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:3910
Debugger & GetDebugger() const
Definition Target.h:1323
lldb::PlatformSP GetPlatform()
Definition Target.h:1972
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1240
const ArchSpec & GetArchitecture() const
Definition Target.h:1282
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:417
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:385
Vote ShouldReportRun(Event *event_ptr)
const char * GetName() const
Returns the name of this thread plan.
Definition ThreadPlan.h:324
ThreadPlanKind GetKind() const
Definition ThreadPlan.h:446
virtual bool ShouldRunBeforePublicStop()
Definition ThreadPlan.h:404
bool PlanExplainsStop(Event *event_ptr)
bool WillResume(lldb::StateType resume_state, bool current_plan)
virtual bool MischiefManaged()
virtual bool IsPlanStale()
Definition ThreadPlan.h:452
virtual bool WillStop()=0
virtual bool ShouldStop(Event *event_ptr)=0
virtual bool IsBasePlan()
Definition ThreadPlan.h:456
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:115
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:1372
bool IsThreadPlanDone(ThreadPlan *plan) const
Checks whether the given plan is in the completed plans for this stop.
Definition Thread.cpp:1205
virtual lldb::user_id_t GetProtocolID() const
Definition Thread.h:1168
lldb::ThreadSP GetCurrentExceptionBacktrace()
Definition Thread.cpp:2396
std::optional< lldb::addr_t > GetPreviousFrameZeroPC()
Request the pc value the thread had when previously stopped.
Definition Thread.cpp:1747
void BroadcastSelectedFrameChange(StackID &new_frame_id)
Definition Thread.cpp:278
@ eBroadcastBitSelectedFrameChanged
Definition Thread.h:79
Status UnwindInnermostExpression()
Unwinds the thread stack for the innermost expression plan currently on the thread plan stack.
Definition Thread.cpp:1288
~Thread() override
Definition Thread.cpp:250
llvm::Expected< ScriptedFrameProviderDescriptor > GetScriptedFrameProviderDescriptorForID(lldb::frame_list_id_t id) const
Definition Thread.cpp:1718
const uint32_t m_index_id
A unique 1 based index assigned to each thread for easy UI/command line access.
Definition Thread.h:1433
void SetShouldRunBeforePublicStop(bool newval)
Definition Thread.h:1278
virtual lldb::StackFrameSP GetStackFrameAtIndex(uint32_t idx)
Definition Thread.h:434
bool CompletedPlanOverridesBreakpoint() const
Check if we have completed plan to override breakpoint stop reason.
Definition Thread.cpp:1213
lldb::StackFrameListSP m_curr_frames_sp
The stack frames that get lazily populated after a thread stops.
Definition Thread.h:1444
virtual bool SafeToCallFunctions()
Check whether this thread is safe to run functions.
Definition Thread.cpp:2019
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:1221
bool WasThreadPlanDiscarded(ThreadPlan *plan) const
Checks whether the given plan is in the discarded plans for this stop.
Definition Thread.cpp:1209
virtual lldb::RegisterContextSP GetRegisterContext()=0
virtual lldb::addr_t GetThreadPointer()
Retrieves the per-thread data area.
Definition Thread.cpp:2001
virtual void DidStop()
Definition Thread.cpp:779
virtual bool RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:549
friend class ThreadPlan
Definition Thread.h:1366
bool SetupToStepOverBreakpointIfNeeded(lldb::RunDirection direction)
Definition Thread.cpp:638
uint32_t m_stop_info_stop_id
Definition Thread.h:1420
void AutoCompleteThreadPlans(CompletionRequest &request) const
Format the thread plan information for auto completion.
Definition Thread.cpp:1164
std::recursive_mutex m_frame_mutex
Multithreaded protection for m_state.
Definition Thread.h:1441
static void SettingsInitialize()
Definition Thread.cpp:1997
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:1449
std::optional< lldb::addr_t > m_prev_framezero_pc
Frame 0's PC the last time this thread was stopped.
Definition Thread.h:1464
Status ReturnFromFrame(lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1805
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Thread.cpp:1465
void DiscardThreadPlans(bool force)
Discards the plans queued on the plan stack of the current thread.
Definition Thread.cpp:1274
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:2153
static std::string RunModeAsString(lldb::RunMode mode)
Definition Thread.cpp:2080
void PushProviderFrameList(lldb::StackFrameListSP frames)
Push/pop provider input frames for the current host thread.
Definition Thread.cpp:1469
void SetTemporaryResumeState(lldb::StateType new_state)
Definition Thread.h:1406
virtual bool MatchesSpec(const ThreadSpec *spec)
Definition Thread.cpp:1113
lldb::ProcessSP CalculateProcess() override
Definition Thread.cpp:1459
StructuredData::ObjectSP GetExtendedInfo()
Retrieve a dictionary of information about this thread.
Definition Thread.h:281
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:2007
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:1416
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:1403
lldb::StackFrameSP GetSelectedFrame(SelectMostRelevant select_most_relevant)
Definition Thread.cpp:287
virtual bool IsStillAtLastBreakpointHit()
Definition Thread.cpp:2266
std::recursive_mutex m_state_mutex
Multithreaded protection for m_state.
Definition Thread.h:1439
void PopProviderFrameList()
Definition Thread.cpp:1479
ThreadPlan * GetPreviousPlan(ThreadPlan *plan) const
Definition Thread.cpp:1217
virtual const char * GetName()
Definition Thread.h:289
void PushPlan(lldb::ThreadPlanSP plan_sp)
Definition Thread.cpp:1133
lldb::StackFrameListSP m_prev_frames_sp
The previous stack frames from the last time this thread stopped.
Definition Thread.h:1461
virtual void ClearStackFrames()
Definition Thread.cpp:1751
ThreadPlan * GetCurrentPlan() const
Gets the plan which will execute next on the plan stack.
Definition Thread.cpp:1180
virtual Unwind & GetUnwinder()
Definition Thread.cpp:2254
static llvm::StringRef GetStaticBroadcasterClass()
Definition Thread.cpp:221
void SetResumeSignal(int signal)
Definition Thread.h:165
bool IsAnyProviderActive()
Returns true if any host thread is currently inside a provider.
Definition Thread.cpp:1496
lldb::ValueObjectSP GetReturnValueObject() const
Gets the outer-most return value from the completed plans.
Definition Thread.cpp:1197
virtual lldb::ThreadSP GetBackingThread() const
Definition Thread.h:525
bool IsRunningCallFunctionPlan() const
Returns true if this thread has a ThreadPlanCallFunction on its plan stack, indicating it is running ...
Definition Thread.cpp:1184
lldb::ExpressionVariableSP GetExpressionVariable() const
Gets the outer-most expression variable from the completed plans.
Definition Thread.cpp:1201
Vote ShouldReportRun(Event *event_ptr)
Definition Thread.cpp:1081
lldb::TargetSP CalculateTarget() override
Definition Thread.cpp:1451
static std::string StopReasonAsString(lldb::StopReason reason)
Definition Thread.cpp:2039
lldb::StackFrameListSP GetFrameListByIdentifier(lldb::frame_list_id_t id)
Get a frame list by its unique identifier.
Definition Thread.cpp:1642
virtual void WillResume(lldb::StateType resume_state)
Definition Thread.h:219
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:1430
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:2241
std::string GetStopDescriptionRaw()
Definition Thread.cpp:614
void ClearScriptedFrameProvider()
Definition Thread.cpp:1737
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:1249
virtual Status StepOver(bool source_step, LazyBool step_out_avoids_code_without_debug_info=eLazyBoolCalculate)
Default implementation for stepping over.
Definition Thread.cpp:2323
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:1476
std::unique_ptr< ThreadPlanStack > m_null_plan_stack_up
Definition Thread.h:1480
lldb::StateType GetTemporaryResumeState() const
Definition Thread.h:1268
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:1664
lldb::ProcessSP GetProcess() const
Definition Thread.h:161
lldb::StackFrameSP CalculateStackFrame() override
Definition Thread.cpp:1463
lldb::StateType GetResumeState() const
Gets the USER resume state for this thread.
Definition Thread.h:205
friend class StackFrame
Definition Thread.h:1370
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:1427
lldb::StopInfoSP m_stop_info_sp
The private stop reason for this thread.
Definition Thread.h:1419
std::mutex m_provider_frames_mutex
Per-host-thread stack of active provider input frames.
Definition Thread.h:1458
lldb::ProcessWP m_process_wp
The process that owns this thread.
Definition Thread.h:1418
void DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, bool stop_format)
Definition Thread.cpp:1978
LazyBool m_override_should_notify
Definition Thread.h:1479
lldb::ThreadSP CalculateThread() override
Definition Thread.cpp:1461
Status ReturnFromFrameWithIndex(uint32_t frame_idx, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1790
virtual Status StepOut(uint32_t frame_idx=0)
Default implementation for stepping out.
Definition Thread.cpp:2356
virtual llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > GetSiginfo(size_t max_size) const
Definition Thread.h:1413
virtual lldb::ThreadPlanSP QueueThreadPlanForStepInRange(bool abort_other_plans, const AddressRange &range, const SymbolContext &addr_context, const char *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:1342
lldb::StateType GetState() const
Definition Thread.cpp:583
lldb::StateType m_state
The state of our process.
Definition Thread.h:1437
virtual lldb::ThreadPlanSP QueueThreadPlanForStepScripted(bool abort_other_plans, const char *class_name, StructuredData::ObjectSP extra_args_sp, bool stop_other_threads, Status &status)
Definition Thread.cpp:1437
bool m_extended_info_fetched
Definition Thread.h:1500
void CalculatePublicStopInfo()
Definition Thread.cpp:396
static void SettingsTerminate()
Definition Thread.cpp:1999
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:1117
lldb::ValueObjectSP GetSiginfoValue()
Definition Thread.cpp:2411
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:1306
uint32_t m_stop_info_override_stop_id
Definition Thread.h:1424
int m_resume_signal
The signal that should be used when continuing this thread.
Definition Thread.h:1466
virtual void DidResume()
Definition Thread.cpp:773
bool StopInfoIsUpToDate() const
Definition Thread.cpp:464
lldb::StackFrameSP GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr)
Definition Thread.cpp:2035
llvm::DenseMap< lldb::frame_list_id_t, lldb::SyntheticFrameProviderSP > m_frame_providers
Map from frame list ID to its frame provider.
Definition Thread.h:1488
lldb::ThreadPlanSP GetCompletedPlan() const
Gets the outer-most plan that was popped off the plan stack in the most recent stop.
Definition Thread.cpp:1193
lldb::ValueObjectSP GetCurrentException()
Definition Thread.cpp:2380
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:1385
virtual lldb::StackFrameSP GetFrameWithConcreteFrameIndex(uint32_t unwind_idx)
Definition Thread.cpp:1786
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:1897
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:1956
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:1261
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:1300
static ThreadProperties & GetGlobalProperties()
Definition Thread.cpp:68
uint32_t GetCurrentInlinedDepth()
Definition Thread.h:445
llvm::DenseMap< HostThread, std::vector< lldb::StackFrameListSP > > m_active_frame_providers_by_thread
Definition Thread.h:1460
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:1315
std::string GetStopDescription()
Definition Thread.cpp:594
StructuredData::ObjectSP m_extended_info
Definition Thread.h:1502
lldb::StopInfoSP GetStopInfo()
Definition Thread.cpp:363
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:1497
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:1471
lldb::StackFrameListSP GetStackFrameList()
Definition Thread.cpp:1501
bool m_should_run_before_public_stop
Definition Thread.h:1427
Vote ShouldReportStop(Event *event_ptr)
Definition Thread.cpp:1020
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:1493
lldb::StateType m_resume_state
This state is used to force a thread to be suspended from outside the ThreadPlan logic.
Definition Thread.h:1468
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:2287
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:2093
lldb::RegisterContextSP m_reg_context_sp
The register context for this thread's current register state.
Definition Thread.h:1435
lldb::StackFrameListSP m_unwinder_frames_sp
The unwinder frame list (ID 0).
Definition Thread.h:1443
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:327
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
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:87
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:84
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:86
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:32
@ Private
Parent (unwinder) frames, private state, private run lock.
Definition Policy.h:36
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:134
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