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