Path: blob/main/contrib/llvm-project/lldb/source/Target/StackFrameList.cpp
39587 views
//===-- StackFrameList.cpp ------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Target/StackFrameList.h"9#include "lldb/Breakpoint/Breakpoint.h"10#include "lldb/Breakpoint/BreakpointLocation.h"11#include "lldb/Core/Debugger.h"12#include "lldb/Core/SourceManager.h"13#include "lldb/Host/StreamFile.h"14#include "lldb/Symbol/Block.h"15#include "lldb/Symbol/Function.h"16#include "lldb/Symbol/Symbol.h"17#include "lldb/Target/Process.h"18#include "lldb/Target/RegisterContext.h"19#include "lldb/Target/StackFrame.h"20#include "lldb/Target/StackFrameRecognizer.h"21#include "lldb/Target/StopInfo.h"22#include "lldb/Target/Target.h"23#include "lldb/Target/Thread.h"24#include "lldb/Target/Unwind.h"25#include "lldb/Utility/LLDBLog.h"26#include "lldb/Utility/Log.h"27#include "llvm/ADT/SmallPtrSet.h"2829#include <memory>3031//#define DEBUG_STACK_FRAMES 13233using namespace lldb;34using namespace lldb_private;3536// StackFrameList constructor37StackFrameList::StackFrameList(Thread &thread,38const lldb::StackFrameListSP &prev_frames_sp,39bool show_inline_frames)40: m_thread(thread), m_prev_frames_sp(prev_frames_sp), m_mutex(), m_frames(),41m_selected_frame_idx(), m_concrete_frames_fetched(0),42m_current_inlined_depth(UINT32_MAX),43m_current_inlined_pc(LLDB_INVALID_ADDRESS),44m_show_inlined_frames(show_inline_frames) {45if (prev_frames_sp) {46m_current_inlined_depth = prev_frames_sp->m_current_inlined_depth;47m_current_inlined_pc = prev_frames_sp->m_current_inlined_pc;48}49}5051StackFrameList::~StackFrameList() {52// Call clear since this takes a lock and clears the stack frame list in case53// another thread is currently using this stack frame list54Clear();55}5657void StackFrameList::CalculateCurrentInlinedDepth() {58uint32_t cur_inlined_depth = GetCurrentInlinedDepth();59if (cur_inlined_depth == UINT32_MAX) {60ResetCurrentInlinedDepth();61}62}6364uint32_t StackFrameList::GetCurrentInlinedDepth() {65if (m_show_inlined_frames && m_current_inlined_pc != LLDB_INVALID_ADDRESS) {66lldb::addr_t cur_pc = m_thread.GetRegisterContext()->GetPC();67if (cur_pc != m_current_inlined_pc) {68m_current_inlined_pc = LLDB_INVALID_ADDRESS;69m_current_inlined_depth = UINT32_MAX;70Log *log = GetLog(LLDBLog::Step);71if (log && log->GetVerbose())72LLDB_LOGF(73log,74"GetCurrentInlinedDepth: invalidating current inlined depth.\n");75}76return m_current_inlined_depth;77} else {78return UINT32_MAX;79}80}8182void StackFrameList::ResetCurrentInlinedDepth() {83if (!m_show_inlined_frames)84return;8586std::lock_guard<std::recursive_mutex> guard(m_mutex);8788GetFramesUpTo(0, DoNotAllowInterruption);89if (m_frames.empty())90return;91if (!m_frames[0]->IsInlined()) {92m_current_inlined_depth = UINT32_MAX;93m_current_inlined_pc = LLDB_INVALID_ADDRESS;94Log *log = GetLog(LLDBLog::Step);95if (log && log->GetVerbose())96LLDB_LOGF(97log,98"ResetCurrentInlinedDepth: Invalidating current inlined depth.\n");99return;100}101102// We only need to do something special about inlined blocks when we are103// at the beginning of an inlined function:104// FIXME: We probably also have to do something special if the PC is at105// the END of an inlined function, which coincides with the end of either106// its containing function or another inlined function.107108Block *block_ptr = m_frames[0]->GetFrameBlock();109if (!block_ptr)110return;111112Address pc_as_address;113lldb::addr_t curr_pc = m_thread.GetRegisterContext()->GetPC();114pc_as_address.SetLoadAddress(curr_pc, &(m_thread.GetProcess()->GetTarget()));115AddressRange containing_range;116if (!block_ptr->GetRangeContainingAddress(pc_as_address, containing_range) ||117pc_as_address != containing_range.GetBaseAddress())118return;119120// If we got here because of a breakpoint hit, then set the inlined depth121// depending on where the breakpoint was set. If we got here because of a122// crash, then set the inlined depth to the deepest most block. Otherwise,123// we stopped here naturally as the result of a step, so set ourselves in the124// containing frame of the whole set of nested inlines, so the user can then125// "virtually" step into the frames one by one, or next over the whole mess.126// Note: We don't have to handle being somewhere in the middle of the stack127// here, since ResetCurrentInlinedDepth doesn't get called if there is a128// valid inlined depth set.129StopInfoSP stop_info_sp = m_thread.GetStopInfo();130if (!stop_info_sp)131return;132switch (stop_info_sp->GetStopReason()) {133case eStopReasonWatchpoint:134case eStopReasonException:135case eStopReasonExec:136case eStopReasonFork:137case eStopReasonVFork:138case eStopReasonVForkDone:139case eStopReasonSignal:140// In all these cases we want to stop in the deepest frame.141m_current_inlined_pc = curr_pc;142m_current_inlined_depth = 0;143break;144case eStopReasonBreakpoint: {145// FIXME: Figure out what this break point is doing, and set the inline146// depth appropriately. Be careful to take into account breakpoints that147// implement step over prologue, since that should do the default148// calculation. For now, if the breakpoints corresponding to this hit are149// all internal, I set the stop location to the top of the inlined stack,150// since that will make things like stepping over prologues work right.151// But if there are any non-internal breakpoints I do to the bottom of the152// stack, since that was the old behavior.153uint32_t bp_site_id = stop_info_sp->GetValue();154BreakpointSiteSP bp_site_sp(155m_thread.GetProcess()->GetBreakpointSiteList().FindByID(bp_site_id));156bool all_internal = true;157if (bp_site_sp) {158uint32_t num_owners = bp_site_sp->GetNumberOfConstituents();159for (uint32_t i = 0; i < num_owners; i++) {160Breakpoint &bp_ref =161bp_site_sp->GetConstituentAtIndex(i)->GetBreakpoint();162if (!bp_ref.IsInternal()) {163all_internal = false;164}165}166}167if (!all_internal) {168m_current_inlined_pc = curr_pc;169m_current_inlined_depth = 0;170break;171}172}173[[fallthrough]];174default: {175// Otherwise, we should set ourselves at the container of the inlining, so176// that the user can descend into them. So first we check whether we have177// more than one inlined block sharing this PC:178int num_inlined_functions = 0;179180for (Block *container_ptr = block_ptr->GetInlinedParent();181container_ptr != nullptr;182container_ptr = container_ptr->GetInlinedParent()) {183if (!container_ptr->GetRangeContainingAddress(pc_as_address,184containing_range))185break;186if (pc_as_address != containing_range.GetBaseAddress())187break;188189num_inlined_functions++;190}191m_current_inlined_pc = curr_pc;192m_current_inlined_depth = num_inlined_functions + 1;193Log *log = GetLog(LLDBLog::Step);194if (log && log->GetVerbose())195LLDB_LOGF(log,196"ResetCurrentInlinedDepth: setting inlined "197"depth: %d 0x%" PRIx64 ".\n",198m_current_inlined_depth, curr_pc);199200break;201}202}203}204205bool StackFrameList::DecrementCurrentInlinedDepth() {206if (m_show_inlined_frames) {207uint32_t current_inlined_depth = GetCurrentInlinedDepth();208if (current_inlined_depth != UINT32_MAX) {209if (current_inlined_depth > 0) {210m_current_inlined_depth--;211return true;212}213}214}215return false;216}217218void StackFrameList::SetCurrentInlinedDepth(uint32_t new_depth) {219m_current_inlined_depth = new_depth;220if (new_depth == UINT32_MAX)221m_current_inlined_pc = LLDB_INVALID_ADDRESS;222else223m_current_inlined_pc = m_thread.GetRegisterContext()->GetPC();224}225226void StackFrameList::GetOnlyConcreteFramesUpTo(uint32_t end_idx,227Unwind &unwinder) {228assert(m_thread.IsValid() && "Expected valid thread");229assert(m_frames.size() <= end_idx && "Expected there to be frames to fill");230231if (end_idx < m_concrete_frames_fetched)232return;233234uint32_t num_frames = unwinder.GetFramesUpTo(end_idx);235if (num_frames <= end_idx + 1) {236// Done unwinding.237m_concrete_frames_fetched = UINT32_MAX;238}239240// Don't create the frames eagerly. Defer this work to GetFrameAtIndex,241// which can lazily query the unwinder to create frames.242m_frames.resize(num_frames);243}244245/// A sequence of calls that comprise some portion of a backtrace. Each frame246/// is represented as a pair of a callee (Function *) and an address within the247/// callee.248struct CallDescriptor {249Function *func;250CallEdge::AddrType address_type = CallEdge::AddrType::Call;251addr_t address = LLDB_INVALID_ADDRESS;252};253using CallSequence = std::vector<CallDescriptor>;254255/// Find the unique path through the call graph from \p begin (with return PC256/// \p return_pc) to \p end. On success this path is stored into \p path, and257/// on failure \p path is unchanged.258static void FindInterveningFrames(Function &begin, Function &end,259ExecutionContext &exe_ctx, Target &target,260addr_t return_pc, CallSequence &path,261ModuleList &images, Log *log) {262LLDB_LOG(log, "Finding frames between {0} and {1}, retn-pc={2:x}",263begin.GetDisplayName(), end.GetDisplayName(), return_pc);264265// Find a non-tail calling edge with the correct return PC.266if (log)267for (const auto &edge : begin.GetCallEdges())268LLDB_LOG(log, "FindInterveningFrames: found call with retn-PC = {0:x}",269edge->GetReturnPCAddress(begin, target));270CallEdge *first_edge = begin.GetCallEdgeForReturnAddress(return_pc, target);271if (!first_edge) {272LLDB_LOG(log, "No call edge outgoing from {0} with retn-PC == {1:x}",273begin.GetDisplayName(), return_pc);274return;275}276277// The first callee may not be resolved, or there may be nothing to fill in.278Function *first_callee = first_edge->GetCallee(images, exe_ctx);279if (!first_callee) {280LLDB_LOG(log, "Could not resolve callee");281return;282}283if (first_callee == &end) {284LLDB_LOG(log, "Not searching further, first callee is {0} (retn-PC: {1:x})",285end.GetDisplayName(), return_pc);286return;287}288289// Run DFS on the tail-calling edges out of the first callee to find \p end.290// Fully explore the set of functions reachable from the first edge via tail291// calls in order to detect ambiguous executions.292struct DFS {293CallSequence active_path = {};294CallSequence solution_path = {};295llvm::SmallPtrSet<Function *, 2> visited_nodes = {};296bool ambiguous = false;297Function *end;298ModuleList &images;299Target ⌖300ExecutionContext &context;301302DFS(Function *end, ModuleList &images, Target &target,303ExecutionContext &context)304: end(end), images(images), target(target), context(context) {}305306void search(CallEdge &first_edge, Function &first_callee,307CallSequence &path) {308dfs(first_edge, first_callee);309if (!ambiguous)310path = std::move(solution_path);311}312313void dfs(CallEdge ¤t_edge, Function &callee) {314// Found a path to the target function.315if (&callee == end) {316if (solution_path.empty())317solution_path = active_path;318else319ambiguous = true;320return;321}322323// Terminate the search if tail recursion is found, or more generally if324// there's more than one way to reach a target. This errs on the side of325// caution: it conservatively stops searching when some solutions are326// still possible to save time in the average case.327if (!visited_nodes.insert(&callee).second) {328ambiguous = true;329return;330}331332// Search the calls made from this callee.333active_path.push_back(CallDescriptor{&callee});334for (const auto &edge : callee.GetTailCallingEdges()) {335Function *next_callee = edge->GetCallee(images, context);336if (!next_callee)337continue;338339std::tie(active_path.back().address_type, active_path.back().address) =340edge->GetCallerAddress(callee, target);341342dfs(*edge, *next_callee);343if (ambiguous)344return;345}346active_path.pop_back();347}348};349350DFS(&end, images, target, exe_ctx).search(*first_edge, *first_callee, path);351}352353/// Given that \p next_frame will be appended to the frame list, synthesize354/// tail call frames between the current end of the list and \p next_frame.355/// If any frames are added, adjust the frame index of \p next_frame.356///357/// --------------358/// | ... | <- Completed frames.359/// --------------360/// | prev_frame |361/// --------------362/// | ... | <- Artificial frames inserted here.363/// --------------364/// | next_frame |365/// --------------366/// | ... | <- Not-yet-visited frames.367/// --------------368void StackFrameList::SynthesizeTailCallFrames(StackFrame &next_frame) {369// Cannot synthesize tail call frames when the stack is empty (there is no370// "previous" frame).371if (m_frames.empty())372return;373374TargetSP target_sp = next_frame.CalculateTarget();375if (!target_sp)376return;377378lldb::RegisterContextSP next_reg_ctx_sp = next_frame.GetRegisterContext();379if (!next_reg_ctx_sp)380return;381382Log *log = GetLog(LLDBLog::Step);383384StackFrame &prev_frame = *m_frames.back().get();385386// Find the functions prev_frame and next_frame are stopped in. The function387// objects are needed to search the lazy call graph for intervening frames.388Function *prev_func =389prev_frame.GetSymbolContext(eSymbolContextFunction).function;390if (!prev_func) {391LLDB_LOG(log, "SynthesizeTailCallFrames: can't find previous function");392return;393}394Function *next_func =395next_frame.GetSymbolContext(eSymbolContextFunction).function;396if (!next_func) {397LLDB_LOG(log, "SynthesizeTailCallFrames: can't find next function");398return;399}400401// Try to find the unique sequence of (tail) calls which led from next_frame402// to prev_frame.403CallSequence path;404addr_t return_pc = next_reg_ctx_sp->GetPC();405Target &target = *target_sp.get();406ModuleList &images = next_frame.CalculateTarget()->GetImages();407ExecutionContext exe_ctx(target_sp, /*get_process=*/true);408exe_ctx.SetFramePtr(&next_frame);409FindInterveningFrames(*next_func, *prev_func, exe_ctx, target, return_pc,410path, images, log);411412// Push synthetic tail call frames.413for (auto calleeInfo : llvm::reverse(path)) {414Function *callee = calleeInfo.func;415uint32_t frame_idx = m_frames.size();416uint32_t concrete_frame_idx = next_frame.GetConcreteFrameIndex();417addr_t cfa = LLDB_INVALID_ADDRESS;418bool cfa_is_valid = false;419addr_t pc = calleeInfo.address;420// If the callee address refers to the call instruction, we do not want to421// subtract 1 from this value.422const bool behaves_like_zeroth_frame =423calleeInfo.address_type == CallEdge::AddrType::Call;424SymbolContext sc;425callee->CalculateSymbolContext(&sc);426auto synth_frame = std::make_shared<StackFrame>(427m_thread.shared_from_this(), frame_idx, concrete_frame_idx, cfa,428cfa_is_valid, pc, StackFrame::Kind::Artificial,429behaves_like_zeroth_frame, &sc);430m_frames.push_back(synth_frame);431LLDB_LOG(log, "Pushed frame {0} at {1:x}", callee->GetDisplayName(), pc);432}433434// If any frames were created, adjust next_frame's index.435if (!path.empty())436next_frame.SetFrameIndex(m_frames.size());437}438439bool StackFrameList::GetFramesUpTo(uint32_t end_idx,440InterruptionControl allow_interrupt) {441// Do not fetch frames for an invalid thread.442bool was_interrupted = false;443if (!m_thread.IsValid())444return false;445446// We've already gotten more frames than asked for, or we've already finished447// unwinding, return.448if (m_frames.size() > end_idx || GetAllFramesFetched())449return false;450451Unwind &unwinder = m_thread.GetUnwinder();452453if (!m_show_inlined_frames) {454GetOnlyConcreteFramesUpTo(end_idx, unwinder);455return false;456}457458#if defined(DEBUG_STACK_FRAMES)459StreamFile s(stdout, false);460#endif461// If we are hiding some frames from the outside world, we need to add462// those onto the total count of frames to fetch. However, we don't need463// to do that if end_idx is 0 since in that case we always get the first464// concrete frame and all the inlined frames below it... And of course, if465// end_idx is UINT32_MAX that means get all, so just do that...466467uint32_t inlined_depth = 0;468if (end_idx > 0 && end_idx != UINT32_MAX) {469inlined_depth = GetCurrentInlinedDepth();470if (inlined_depth != UINT32_MAX) {471if (end_idx > 0)472end_idx += inlined_depth;473}474}475476StackFrameSP unwind_frame_sp;477Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();478do {479uint32_t idx = m_concrete_frames_fetched++;480lldb::addr_t pc = LLDB_INVALID_ADDRESS;481lldb::addr_t cfa = LLDB_INVALID_ADDRESS;482bool behaves_like_zeroth_frame = (idx == 0);483if (idx == 0) {484// We might have already created frame zero, only create it if we need485// to.486if (m_frames.empty()) {487RegisterContextSP reg_ctx_sp(m_thread.GetRegisterContext());488489if (reg_ctx_sp) {490const bool success = unwinder.GetFrameInfoAtIndex(491idx, cfa, pc, behaves_like_zeroth_frame);492// There shouldn't be any way not to get the frame info for frame493// 0. But if the unwinder can't make one, lets make one by hand494// with the SP as the CFA and see if that gets any further.495if (!success) {496cfa = reg_ctx_sp->GetSP();497pc = reg_ctx_sp->GetPC();498}499500unwind_frame_sp = std::make_shared<StackFrame>(501m_thread.shared_from_this(), m_frames.size(), idx, reg_ctx_sp,502cfa, pc, behaves_like_zeroth_frame, nullptr);503m_frames.push_back(unwind_frame_sp);504}505} else {506unwind_frame_sp = m_frames.front();507cfa = unwind_frame_sp->m_id.GetCallFrameAddress();508}509} else {510// Check for interruption when building the frames.511// Do the check in idx > 0 so that we'll always create a 0th frame.512if (allow_interrupt513&& INTERRUPT_REQUESTED(dbg, "Interrupted having fetched {0} frames",514m_frames.size())) {515was_interrupted = true;516break;517}518519const bool success =520unwinder.GetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame);521if (!success) {522// We've gotten to the end of the stack.523SetAllFramesFetched();524break;525}526const bool cfa_is_valid = true;527unwind_frame_sp = std::make_shared<StackFrame>(528m_thread.shared_from_this(), m_frames.size(), idx, cfa, cfa_is_valid,529pc, StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);530531// Create synthetic tail call frames between the previous frame and the532// newly-found frame. The new frame's index may change after this call,533// although its concrete index will stay the same.534SynthesizeTailCallFrames(*unwind_frame_sp.get());535536m_frames.push_back(unwind_frame_sp);537}538539assert(unwind_frame_sp);540SymbolContext unwind_sc = unwind_frame_sp->GetSymbolContext(541eSymbolContextBlock | eSymbolContextFunction);542Block *unwind_block = unwind_sc.block;543TargetSP target_sp = m_thread.CalculateTarget();544if (unwind_block) {545Address curr_frame_address(546unwind_frame_sp->GetFrameCodeAddressForSymbolication());547548SymbolContext next_frame_sc;549Address next_frame_address;550551while (unwind_sc.GetParentOfInlinedScope(552curr_frame_address, next_frame_sc, next_frame_address)) {553next_frame_sc.line_entry.ApplyFileMappings(target_sp);554behaves_like_zeroth_frame = false;555StackFrameSP frame_sp(new StackFrame(556m_thread.shared_from_this(), m_frames.size(), idx,557unwind_frame_sp->GetRegisterContextSP(), cfa, next_frame_address,558behaves_like_zeroth_frame, &next_frame_sc));559560m_frames.push_back(frame_sp);561unwind_sc = next_frame_sc;562curr_frame_address = next_frame_address;563}564}565} while (m_frames.size() - 1 < end_idx);566567// Don't try to merge till you've calculated all the frames in this stack.568if (GetAllFramesFetched() && m_prev_frames_sp) {569StackFrameList *prev_frames = m_prev_frames_sp.get();570StackFrameList *curr_frames = this;571572#if defined(DEBUG_STACK_FRAMES)573s.PutCString("\nprev_frames:\n");574prev_frames->Dump(&s);575s.PutCString("\ncurr_frames:\n");576curr_frames->Dump(&s);577s.EOL();578#endif579size_t curr_frame_num, prev_frame_num;580581for (curr_frame_num = curr_frames->m_frames.size(),582prev_frame_num = prev_frames->m_frames.size();583curr_frame_num > 0 && prev_frame_num > 0;584--curr_frame_num, --prev_frame_num) {585const size_t curr_frame_idx = curr_frame_num - 1;586const size_t prev_frame_idx = prev_frame_num - 1;587StackFrameSP curr_frame_sp(curr_frames->m_frames[curr_frame_idx]);588StackFrameSP prev_frame_sp(prev_frames->m_frames[prev_frame_idx]);589590#if defined(DEBUG_STACK_FRAMES)591s.Printf("\n\nCurr frame #%u ", curr_frame_idx);592if (curr_frame_sp)593curr_frame_sp->Dump(&s, true, false);594else595s.PutCString("NULL");596s.Printf("\nPrev frame #%u ", prev_frame_idx);597if (prev_frame_sp)598prev_frame_sp->Dump(&s, true, false);599else600s.PutCString("NULL");601#endif602603StackFrame *curr_frame = curr_frame_sp.get();604StackFrame *prev_frame = prev_frame_sp.get();605606if (curr_frame == nullptr || prev_frame == nullptr)607break;608609// Check the stack ID to make sure they are equal.610if (curr_frame->GetStackID() != prev_frame->GetStackID())611break;612613prev_frame->UpdatePreviousFrameFromCurrentFrame(*curr_frame);614// Now copy the fixed up previous frame into the current frames so the615// pointer doesn't change.616m_frames[curr_frame_idx] = prev_frame_sp;617618#if defined(DEBUG_STACK_FRAMES)619s.Printf("\n Copying previous frame to current frame");620#endif621}622// We are done with the old stack frame list, we can release it now.623m_prev_frames_sp.reset();624}625626#if defined(DEBUG_STACK_FRAMES)627s.PutCString("\n\nNew frames:\n");628Dump(&s);629s.EOL();630#endif631// Don't report interrupted if we happen to have gotten all the frames:632if (!GetAllFramesFetched())633return was_interrupted;634return false;635}636637uint32_t StackFrameList::GetNumFrames(bool can_create) {638std::lock_guard<std::recursive_mutex> guard(m_mutex);639640if (can_create) {641// Don't allow interrupt or we might not return the correct count642GetFramesUpTo(UINT32_MAX, DoNotAllowInterruption);643}644return GetVisibleStackFrameIndex(m_frames.size());645}646647void StackFrameList::Dump(Stream *s) {648if (s == nullptr)649return;650651std::lock_guard<std::recursive_mutex> guard(m_mutex);652653const_iterator pos, begin = m_frames.begin(), end = m_frames.end();654for (pos = begin; pos != end; ++pos) {655StackFrame *frame = (*pos).get();656s->Printf("%p: ", static_cast<void *>(frame));657if (frame) {658frame->GetStackID().Dump(s);659frame->DumpUsingSettingsFormat(s);660} else661s->Printf("frame #%u", (uint32_t)std::distance(begin, pos));662s->EOL();663}664s->EOL();665}666667StackFrameSP StackFrameList::GetFrameAtIndex(uint32_t idx) {668StackFrameSP frame_sp;669std::lock_guard<std::recursive_mutex> guard(m_mutex);670uint32_t original_idx = idx;671672uint32_t inlined_depth = GetCurrentInlinedDepth();673if (inlined_depth != UINT32_MAX)674idx += inlined_depth;675676if (idx < m_frames.size())677frame_sp = m_frames[idx];678679if (frame_sp)680return frame_sp;681682// GetFramesUpTo will fill m_frames with as many frames as you asked for, if683// there are that many. If there weren't then you asked for too many frames.684// GetFramesUpTo returns true if interrupted:685if (GetFramesUpTo(idx)) {686Log *log = GetLog(LLDBLog::Thread);687LLDB_LOG(log, "GetFrameAtIndex was interrupted");688return {};689}690691if (idx < m_frames.size()) {692if (m_show_inlined_frames) {693// When inline frames are enabled we actually create all the frames in694// GetFramesUpTo.695frame_sp = m_frames[idx];696} else {697addr_t pc, cfa;698bool behaves_like_zeroth_frame = (idx == 0);699if (m_thread.GetUnwinder().GetFrameInfoAtIndex(700idx, cfa, pc, behaves_like_zeroth_frame)) {701const bool cfa_is_valid = true;702frame_sp = std::make_shared<StackFrame>(703m_thread.shared_from_this(), idx, idx, cfa, cfa_is_valid, pc,704StackFrame::Kind::Regular, behaves_like_zeroth_frame, nullptr);705706Function *function =707frame_sp->GetSymbolContext(eSymbolContextFunction).function;708if (function) {709// When we aren't showing inline functions we always use the top710// most function block as the scope.711frame_sp->SetSymbolContextScope(&function->GetBlock(false));712} else {713// Set the symbol scope from the symbol regardless if it is nullptr714// or valid.715frame_sp->SetSymbolContextScope(716frame_sp->GetSymbolContext(eSymbolContextSymbol).symbol);717}718SetFrameAtIndex(idx, frame_sp);719}720}721} else if (original_idx == 0) {722// There should ALWAYS be a frame at index 0. If something went wrong with723// the CurrentInlinedDepth such that there weren't as many frames as we724// thought taking that into account, then reset the current inlined depth725// and return the real zeroth frame.726if (m_frames.empty()) {727// Why do we have a thread with zero frames, that should not ever728// happen...729assert(!m_thread.IsValid() && "A valid thread has no frames.");730} else {731ResetCurrentInlinedDepth();732frame_sp = m_frames[original_idx];733}734}735736return frame_sp;737}738739StackFrameSP740StackFrameList::GetFrameWithConcreteFrameIndex(uint32_t unwind_idx) {741// First try assuming the unwind index is the same as the frame index. The742// unwind index is always greater than or equal to the frame index, so it is743// a good place to start. If we have inlined frames we might have 5 concrete744// frames (frame unwind indexes go from 0-4), but we might have 15 frames745// after we make all the inlined frames. Most of the time the unwind frame746// index (or the concrete frame index) is the same as the frame index.747uint32_t frame_idx = unwind_idx;748StackFrameSP frame_sp(GetFrameAtIndex(frame_idx));749while (frame_sp) {750if (frame_sp->GetFrameIndex() == unwind_idx)751break;752frame_sp = GetFrameAtIndex(++frame_idx);753}754return frame_sp;755}756757static bool CompareStackID(const StackFrameSP &stack_sp,758const StackID &stack_id) {759return stack_sp->GetStackID() < stack_id;760}761762StackFrameSP StackFrameList::GetFrameWithStackID(const StackID &stack_id) {763StackFrameSP frame_sp;764765if (stack_id.IsValid()) {766std::lock_guard<std::recursive_mutex> guard(m_mutex);767uint32_t frame_idx = 0;768// Do a binary search in case the stack frame is already in our cache769collection::const_iterator begin = m_frames.begin();770collection::const_iterator end = m_frames.end();771if (begin != end) {772collection::const_iterator pos =773std::lower_bound(begin, end, stack_id, CompareStackID);774if (pos != end) {775if ((*pos)->GetStackID() == stack_id)776return *pos;777}778}779do {780frame_sp = GetFrameAtIndex(frame_idx);781if (frame_sp && frame_sp->GetStackID() == stack_id)782break;783frame_idx++;784} while (frame_sp);785}786return frame_sp;787}788789bool StackFrameList::SetFrameAtIndex(uint32_t idx, StackFrameSP &frame_sp) {790if (idx >= m_frames.size())791m_frames.resize(idx + 1);792// Make sure allocation succeeded by checking bounds again793if (idx < m_frames.size()) {794m_frames[idx] = frame_sp;795return true;796}797return false; // resize failed, out of memory?798}799800void StackFrameList::SelectMostRelevantFrame() {801// Don't call into the frame recognizers on the private state thread as802// they can cause code to run in the target, and that can cause deadlocks803// when fetching stop events for the expression.804if (m_thread.GetProcess()->CurrentThreadIsPrivateStateThread())805return;806807Log *log = GetLog(LLDBLog::Thread);808809// Only the top frame should be recognized.810StackFrameSP frame_sp = GetFrameAtIndex(0);811if (!frame_sp) {812LLDB_LOG(log, "Failed to construct Frame #0");813return;814}815816RecognizedStackFrameSP recognized_frame_sp = frame_sp->GetRecognizedFrame();817818if (!recognized_frame_sp) {819LLDB_LOG(log, "Frame #0 not recognized");820return;821}822823if (StackFrameSP most_relevant_frame_sp =824recognized_frame_sp->GetMostRelevantFrame()) {825LLDB_LOG(log, "Found most relevant frame at index {0}",826most_relevant_frame_sp->GetFrameIndex());827SetSelectedFrame(most_relevant_frame_sp.get());828} else {829LLDB_LOG(log, "No relevant frame!");830}831}832833uint32_t StackFrameList::GetSelectedFrameIndex(834SelectMostRelevant select_most_relevant) {835std::lock_guard<std::recursive_mutex> guard(m_mutex);836if (!m_selected_frame_idx && select_most_relevant)837SelectMostRelevantFrame();838if (!m_selected_frame_idx) {839// If we aren't selecting the most relevant frame, and the selected frame840// isn't set, then don't force a selection here, just return 0.841if (!select_most_relevant)842return 0;843m_selected_frame_idx = 0;844}845return *m_selected_frame_idx;846}847848uint32_t StackFrameList::SetSelectedFrame(lldb_private::StackFrame *frame) {849std::lock_guard<std::recursive_mutex> guard(m_mutex);850const_iterator pos;851const_iterator begin = m_frames.begin();852const_iterator end = m_frames.end();853m_selected_frame_idx = 0;854855for (pos = begin; pos != end; ++pos) {856if (pos->get() == frame) {857m_selected_frame_idx = std::distance(begin, pos);858uint32_t inlined_depth = GetCurrentInlinedDepth();859if (inlined_depth != UINT32_MAX)860m_selected_frame_idx = *m_selected_frame_idx - inlined_depth;861break;862}863}864865SetDefaultFileAndLineToSelectedFrame();866return *m_selected_frame_idx;867}868869bool StackFrameList::SetSelectedFrameByIndex(uint32_t idx) {870std::lock_guard<std::recursive_mutex> guard(m_mutex);871StackFrameSP frame_sp(GetFrameAtIndex(idx));872if (frame_sp) {873SetSelectedFrame(frame_sp.get());874return true;875} else876return false;877}878879void StackFrameList::SetDefaultFileAndLineToSelectedFrame() {880if (m_thread.GetID() ==881m_thread.GetProcess()->GetThreadList().GetSelectedThread()->GetID()) {882StackFrameSP frame_sp(883GetFrameAtIndex(GetSelectedFrameIndex(DoNoSelectMostRelevantFrame)));884if (frame_sp) {885SymbolContext sc = frame_sp->GetSymbolContext(eSymbolContextLineEntry);886if (sc.line_entry.GetFile())887m_thread.CalculateTarget()->GetSourceManager().SetDefaultFileAndLine(888sc.line_entry.GetFile(), sc.line_entry.line);889}890}891}892893// The thread has been run, reset the number stack frames to zero so we can894// determine how many frames we have lazily.895// Note, we don't actually re-use StackFrameLists, we always make a new896// StackFrameList every time we stop, and then copy frame information frame897// by frame from the old to the new StackFrameList. So the comment above,898// does not describe how StackFrameLists are currently used.899// Clear is currently only used to clear the list in the destructor.900void StackFrameList::Clear() {901std::lock_guard<std::recursive_mutex> guard(m_mutex);902m_frames.clear();903m_concrete_frames_fetched = 0;904m_selected_frame_idx.reset();905}906907lldb::StackFrameSP908StackFrameList::GetStackFrameSPForStackFramePtr(StackFrame *stack_frame_ptr) {909const_iterator pos;910const_iterator begin = m_frames.begin();911const_iterator end = m_frames.end();912lldb::StackFrameSP ret_sp;913914for (pos = begin; pos != end; ++pos) {915if (pos->get() == stack_frame_ptr) {916ret_sp = (*pos);917break;918}919}920return ret_sp;921}922923size_t StackFrameList::GetStatus(Stream &strm, uint32_t first_frame,924uint32_t num_frames, bool show_frame_info,925uint32_t num_frames_with_source,926bool show_unique,927const char *selected_frame_marker) {928size_t num_frames_displayed = 0;929930if (num_frames == 0)931return 0;932933StackFrameSP frame_sp;934uint32_t frame_idx = 0;935uint32_t last_frame;936937// Don't let the last frame wrap around...938if (num_frames == UINT32_MAX)939last_frame = UINT32_MAX;940else941last_frame = first_frame + num_frames;942943StackFrameSP selected_frame_sp =944m_thread.GetSelectedFrame(DoNoSelectMostRelevantFrame);945const char *unselected_marker = nullptr;946std::string buffer;947if (selected_frame_marker) {948size_t len = strlen(selected_frame_marker);949buffer.insert(buffer.begin(), len, ' ');950unselected_marker = buffer.c_str();951}952const char *marker = nullptr;953954for (frame_idx = first_frame; frame_idx < last_frame; ++frame_idx) {955frame_sp = GetFrameAtIndex(frame_idx);956if (!frame_sp)957break;958959if (selected_frame_marker != nullptr) {960if (frame_sp == selected_frame_sp)961marker = selected_frame_marker;962else963marker = unselected_marker;964}965// Check for interruption here. If we're fetching arguments, this loop966// can go slowly:967Debugger &dbg = m_thread.GetProcess()->GetTarget().GetDebugger();968if (INTERRUPT_REQUESTED(969dbg, "Interrupted dumping stack for thread {0:x} with {1} shown.",970m_thread.GetID(), num_frames_displayed))971break;972973974if (!frame_sp->GetStatus(strm, show_frame_info,975num_frames_with_source > (first_frame - frame_idx),976show_unique, marker))977break;978++num_frames_displayed;979}980981strm.IndentLess();982return num_frames_displayed;983}984985986