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 // Sort by priority (lower number = higher priority).
1542 llvm::sort(thread_descriptors,
1545 // nullopt (no priority) sorts last (UINT32_MAX).
1546 uint32_t priority_a = a->GetPriority().value_or(UINT32_MAX);
1547 uint32_t priority_b = b->GetPriority().value_or(UINT32_MAX);
1548 return priority_a < priority_b;
1549 });
1550
1551 // Load ALL matching providers in priority order.
1552 for (const auto *descriptor : thread_descriptors) {
1553 if (llvm::Error error = LoadScriptedFrameProvider(*descriptor)) {
1555 "Failed to load scripted frame provider: {0}");
1556 continue; // Try next provider if this one fails.
1557 }
1558 }
1559 }
1560 }
1561
1562 // Create the frame list based on whether we have providers.
1563 if (!m_provider_chain_ids.empty()) {
1564 // We have providers - use the last one in the chain.
1565 // The last provider has already been chained with all previous providers.
1566 auto [last_desc, last_id] = m_provider_chain_ids.back();
1567 auto it = m_frame_providers.find(last_id);
1568 if (it != m_frame_providers.end()) {
1569 SyntheticFrameProviderSP last_provider = it->second;
1570 StackFrameListSP input_frames = last_provider->GetInputFrames();
1571 m_curr_frames_sp = std::make_shared<SyntheticStackFrameList>(
1572 *this, input_frames, m_prev_frames_sp, true, last_provider, last_id);
1573 } else {
1575 "Missing frame provider (id = {0}) in Thread #{1:x}}", last_id,
1576 GetID());
1577 }
1578 }
1579
1580 if (!m_curr_frames_sp) {
1581 // No provider - use normal unwinder frames with stable ID = 0.
1582 m_unwinder_frames_sp = std::make_shared<StackFrameList>(
1583 *this, m_prev_frames_sp, true, /*provider_id=*/0);
1585 } else {
1586 // Register this frame list by its identifier for later lookup.
1587 m_frame_lists_by_id.insert(
1588 {m_curr_frames_sp->GetIdentifier(), m_curr_frames_sp});
1589 }
1590
1591 return m_curr_frames_sp;
1592}
1593
1596 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1597
1598 // ID 0 is reserved for the unwinder frame list. Always return the unwinder
1599 // frame list for ID 0.
1600 if (id == 0) {
1601 return m_unwinder_frames_sp;
1602 }
1603
1604 auto it = m_frame_lists_by_id.find(id);
1605 if (it != m_frame_lists_by_id.end()) {
1606 return it->second.lock();
1607 }
1608 return nullptr;
1609}
1610
1612 const ScriptedFrameProviderDescriptor &descriptor) {
1613 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1614
1615 StackFrameListSP input_frames;
1616 if (m_frame_providers.empty()) {
1617 // First provider gets real unwinder frames with stable ID = 0.
1619 std::make_shared<StackFrameList>(*this, m_prev_frames_sp, true,
1620 /*provider_id=*/0);
1621 input_frames = m_unwinder_frames_sp;
1622 } else {
1623 // Subsequent providers wrap the previous provider.
1624 auto [last_desc, last_id] = m_provider_chain_ids.back();
1625 auto it = m_frame_providers.find(last_id);
1626 if (it == m_frame_providers.end())
1627 return llvm::createStringError("Previous frame provider not found");
1628 SyntheticFrameProviderSP last_provider = it->second;
1629 StackFrameListSP last_provider_frames = last_provider->GetInputFrames();
1630 input_frames = std::make_shared<SyntheticStackFrameList>(
1631 *this, last_provider_frames, m_prev_frames_sp, true, last_provider,
1632 last_id);
1633 }
1634
1635 // Protect provider construction (__init__) from re-entrancy. If the
1636 // provider calls back into the frame machinery (e.g. HandleCommand("bt"))
1637 // during __init__, GetStackFrameList() will find this thread in the
1638 // active-provider map and return input_frames instead of trying to
1639 // build a new synthetic list — preventing infinite recursion.
1640 PushProviderFrameList(input_frames);
1641 auto provider_or_err =
1642 SyntheticFrameProvider::CreateInstance(input_frames, descriptor);
1644 if (!provider_or_err)
1645 return provider_or_err.takeError();
1646
1647 if (m_next_provider_id == std::numeric_limits<lldb::frame_list_id_t>::max())
1649 else
1651
1653 m_frame_providers.insert({provider_id, *provider_or_err});
1654
1655 // Add to the provider chain.
1656 m_provider_chain_ids.push_back({descriptor, provider_id});
1657
1658 return llvm::Error::success();
1659}
1660
1661llvm::Expected<ScriptedFrameProviderDescriptor>
1663 lldb::frame_list_id_t id) const {
1666
1667 auto it = llvm::find_if(
1669 [id](const std::pair<ScriptedFrameProviderDescriptor,
1670 lldb::frame_list_id_t> &provider_id_pair) {
1671 return provider_id_pair.second == id;
1672 });
1673
1674 if (it == m_provider_chain_ids.end())
1675 return llvm::createStringError(
1676 "Couldn't find ScriptedFrameProviderDescriptor for id = %u.", id);
1677
1678 return it->first;
1679}
1680
1682 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1683 m_frame_providers.clear();
1684 m_provider_chain_ids.clear();
1685 m_next_provider_id = 1; // Reset counter.
1686 m_unwinder_frames_sp.reset();
1687 m_curr_frames_sp.reset();
1688 m_prev_frames_sp.reset();
1689}
1690
1691std::optional<addr_t> Thread::GetPreviousFrameZeroPC() {
1692 return m_prev_framezero_pc;
1693}
1694
1696 std::lock_guard<std::recursive_mutex> guard(m_frame_mutex);
1697
1698 // If any host thread is inside a frame provider call (e.g. the provider
1699 // called EvaluateExpression which resumes the process), don't tear down the
1700 // frame state. The synthetic frame list is still being constructed and the
1701 // thread will stop right back where it was after the expression finishes.
1702 // This must be a global check (not per-host-thread) because the frame state
1703 // is shared and clearing it would destroy in-progress provider work.
1704 if (IsAnyProviderActive())
1705 return;
1706
1707 GetUnwinder().Clear();
1708 m_prev_framezero_pc.reset();
1709 if (RegisterContextSP reg_ctx_sp = GetRegisterContext())
1710 m_prev_framezero_pc = reg_ctx_sp->GetPC();
1711
1712 // Only store away the old "reference" StackFrameList if we got all its
1713 // frames:
1714 // FIXME: At some point we can try to splice in the frames we have fetched
1715 // into the new frame as we make it, but let's not try that now.
1716 if (m_curr_frames_sp && m_curr_frames_sp->WereAllFramesFetched())
1718 m_curr_frames_sp.reset();
1719 m_unwinder_frames_sp.reset();
1720
1721 // Clear the provider instances, but keep the chain configuration
1722 // (m_provider_chain_ids and m_next_provider_id) so provider IDs
1723 // remain stable across ClearStackFrames() calls.
1724 m_frame_providers.clear();
1725 m_frame_lists_by_id.clear();
1726 m_extended_info.reset();
1728}
1729
1731 return GetStackFrameList()->GetFrameWithConcreteFrameIndex(unwind_idx);
1732}
1733
1735 lldb::ValueObjectSP return_value_sp,
1736 bool broadcast) {
1737 StackFrameSP frame_sp = GetStackFrameAtIndex(frame_idx);
1738 Status return_error;
1739
1740 if (!frame_sp) {
1741 return_error = Status::FromErrorStringWithFormat(
1742 "Could not find frame with index %d in thread 0x%" PRIx64 ".",
1743 frame_idx, GetID());
1744 }
1745
1746 return ReturnFromFrame(frame_sp, return_value_sp, broadcast);
1747}
1748
1750 lldb::ValueObjectSP return_value_sp,
1751 bool broadcast) {
1752 Status return_error;
1753
1754 if (!frame_sp) {
1755 return_error = Status::FromErrorString("Can't return to a null frame.");
1756 return return_error;
1757 }
1758
1759 Thread *thread = frame_sp->GetThread().get();
1760 uint32_t older_frame_idx = frame_sp->GetFrameIndex() + 1;
1761 StackFrameSP older_frame_sp = thread->GetStackFrameAtIndex(older_frame_idx);
1762 if (!older_frame_sp) {
1763 return_error = Status::FromErrorString("No older frame to return to.");
1764 return return_error;
1765 }
1766
1767 if (return_value_sp) {
1768 lldb::ABISP abi = thread->GetProcess()->GetABI();
1769 if (!abi) {
1770 return_error =
1771 Status::FromErrorString("Could not find ABI to set return value.");
1772 return return_error;
1773 }
1774 SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextFunction);
1775
1776 // FIXME: ValueObject::Cast doesn't currently work correctly, at least not
1777 // for scalars.
1778 // Turn that back on when that works.
1779 if (/* DISABLES CODE */ (false) && sc.function != nullptr) {
1780 Type *function_type = sc.function->GetType();
1781 if (function_type) {
1782 CompilerType return_type =
1784 if (return_type) {
1785 StreamString s;
1786 return_type.DumpTypeDescription(&s);
1787 ValueObjectSP cast_value_sp = return_value_sp->Cast(return_type);
1788 if (cast_value_sp) {
1789 cast_value_sp->SetFormat(eFormatHex);
1790 return_value_sp = cast_value_sp;
1791 }
1792 }
1793 }
1794 }
1795
1796 return_error = abi->SetReturnValueObject(older_frame_sp, return_value_sp);
1797 if (!return_error.Success())
1798 return return_error;
1799 }
1800
1801 // Now write the return registers for the chosen frame: Note, we can't use
1802 // ReadAllRegisterValues->WriteAllRegisterValues, since the read & write cook
1803 // their data
1804
1805 StackFrameSP youngest_frame_sp = thread->GetStackFrameAtIndex(0);
1806 if (youngest_frame_sp) {
1807 lldb::RegisterContextSP reg_ctx_sp(youngest_frame_sp->GetRegisterContext());
1808 if (reg_ctx_sp) {
1809 bool copy_success = reg_ctx_sp->CopyFromRegisterContext(
1810 older_frame_sp->GetRegisterContext());
1811 if (copy_success) {
1812 thread->DiscardThreadPlans(true);
1813 thread->ClearStackFrames();
1815 auto data_sp = std::make_shared<ThreadEventData>(shared_from_this());
1817 }
1818 } else {
1819 return_error =
1820 Status::FromErrorString("Could not reset register values.");
1821 }
1822 } else {
1823 return_error = Status::FromErrorString("Frame has no register context.");
1824 }
1825 } else {
1826 return_error = Status::FromErrorString("Returned past top frame.");
1827 }
1828 return return_error;
1829}
1830
1831static void DumpAddressList(Stream &s, const std::vector<Address> &list,
1832 ExecutionContextScope *exe_scope) {
1833 for (size_t n = 0; n < list.size(); n++) {
1834 s << "\t";
1835 list[n].Dump(&s, exe_scope, Address::DumpStyleResolvedDescription,
1837 s << "\n";
1838 }
1839}
1840
1841Status Thread::JumpToLine(const FileSpec &file, uint32_t line,
1842 bool can_leave_function, std::string *warnings) {
1844 Target *target = exe_ctx.GetTargetPtr();
1845 TargetSP target_sp = exe_ctx.GetTargetSP();
1846 RegisterContext *reg_ctx = exe_ctx.GetRegisterContext();
1847 StackFrame *frame = exe_ctx.GetFramePtr();
1848 const SymbolContext &sc = frame->GetSymbolContext(eSymbolContextFunction);
1849
1850 // Find candidate locations.
1851 std::vector<Address> candidates, within_function, outside_function;
1852 target->GetImages().FindAddressesForLine(target_sp, file, line, sc.function,
1853 within_function, outside_function);
1854
1855 // If possible, we try and stay within the current function. Within a
1856 // function, we accept multiple locations (optimized code may do this,
1857 // there's no solution here so we do the best we can). However if we're
1858 // trying to leave the function, we don't know how to pick the right
1859 // location, so if there's more than one then we bail.
1860 if (!within_function.empty())
1861 candidates = within_function;
1862 else if (outside_function.size() == 1 && can_leave_function)
1863 candidates = outside_function;
1864
1865 // Check if we got anything.
1866 if (candidates.empty()) {
1867 if (outside_function.empty()) {
1869 "Cannot locate an address for %s:%i.", file.GetFilename().AsCString(),
1870 line);
1871 } else if (outside_function.size() == 1) {
1873 "%s:%i is outside the current function.",
1874 file.GetFilename().AsCString(), line);
1875 } else {
1876 StreamString sstr;
1877 DumpAddressList(sstr, outside_function, target);
1879 "%s:%i has multiple candidate locations:\n%s",
1880 file.GetFilename().AsCString(), line, sstr.GetData());
1881 }
1882 }
1883
1884 // Accept the first location, warn about any others.
1885 Address dest = candidates[0];
1886 if (warnings && candidates.size() > 1) {
1887 StreamString sstr;
1888 sstr.Printf("%s:%i appears multiple times in this function, selecting the "
1889 "first location:\n",
1890 file.GetFilename().AsCString(), line);
1891 DumpAddressList(sstr, candidates, target);
1892 *warnings = std::string(sstr.GetString());
1893 }
1894
1895 if (!reg_ctx->SetPC(dest))
1896 return Status::FromErrorString("Cannot change PC to target address.");
1897
1898 return Status();
1899}
1900
1901bool Thread::DumpUsingFormat(Stream &strm, uint32_t frame_idx,
1902 const FormatEntity::Entry *format) {
1903 ExecutionContext exe_ctx(shared_from_this());
1904 Process *process = exe_ctx.GetProcessPtr();
1905 if (!process || !format)
1906 return false;
1907
1908 StackFrameSP frame_sp;
1909 SymbolContext frame_sc;
1910 if (frame_idx != LLDB_INVALID_FRAME_ID) {
1911 frame_sp = GetStackFrameAtIndex(frame_idx);
1912 if (frame_sp) {
1913 exe_ctx.SetFrameSP(frame_sp);
1914 frame_sc = frame_sp->GetSymbolContext(eSymbolContextEverything);
1915 }
1916 }
1917
1918 return FormatEntity::Formatter(frame_sp ? &frame_sc : nullptr, &exe_ctx,
1919 nullptr, false, false)
1920 .Format(*format, strm);
1921}
1922
1923void Thread::DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx,
1924 bool stop_format) {
1925 ExecutionContext exe_ctx(shared_from_this());
1926
1927 const FormatEntity::Entry *thread_format;
1928 FormatEntity::Entry format_entry;
1929 if (stop_format) {
1930 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadStopFormat();
1931 thread_format = &format_entry;
1932 } else {
1933 format_entry = exe_ctx.GetTargetRef().GetDebugger().GetThreadFormat();
1934 thread_format = &format_entry;
1935 }
1936
1937 assert(thread_format);
1938
1939 DumpUsingFormat(strm, frame_idx, thread_format);
1940}
1941
1943
1945
1947 if (m_reg_context_sp)
1948 return m_reg_context_sp->GetThreadPointer();
1949 return LLDB_INVALID_ADDRESS;
1950}
1951
1953 lldb::addr_t tls_file_addr) {
1954 // The default implementation is to ask the dynamic loader for it. This can
1955 // be overridden for specific platforms.
1956 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1957 if (loader)
1958 return loader->GetThreadLocalData(module, shared_from_this(),
1959 tls_file_addr);
1960 else
1961 return LLDB_INVALID_ADDRESS;
1962}
1963
1965 Process *process = GetProcess().get();
1966 if (process) {
1967 DynamicLoader *loader = GetProcess()->GetDynamicLoader();
1968 if (loader && loader->IsFullyInitialized() == false)
1969 return false;
1970
1971 SystemRuntime *runtime = process->GetSystemRuntime();
1972 if (runtime) {
1973 return runtime->SafeToCallFunctionsOnThisThread(shared_from_this());
1974 }
1975 }
1976 return true;
1977}
1978
1981 return GetStackFrameList()->GetStackFrameSPForStackFramePtr(stack_frame_ptr);
1982}
1983
1985 switch (reason) {
1986 case eStopReasonInvalid:
1987 return "invalid";
1988 case eStopReasonNone:
1989 return "none";
1990 case eStopReasonTrace:
1991 return "trace";
1993 return "breakpoint";
1995 return "watchpoint";
1996 case eStopReasonSignal:
1997 return "signal";
1999 return "exception";
2000 case eStopReasonExec:
2001 return "exec";
2002 case eStopReasonFork:
2003 return "fork";
2004 case eStopReasonVFork:
2005 return "vfork";
2007 return "vfork done";
2009 return "plan complete";
2011 return "thread exiting";
2013 return "instrumentation break";
2015 return "processor trace";
2017 return "async interrupt";
2019 return "history boundary";
2020 }
2021
2022 return "StopReason = " + std::to_string(reason);
2023}
2024
2026 switch (mode) {
2027 case eOnlyThisThread:
2028 return "only this thread";
2029 case eAllThreads:
2030 return "all threads";
2032 return "only during stepping";
2033 }
2034
2035 return "RunMode = " + std::to_string(mode);
2036}
2037
2038size_t Thread::GetStatus(Stream &strm, uint32_t start_frame,
2039 uint32_t num_frames, uint32_t num_frames_with_source,
2040 bool stop_format, bool show_hidden, bool only_stacks) {
2041
2042 ExecutionContext exe_ctx(shared_from_this());
2043 Target *target = exe_ctx.GetTargetPtr();
2044 if (!only_stacks) {
2045 Process *process = exe_ctx.GetProcessPtr();
2046 strm.Indent();
2047 bool is_selected = false;
2048 if (process) {
2049 if (process->GetThreadList().GetSelectedThread().get() == this)
2050 is_selected = true;
2051 }
2052 strm.Printf("%c ", is_selected ? '*' : ' ');
2053 if (target && target->GetDebugger().GetUseExternalEditor()) {
2054 StackFrameSP frame_sp = GetStackFrameAtIndex(start_frame);
2055 if (frame_sp) {
2056 SymbolContext frame_sc(
2057 frame_sp->GetSymbolContext(eSymbolContextLineEntry));
2058 if (frame_sc.line_entry.line != 0 && frame_sc.line_entry.GetFile()) {
2059 if (llvm::Error e = Host::OpenFileInExternalEditor(
2060 target->GetDebugger().GetExternalEditor(),
2061 frame_sc.line_entry.GetFile(), frame_sc.line_entry.line)) {
2062 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), std::move(e),
2063 "OpenFileInExternalEditor failed: {0}");
2064 }
2065 }
2066 }
2067 }
2068
2069 DumpUsingSettingsFormat(strm, start_frame, stop_format);
2070 }
2071
2072 size_t num_frames_shown = 0;
2073 if (num_frames > 0) {
2074 strm.IndentMore();
2075
2076 const bool show_frame_info = true;
2077 const bool show_frame_unique = only_stacks;
2078 bool show_selected_frame = false;
2079 if (num_frames == 1 || only_stacks ||
2080 (GetID() != GetProcess()->GetThreadList().GetSelectedThread()->GetID()))
2081 strm.IndentMore();
2082 else
2083 show_selected_frame = true;
2084
2085 bool show_hidden_marker =
2086 target && target->GetDebugger().GetMarkHiddenFrames();
2087 num_frames_shown = GetStackFrameList()->GetStatus(
2088 strm, start_frame, num_frames, show_frame_info, num_frames_with_source,
2089 show_frame_unique, show_hidden, show_hidden_marker,
2090 show_selected_frame);
2091 if (num_frames == 1)
2092 strm.IndentLess();
2093 strm.IndentLess();
2094 }
2095 return num_frames_shown;
2096}
2097
2099 bool print_json_thread, bool print_json_stopinfo) {
2100 const bool stop_format = false;
2101 DumpUsingSettingsFormat(strm, 0, stop_format);
2102 strm.Printf("\n");
2103
2105
2106 if (print_json_thread || print_json_stopinfo) {
2107 if (thread_info && print_json_thread) {
2108 thread_info->Dump(strm);
2109 strm.Printf("\n");
2110 }
2111
2112 if (print_json_stopinfo && m_stop_info_sp) {
2113 StructuredData::ObjectSP stop_info = m_stop_info_sp->GetExtendedInfo();
2114 if (stop_info) {
2115 stop_info->Dump(strm);
2116 strm.Printf("\n");
2117 }
2118 }
2119
2120 return true;
2121 }
2122
2123 if (thread_info) {
2124 StructuredData::ObjectSP activity =
2125 thread_info->GetObjectForDotSeparatedPath("activity");
2126 StructuredData::ObjectSP breadcrumb =
2127 thread_info->GetObjectForDotSeparatedPath("breadcrumb");
2128 StructuredData::ObjectSP messages =
2129 thread_info->GetObjectForDotSeparatedPath("trace_messages");
2130
2131 bool printed_activity = false;
2132 if (activity && activity->GetType() == eStructuredDataTypeDictionary) {
2133 StructuredData::Dictionary *activity_dict = activity->GetAsDictionary();
2134 StructuredData::ObjectSP id = activity_dict->GetValueForKey("id");
2135 StructuredData::ObjectSP name = activity_dict->GetValueForKey("name");
2136 if (name && name->GetType() == eStructuredDataTypeString && id &&
2137 id->GetType() == eStructuredDataTypeInteger) {
2138 strm.Format(" Activity '{0}', {1:x}\n",
2139 name->GetAsString()->GetValue(),
2140 id->GetUnsignedIntegerValue());
2141 }
2142 printed_activity = true;
2143 }
2144 bool printed_breadcrumb = false;
2145 if (breadcrumb && breadcrumb->GetType() == eStructuredDataTypeDictionary) {
2146 if (printed_activity)
2147 strm.Printf("\n");
2148 StructuredData::Dictionary *breadcrumb_dict =
2149 breadcrumb->GetAsDictionary();
2150 StructuredData::ObjectSP breadcrumb_text =
2151 breadcrumb_dict->GetValueForKey("name");
2152 if (breadcrumb_text &&
2153 breadcrumb_text->GetType() == eStructuredDataTypeString) {
2154 strm.Format(" Current Breadcrumb: {0}\n",
2155 breadcrumb_text->GetAsString()->GetValue());
2156 }
2157 printed_breadcrumb = true;
2158 }
2159 if (messages && messages->GetType() == eStructuredDataTypeArray) {
2160 if (printed_breadcrumb)
2161 strm.Printf("\n");
2162 StructuredData::Array *messages_array = messages->GetAsArray();
2163 const size_t msg_count = messages_array->GetSize();
2164 if (msg_count > 0) {
2165 strm.Printf(" %zu trace messages:\n", msg_count);
2166 for (size_t i = 0; i < msg_count; i++) {
2167 StructuredData::ObjectSP message = messages_array->GetItemAtIndex(i);
2168 if (message && message->GetType() == eStructuredDataTypeDictionary) {
2169 StructuredData::Dictionary *message_dict =
2170 message->GetAsDictionary();
2171 StructuredData::ObjectSP message_text =
2172 message_dict->GetValueForKey("message");
2173 if (message_text &&
2174 message_text->GetType() == eStructuredDataTypeString) {
2175 strm.Format(" {0}\n", message_text->GetAsString()->GetValue());
2176 }
2177 }
2178 }
2179 }
2180 }
2181 }
2182
2183 return true;
2184}
2185
2186size_t Thread::GetStackFrameStatus(Stream &strm, uint32_t first_frame,
2187 uint32_t num_frames, bool show_frame_info,
2188 uint32_t num_frames_with_source,
2189 bool show_hidden) {
2190 ExecutionContext exe_ctx(shared_from_this());
2191 Target *target = exe_ctx.GetTargetPtr();
2192 bool show_hidden_marker =
2193 target && target->GetDebugger().GetMarkHiddenFrames();
2194 return GetStackFrameList()->GetStatus(
2195 strm, first_frame, num_frames, show_frame_info, num_frames_with_source,
2196 /*show_unique*/ false, show_hidden, show_hidden_marker);
2197}
2198
2200 if (!m_unwinder_up)
2201 m_unwinder_up = std::make_unique<UnwindLLDB>(*this);
2202 return *m_unwinder_up;
2203}
2204
2210
2212 // If we are currently stopped at a breakpoint, always return that stopinfo
2213 // and don't reset it. This allows threads to maintain their breakpoint
2214 // stopinfo, such as when thread-stepping in multithreaded programs.
2215 if (m_stop_info_sp) {
2216 StopReason stop_reason = m_stop_info_sp->GetStopReason();
2217 if (stop_reason == lldb::eStopReasonBreakpoint) {
2218 uint64_t value = m_stop_info_sp->GetValue();
2220 if (reg_ctx_sp) {
2221 lldb::addr_t pc = reg_ctx_sp->GetPC();
2222 BreakpointSiteSP bp_site_sp =
2223 GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2224 if (bp_site_sp && static_cast<break_id_t>(value) == bp_site_sp->GetID())
2225 return true;
2226 }
2227 }
2228 }
2229 return false;
2230}
2231
2232Status Thread::StepIn(bool source_step,
2233 LazyBool step_in_avoids_code_without_debug_info,
2234 LazyBool step_out_avoids_code_without_debug_info)
2235
2236{
2237 Status error;
2238 Process *process = GetProcess().get();
2239 if (StateIsStoppedState(process->GetState(), true)) {
2240 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2241 ThreadPlanSP new_plan_sp;
2242 const lldb::RunMode run_mode = eOnlyThisThread;
2243 const bool abort_other_plans = false;
2244
2245 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2246 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2247 new_plan_sp = QueueThreadPlanForStepInRange(
2248 abort_other_plans, sc.line_entry, sc, nullptr, run_mode, error,
2249 step_in_avoids_code_without_debug_info,
2250 step_out_avoids_code_without_debug_info);
2251 } else {
2253 false, abort_other_plans, run_mode, error);
2254 }
2255
2256 new_plan_sp->SetIsControllingPlan(true);
2257 new_plan_sp->SetOkayToDiscard(false);
2258
2259 // Why do we need to set the current thread by ID here???
2261 error = process->Resume();
2262 } else {
2263 error = Status::FromErrorString("process not stopped");
2264 }
2265 return error;
2266}
2267
2268Status Thread::StepOver(bool source_step,
2269 LazyBool step_out_avoids_code_without_debug_info) {
2270 Status error;
2271 Process *process = GetProcess().get();
2272 if (StateIsStoppedState(process->GetState(), true)) {
2273 StackFrameSP frame_sp = GetStackFrameAtIndex(0);
2274 ThreadPlanSP new_plan_sp;
2275
2276 const lldb::RunMode run_mode = eOnlyThisThread;
2277 const bool abort_other_plans = false;
2278
2279 if (source_step && frame_sp && frame_sp->HasDebugInformation()) {
2280 SymbolContext sc(frame_sp->GetSymbolContext(eSymbolContextEverything));
2281 new_plan_sp = QueueThreadPlanForStepOverRange(
2282 abort_other_plans, sc.line_entry, sc, run_mode, error,
2283 step_out_avoids_code_without_debug_info);
2284 } else {
2286 true, abort_other_plans, run_mode, error);
2287 }
2288
2289 new_plan_sp->SetIsControllingPlan(true);
2290 new_plan_sp->SetOkayToDiscard(false);
2291
2292 // Why do we need to set the current thread by ID here???
2294 error = process->Resume();
2295 } else {
2296 error = Status::FromErrorString("process not stopped");
2297 }
2298 return error;
2299}
2300
2301Status Thread::StepOut(uint32_t frame_idx) {
2302 Status error;
2303 Process *process = GetProcess().get();
2304 if (StateIsStoppedState(process->GetState(), true)) {
2305 const bool first_instruction = false;
2306 const bool stop_other_threads = false;
2307 const bool abort_other_plans = false;
2308
2310 abort_other_plans, nullptr, first_instruction, stop_other_threads,
2311 eVoteYes, eVoteNoOpinion, frame_idx, error));
2312
2313 new_plan_sp->SetIsControllingPlan(true);
2314 new_plan_sp->SetOkayToDiscard(false);
2315
2316 // Why do we need to set the current thread by ID here???
2318 error = process->Resume();
2319 } else {
2320 error = Status::FromErrorString("process not stopped");
2321 }
2322 return error;
2323}
2324
2326 if (auto frame_sp = GetStackFrameAtIndex(0))
2327 if (auto recognized_frame = frame_sp->GetRecognizedFrame())
2328 if (auto e = recognized_frame->GetExceptionObject())
2329 return e;
2330
2331 // NOTE: Even though this behavior is generalized, only ObjC is actually
2332 // supported at the moment.
2333 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2334 if (auto e = runtime->GetExceptionObjectForThread(shared_from_this()))
2335 return e;
2336 }
2337
2338 return ValueObjectSP();
2339}
2340
2342 ValueObjectSP exception = GetCurrentException();
2343 if (!exception)
2344 return ThreadSP();
2345
2346 // NOTE: Even though this behavior is generalized, only ObjC is actually
2347 // supported at the moment.
2348 for (LanguageRuntime *runtime : GetProcess()->GetLanguageRuntimes()) {
2349 if (auto bt = runtime->GetBacktraceThreadFromException(exception))
2350 return bt;
2351 }
2352
2353 return ThreadSP();
2354}
2355
2357 ProcessSP process_sp = GetProcess();
2358 assert(process_sp);
2359 Target &target = process_sp->GetTarget();
2360 PlatformSP platform_sp = target.GetPlatform();
2361 assert(platform_sp);
2362 ArchSpec arch = target.GetArchitecture();
2363
2364 CompilerType type = platform_sp->GetSiginfoType(arch.GetTriple());
2365 if (!type.IsValid())
2367 &target, Status::FromErrorString("no siginfo_t for the platform"));
2368
2369 auto type_size_or_err = type.GetByteSize(nullptr);
2370 if (!type_size_or_err)
2372 &target, Status::FromError(type_size_or_err.takeError()));
2373
2374 llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>> data =
2375 GetSiginfo(*type_size_or_err);
2376 if (!data)
2377 return ValueObjectConstResult::Create(&target,
2378 Status::FromError(data.takeError()));
2379
2380 DataExtractor data_extractor{data.get()->getBufferStart(), data.get()->getBufferSize(),
2381 process_sp->GetByteOrder(), arch.GetAddressByteSize()};
2382 return ValueObjectConstResult::Create(&target, type, ConstString("__lldb_siginfo"), data_extractor);
2383}
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:369
#define LLDB_LOGF(log,...)
Definition Log.h:383
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:399
static void DumpAddressList(Stream &s, const std::vector< Address > &list, ExecutionContextScope *exe_scope)
Definition Thread.cpp:1831
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
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
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:4535
A plug-in interface definition class for debugging a process.
Definition Process.h:354
ThreadList & GetThreadList()
Definition Process.h:2269
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:2932
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 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:376
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
ObjectSP GetItemAtIndex(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
std::shared_ptr< Object > ObjectSP
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
LineEntry line_entry
The LineEntry for a given query.
static llvm::Expected< lldb::SyntheticFrameProviderSP > CreateInstance(lldb::StackFrameListSP input_frames, const ScriptedFrameProviderDescriptor &descriptor)
Try to create a SyntheticFrameProvider instance for the given input frames and descriptor.
A plug-in interface definition class for system runtimes.
virtual bool SafeToCallFunctionsOnThisThread(lldb::ThreadSP thread_sp)
Determine whether it is safe to run an expression on a given thread.
Debugger & GetDebugger() const
Definition Target.h:1223
const llvm::DenseMap< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3775
lldb::PlatformSP GetPlatform()
Definition Target.h:1677
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1140
const ArchSpec & GetArchitecture() const
Definition Target.h:1182
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:2341
std::optional< lldb::addr_t > GetPreviousFrameZeroPC()
Request the pc value the thread had when previously stopped.
Definition Thread.cpp:1691
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:1662
const uint32_t m_index_id
A unique 1 based index assigned to each thread for easy UI/command line access.
Definition Thread.h:1395
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:1406
virtual bool SafeToCallFunctions()
Check whether this thread is safe to run functions.
Definition Thread.cpp:1964
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:1946
virtual void DidStop()
Definition Thread.cpp:778
virtual bool RestoreRegisterStateFromCheckpoint(ThreadStateCheckpoint &saved_state)
Definition Thread.cpp:548
friend class ThreadPlan
Definition Thread.h:1328
bool SetupToStepOverBreakpointIfNeeded(lldb::RunDirection direction)
Definition Thread.cpp:637
uint32_t m_stop_info_stop_id
Definition Thread.h:1382
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:1403
static void SettingsInitialize()
Definition Thread.cpp:1942
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:1426
Status ReturnFromFrame(lldb::StackFrameSP frame_sp, lldb::ValueObjectSP return_value_sp, bool broadcast=false)
Definition Thread.cpp:1749
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:2098
static std::string RunModeAsString(lldb::RunMode mode)
Definition Thread.cpp:2025
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:1368
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:1952
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:2211
std::recursive_mutex m_state_mutex
Multithreaded protection for m_state.
Definition Thread.h:1401
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:1423
lldb::frame_list_id_t m_next_provider_id
Counter for assigning unique provider IDs.
Definition Thread.h:1463
virtual void ClearStackFrames()
Definition Thread.cpp:1695
ThreadPlan * GetCurrentPlan() const
Gets the plan which will execute next on the plan stack.
Definition Thread.cpp:1179
virtual Unwind & GetUnwinder()
Definition Thread.cpp:2199
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:1984
lldb::StackFrameListSP GetFrameListByIdentifier(lldb::frame_list_id_t id)
Get a frame list by its unique identifier.
Definition Thread.cpp:1595
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:1392
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:2186
std::string GetStopDescriptionRaw()
Definition Thread.cpp:613
void ClearScriptedFrameProvider()
Definition Thread.cpp:1681
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:2268
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:1438
std::unique_ptr< ThreadPlanStack > m_null_plan_stack_up
Definition Thread.h:1442
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:1611
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:1332
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:1381
std::mutex m_provider_frames_mutex
Per-host-thread stack of active provider input frames.
Definition Thread.h:1420
lldb::ProcessWP m_process_wp
The process that owns this thread.
Definition Thread.h:1380
void DumpUsingSettingsFormat(Stream &strm, uint32_t frame_idx, bool stop_format)
Definition Thread.cpp:1923
LazyBool m_override_should_notify
Definition Thread.h:1441
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:1734
virtual Status StepOut(uint32_t frame_idx=0)
Default implementation for stepping out.
Definition Thread.cpp:2301
virtual llvm::Expected< std::unique_ptr< llvm::MemoryBuffer > > GetSiginfo(size_t max_size) const
Definition Thread.h:1375
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:1399
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:1466
void CalculatePublicStopInfo()
Definition Thread.cpp:395
static void SettingsTerminate()
Definition Thread.cpp:1944
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:2356
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:1386
int m_resume_signal
The signal that should be used when continuing this thread.
Definition Thread.h:1428
virtual void DidResume()
Definition Thread.cpp:772
bool StopInfoIsUpToDate() const
Definition Thread.cpp:463
lldb::StackFrameSP GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr)
Definition Thread.cpp:1980
llvm::DenseMap< lldb::frame_list_id_t, lldb::SyntheticFrameProviderSP > m_frame_providers
Map from frame list ID to its frame provider.
Definition Thread.h:1450
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:2325
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:1730
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:1841
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:1901
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:1422
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:1468
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:1459
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:1433
lldb::StackFrameListSP GetStackFrameList()
Definition Thread.cpp:1491
bool m_should_run_before_public_stop
Definition Thread.h:1389
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:1455
lldb::StateType m_resume_state
This state is used to force a thread to be suspended from outside the ThreadPlan logic.
Definition Thread.h:1430
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:2232
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:2038
lldb::RegisterContextSP m_reg_context_sp
The register context for this thread's current register state.
Definition Thread.h:1397
lldb::StackFrameListSP m_unwinder_frames_sp
The unwinder frame list (ID 0).
Definition Thread.h:1405
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:332
bool StateIsStoppedState(lldb::StateType state, bool must_exist)
Check if a state represents a state where the process or thread is stopped.
Definition State.cpp:89
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...
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