Path: blob/main/contrib/llvm-project/lldb/source/Target/RegisterContextUnwind.cpp
96333 views
//===-- RegisterContextUnwind.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/RegisterContextUnwind.h"9#include "lldb/Core/Address.h"10#include "lldb/Core/AddressRange.h"11#include "lldb/Core/Module.h"12#include "lldb/Core/Value.h"13#include "lldb/Expression/DWARFExpressionList.h"14#include "lldb/Symbol/ArmUnwindInfo.h"15#include "lldb/Symbol/CallFrameInfo.h"16#include "lldb/Symbol/DWARFCallFrameInfo.h"17#include "lldb/Symbol/FuncUnwinders.h"18#include "lldb/Symbol/Function.h"19#include "lldb/Symbol/ObjectFile.h"20#include "lldb/Symbol/Symbol.h"21#include "lldb/Symbol/SymbolContext.h"22#include "lldb/Symbol/SymbolFile.h"23#include "lldb/Target/ABI.h"24#include "lldb/Target/DynamicLoader.h"25#include "lldb/Target/ExecutionContext.h"26#include "lldb/Target/LanguageRuntime.h"27#include "lldb/Target/Platform.h"28#include "lldb/Target/Process.h"29#include "lldb/Target/SectionLoadList.h"30#include "lldb/Target/StackFrame.h"31#include "lldb/Target/Target.h"32#include "lldb/Target/Thread.h"33#include "lldb/Utility/DataBufferHeap.h"34#include "lldb/Utility/LLDBLog.h"35#include "lldb/Utility/Log.h"36#include "lldb/Utility/RegisterValue.h"37#include "lldb/Utility/VASPrintf.h"38#include "lldb/lldb-private.h"3940#include <cassert>41#include <memory>4243using namespace lldb;44using namespace lldb_private;4546static ConstString GetSymbolOrFunctionName(const SymbolContext &sym_ctx) {47if (sym_ctx.symbol)48return sym_ctx.symbol->GetName();49else if (sym_ctx.function)50return sym_ctx.function->GetName();51return ConstString();52}5354RegisterContextUnwind::RegisterContextUnwind(Thread &thread,55const SharedPtr &next_frame,56SymbolContext &sym_ctx,57uint32_t frame_number,58UnwindLLDB &unwind_lldb)59: RegisterContext(thread, frame_number), m_thread(thread),60m_fast_unwind_plan_sp(), m_full_unwind_plan_sp(),61m_fallback_unwind_plan_sp(), m_all_registers_available(false),62m_frame_type(-1), m_cfa(LLDB_INVALID_ADDRESS),63m_afa(LLDB_INVALID_ADDRESS), m_start_pc(), m_current_pc(),64m_current_offset(0), m_current_offset_backed_up_one(0),65m_behaves_like_zeroth_frame(false), m_sym_ctx(sym_ctx),66m_sym_ctx_valid(false), m_frame_number(frame_number), m_registers(),67m_parent_unwind(unwind_lldb) {68m_sym_ctx.Clear(false);69m_sym_ctx_valid = false;7071if (IsFrameZero()) {72InitializeZerothFrame();73} else {74InitializeNonZerothFrame();75}7677// This same code exists over in the GetFullUnwindPlanForFrame() but it may78// not have been executed yet79if (IsFrameZero() || next_frame->m_frame_type == eTrapHandlerFrame ||80next_frame->m_frame_type == eDebuggerFrame) {81m_all_registers_available = true;82}83}8485bool RegisterContextUnwind::IsUnwindPlanValidForCurrentPC(86lldb::UnwindPlanSP unwind_plan_sp) {87if (!unwind_plan_sp)88return false;8990// check if m_current_pc is valid91if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {92// yes - current offset can be used as is93return true;94}9596// if m_current_offset <= 0, we've got nothing else to try97if (m_current_offset <= 0)98return false;99100// check pc - 1 to see if it's valid101Address pc_minus_one(m_current_pc);102pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);103if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one)) {104return true;105}106107return false;108}109110// Initialize a RegisterContextUnwind which is the first frame of a stack -- the111// zeroth frame or currently executing frame.112113void RegisterContextUnwind::InitializeZerothFrame() {114Log *log = GetLog(LLDBLog::Unwind);115ExecutionContext exe_ctx(m_thread.shared_from_this());116RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();117118if (reg_ctx_sp.get() == nullptr) {119m_frame_type = eNotAValidFrame;120UnwindLogMsg("frame does not have a register context");121return;122}123124addr_t current_pc = reg_ctx_sp->GetPC();125126if (current_pc == LLDB_INVALID_ADDRESS) {127m_frame_type = eNotAValidFrame;128UnwindLogMsg("frame does not have a pc");129return;130}131132Process *process = exe_ctx.GetProcessPtr();133134// Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs135// this will strip bit zero in case we read a PC from memory or from the LR.136// (which would be a no-op in frame 0 where we get it from the register set,137// but still a good idea to make the call here for other ABIs that may138// exist.)139if (ABISP abi_sp = process->GetABI())140current_pc = abi_sp->FixCodeAddress(current_pc);141142UnwindPlanSP lang_runtime_plan_sp = LanguageRuntime::GetRuntimeUnwindPlan(143m_thread, this, m_behaves_like_zeroth_frame);144if (lang_runtime_plan_sp.get()) {145UnwindLogMsg("This is an async frame");146}147148// Initialize m_current_pc, an Address object, based on current_pc, an149// addr_t.150m_current_pc.SetLoadAddress(current_pc, &process->GetTarget());151152// If we don't have a Module for some reason, we're not going to find153// symbol/function information - just stick in some reasonable defaults and154// hope we can unwind past this frame.155ModuleSP pc_module_sp(m_current_pc.GetModule());156if (!m_current_pc.IsValid() || !pc_module_sp) {157UnwindLogMsg("using architectural default unwind method");158}159160AddressRange addr_range;161m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);162163if (m_sym_ctx.symbol) {164UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'",165current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));166} else if (m_sym_ctx.function) {167UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'",168current_pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));169} else {170UnwindLogMsg("with pc value of 0x%" PRIx64171", no symbol/function name is known.",172current_pc);173}174175if (IsTrapHandlerSymbol(process, m_sym_ctx)) {176m_frame_type = eTrapHandlerFrame;177} else {178// FIXME: Detect eDebuggerFrame here.179m_frame_type = eNormalFrame;180}181182// If we were able to find a symbol/function, set addr_range to the bounds of183// that symbol/function. else treat the current pc value as the start_pc and184// record no offset.185if (addr_range.GetBaseAddress().IsValid()) {186m_start_pc = addr_range.GetBaseAddress();187if (m_current_pc.GetSection() == m_start_pc.GetSection()) {188m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();189} else if (m_current_pc.GetModule() == m_start_pc.GetModule()) {190// This means that whatever symbol we kicked up isn't really correct ---191// we should not cross section boundaries ... We really should NULL out192// the function/symbol in this case unless there is a bad assumption here193// due to inlined functions?194m_current_offset =195m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();196}197m_current_offset_backed_up_one = m_current_offset;198} else {199m_start_pc = m_current_pc;200m_current_offset = -1;201m_current_offset_backed_up_one = -1;202}203204// We've set m_frame_type and m_sym_ctx before these calls.205206m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();207m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();208209UnwindPlan::RowSP active_row;210lldb::RegisterKind row_register_kind = eRegisterKindGeneric;211212// If we have LanguageRuntime UnwindPlan for this unwind, use those213// rules to find the caller frame instead of the function's normal214// UnwindPlans. The full unwind plan for this frame will be215// the LanguageRuntime-provided unwind plan, and there will not be a216// fast unwind plan.217if (lang_runtime_plan_sp.get()) {218active_row =219lang_runtime_plan_sp->GetRowForFunctionOffset(m_current_offset);220row_register_kind = lang_runtime_plan_sp->GetRegisterKind();221if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(),222m_cfa)) {223UnwindLogMsg("Cannot set cfa");224} else {225m_full_unwind_plan_sp = lang_runtime_plan_sp;226if (log) {227StreamString active_row_strm;228active_row->Dump(active_row_strm, lang_runtime_plan_sp.get(), &m_thread,229m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));230UnwindLogMsg("async active row: %s", active_row_strm.GetData());231}232UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);233UnwindLogMsg(234"initialized async frame current pc is 0x%" PRIx64235" cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,236(uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),237(uint64_t)m_cfa, (uint64_t)m_afa);238239return;240}241}242243if (m_full_unwind_plan_sp &&244m_full_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {245active_row =246m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);247row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();248if (active_row.get() && log) {249StreamString active_row_strm;250active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread,251m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));252UnwindLogMsg("%s", active_row_strm.GetData());253}254}255256if (!active_row.get()) {257UnwindLogMsg("could not find an unwindplan row for this frame's pc");258m_frame_type = eNotAValidFrame;259return;260}261262if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {263// Try the fall back unwind plan since the264// full unwind plan failed.265FuncUnwindersSP func_unwinders_sp;266UnwindPlanSP call_site_unwind_plan;267bool cfa_status = false;268269if (m_sym_ctx_valid) {270func_unwinders_sp =271pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(272m_current_pc, m_sym_ctx);273}274275if (func_unwinders_sp.get() != nullptr)276call_site_unwind_plan = func_unwinders_sp->GetUnwindPlanAtCallSite(277process->GetTarget(), m_thread);278279if (call_site_unwind_plan.get() != nullptr) {280m_fallback_unwind_plan_sp = call_site_unwind_plan;281if (TryFallbackUnwindPlan())282cfa_status = true;283}284if (!cfa_status) {285UnwindLogMsg("could not read CFA value for first frame.");286m_frame_type = eNotAValidFrame;287return;288}289} else290ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);291292if (m_cfa == LLDB_INVALID_ADDRESS && m_afa == LLDB_INVALID_ADDRESS) {293UnwindLogMsg(294"could not read CFA or AFA values for first frame, not valid.");295m_frame_type = eNotAValidFrame;296return;297}298299UnwindLogMsg("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64300" afa is 0x%" PRIx64 " using %s UnwindPlan",301(uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),302(uint64_t)m_cfa,303(uint64_t)m_afa,304m_full_unwind_plan_sp->GetSourceName().GetCString());305}306307// Initialize a RegisterContextUnwind for the non-zeroth frame -- rely on the308// RegisterContextUnwind "below" it to provide things like its current pc value.309310void RegisterContextUnwind::InitializeNonZerothFrame() {311Log *log = GetLog(LLDBLog::Unwind);312if (IsFrameZero()) {313m_frame_type = eNotAValidFrame;314UnwindLogMsg("non-zeroth frame tests positive for IsFrameZero -- that "315"shouldn't happen.");316return;317}318319if (!GetNextFrame().get() || !GetNextFrame()->IsValid()) {320m_frame_type = eNotAValidFrame;321UnwindLogMsg("Could not get next frame, marking this frame as invalid.");322return;323}324if (!m_thread.GetRegisterContext()) {325m_frame_type = eNotAValidFrame;326UnwindLogMsg("Could not get register context for this thread, marking this "327"frame as invalid.");328return;329}330331ExecutionContext exe_ctx(m_thread.shared_from_this());332Process *process = exe_ctx.GetProcessPtr();333334// Some languages may have a logical parent stack frame which is335// not a real stack frame, but the programmer would consider it to336// be the caller of the frame, e.g. Swift asynchronous frames.337//338// A LanguageRuntime may provide an UnwindPlan that is used in this339// stack trace base on the RegisterContext contents, intsead340// of the normal UnwindPlans we would use for the return-pc.341UnwindPlanSP lang_runtime_plan_sp = LanguageRuntime::GetRuntimeUnwindPlan(342m_thread, this, m_behaves_like_zeroth_frame);343if (lang_runtime_plan_sp.get()) {344UnwindLogMsg("This is an async frame");345}346347addr_t pc;348if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {349UnwindLogMsg("could not get pc value");350m_frame_type = eNotAValidFrame;351return;352}353354// Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs355// this will strip bit zero in case we read a PC from memory or from the LR.356ABISP abi_sp = process->GetABI();357if (abi_sp)358pc = abi_sp->FixCodeAddress(pc);359360if (log) {361UnwindLogMsg("pc = 0x%" PRIx64, pc);362addr_t reg_val;363if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val)) {364if (abi_sp)365reg_val = abi_sp->FixDataAddress(reg_val);366UnwindLogMsg("fp = 0x%" PRIx64, reg_val);367}368if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val)) {369if (abi_sp)370reg_val = abi_sp->FixDataAddress(reg_val);371UnwindLogMsg("sp = 0x%" PRIx64, reg_val);372}373}374375// A pc of 0x0 means it's the end of the stack crawl unless we're above a trap376// handler function377bool above_trap_handler = false;378if (GetNextFrame().get() && GetNextFrame()->IsValid() &&379GetNextFrame()->IsTrapHandlerFrame())380above_trap_handler = true;381382if (pc == 0 || pc == 0x1) {383if (!above_trap_handler) {384m_frame_type = eNotAValidFrame;385UnwindLogMsg("this frame has a pc of 0x0");386return;387}388}389390const bool allow_section_end = true;391m_current_pc.SetLoadAddress(pc, &process->GetTarget(), allow_section_end);392393// If we don't have a Module for some reason, we're not going to find394// symbol/function information - just stick in some reasonable defaults and395// hope we can unwind past this frame. If we're above a trap handler,396// we may be at a bogus address because we jumped through a bogus function397// pointer and trapped, so don't force the arch default unwind plan in that398// case.399ModuleSP pc_module_sp(m_current_pc.GetModule());400if ((!m_current_pc.IsValid() || !pc_module_sp) &&401above_trap_handler == false) {402UnwindLogMsg("using architectural default unwind method");403404// Test the pc value to see if we know it's in an unmapped/non-executable405// region of memory.406uint32_t permissions;407if (process->GetLoadAddressPermissions(pc, permissions) &&408(permissions & ePermissionsExecutable) == 0) {409// If this is the second frame off the stack, we may have unwound the410// first frame incorrectly. But using the architecture default unwind411// plan may get us back on track -- albeit possibly skipping a real412// frame. Give this frame a clearly-invalid pc and see if we can get any413// further.414if (GetNextFrame().get() && GetNextFrame()->IsValid() &&415GetNextFrame()->IsFrameZero()) {416UnwindLogMsg("had a pc of 0x%" PRIx64 " which is not in executable "417"memory but on frame 1 -- "418"allowing it once.",419(uint64_t)pc);420m_frame_type = eSkipFrame;421} else {422// anywhere other than the second frame, a non-executable pc means423// we're off in the weeds -- stop now.424m_frame_type = eNotAValidFrame;425UnwindLogMsg("pc is in a non-executable section of memory and this "426"isn't the 2nd frame in the stack walk.");427return;428}429}430431if (abi_sp) {432m_fast_unwind_plan_sp.reset();433m_full_unwind_plan_sp =434std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);435abi_sp->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);436if (m_frame_type != eSkipFrame) // don't override eSkipFrame437{438m_frame_type = eNormalFrame;439}440m_all_registers_available = false;441m_current_offset = -1;442m_current_offset_backed_up_one = -1;443RegisterKind row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();444UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);445if (row.get()) {446if (!ReadFrameAddress(row_register_kind, row->GetCFAValue(), m_cfa)) {447UnwindLogMsg("failed to get cfa value");448if (m_frame_type != eSkipFrame) // don't override eSkipFrame449{450m_frame_type = eNotAValidFrame;451}452return;453}454455ReadFrameAddress(row_register_kind, row->GetAFAValue(), m_afa);456457// A couple of sanity checks..458if (m_cfa == LLDB_INVALID_ADDRESS || m_cfa == 0 || m_cfa == 1) {459UnwindLogMsg("could not find a valid cfa address");460m_frame_type = eNotAValidFrame;461return;462}463464// m_cfa should point into the stack memory; if we can query memory465// region permissions, see if the memory is allocated & readable.466if (process->GetLoadAddressPermissions(m_cfa, permissions) &&467(permissions & ePermissionsReadable) == 0) {468m_frame_type = eNotAValidFrame;469UnwindLogMsg(470"the CFA points to a region of memory that is not readable");471return;472}473} else {474UnwindLogMsg("could not find a row for function offset zero");475m_frame_type = eNotAValidFrame;476return;477}478479if (CheckIfLoopingStack()) {480TryFallbackUnwindPlan();481if (CheckIfLoopingStack()) {482UnwindLogMsg("same CFA address as next frame, assuming the unwind is "483"looping - stopping");484m_frame_type = eNotAValidFrame;485return;486}487}488489UnwindLogMsg("initialized frame cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,490(uint64_t)m_cfa, (uint64_t)m_afa);491return;492}493m_frame_type = eNotAValidFrame;494UnwindLogMsg("could not find any symbol for this pc, or a default unwind "495"plan, to continue unwind.");496return;497}498499AddressRange addr_range;500m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);501502if (m_sym_ctx.symbol) {503UnwindLogMsg("with pc value of 0x%" PRIx64 ", symbol name is '%s'", pc,504GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));505} else if (m_sym_ctx.function) {506UnwindLogMsg("with pc value of 0x%" PRIx64 ", function name is '%s'", pc,507GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));508} else {509UnwindLogMsg("with pc value of 0x%" PRIx64510", no symbol/function name is known.",511pc);512}513514bool decr_pc_and_recompute_addr_range;515516if (!m_sym_ctx_valid) {517// Always decrement and recompute if the symbol lookup failed518decr_pc_and_recompute_addr_range = true;519} else if (GetNextFrame()->m_frame_type == eTrapHandlerFrame ||520GetNextFrame()->m_frame_type == eDebuggerFrame) {521// Don't decrement if we're "above" an asynchronous event like522// sigtramp.523decr_pc_and_recompute_addr_range = false;524} else if (!addr_range.GetBaseAddress().IsValid() ||525addr_range.GetBaseAddress().GetSection() != m_current_pc.GetSection() ||526addr_range.GetBaseAddress().GetOffset() != m_current_pc.GetOffset()) {527// If our "current" pc isn't the start of a function, decrement the pc528// if we're up the stack.529if (m_behaves_like_zeroth_frame)530decr_pc_and_recompute_addr_range = false;531else532decr_pc_and_recompute_addr_range = true;533} else if (IsTrapHandlerSymbol(process, m_sym_ctx)) {534// Signal dispatch may set the return address of the handler it calls to535// point to the first byte of a return trampoline (like __kernel_rt_sigreturn),536// so do not decrement and recompute if the symbol we already found is a trap537// handler.538decr_pc_and_recompute_addr_range = false;539} else if (m_behaves_like_zeroth_frame) {540decr_pc_and_recompute_addr_range = false;541} else {542// Decrement to find the function containing the call.543decr_pc_and_recompute_addr_range = true;544}545546// We need to back up the pc by 1 byte and re-search for the Symbol to handle547// the case where the "saved pc" value is pointing to the next function, e.g.548// if a function ends with a CALL instruction.549// FIXME this may need to be an architectural-dependent behavior; if so we'll550// need to add a member function551// to the ABI plugin and consult that.552if (decr_pc_and_recompute_addr_range) {553UnwindLogMsg("Backing up the pc value of 0x%" PRIx64554" by 1 and re-doing symbol lookup; old symbol was %s",555pc, GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));556Address temporary_pc;557temporary_pc.SetLoadAddress(pc - 1, &process->GetTarget());558m_sym_ctx.Clear(false);559m_sym_ctx_valid = temporary_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);560561UnwindLogMsg("Symbol is now %s",562GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));563}564565// If we were able to find a symbol/function, set addr_range_ptr to the566// bounds of that symbol/function. else treat the current pc value as the567// start_pc and record no offset.568if (addr_range.GetBaseAddress().IsValid()) {569m_start_pc = addr_range.GetBaseAddress();570m_current_offset = pc - m_start_pc.GetLoadAddress(&process->GetTarget());571m_current_offset_backed_up_one = m_current_offset;572if (decr_pc_and_recompute_addr_range &&573m_current_offset_backed_up_one > 0) {574m_current_offset_backed_up_one--;575if (m_sym_ctx_valid) {576m_current_pc.SetLoadAddress(pc - 1, &process->GetTarget());577}578}579} else {580m_start_pc = m_current_pc;581m_current_offset = -1;582m_current_offset_backed_up_one = -1;583}584585if (IsTrapHandlerSymbol(process, m_sym_ctx)) {586m_frame_type = eTrapHandlerFrame;587} else {588// FIXME: Detect eDebuggerFrame here.589if (m_frame_type != eSkipFrame) // don't override eSkipFrame590{591m_frame_type = eNormalFrame;592}593}594595UnwindPlan::RowSP active_row;596RegisterKind row_register_kind = eRegisterKindGeneric;597598// If we have LanguageRuntime UnwindPlan for this unwind, use those599// rules to find the caller frame instead of the function's normal600// UnwindPlans. The full unwind plan for this frame will be601// the LanguageRuntime-provided unwind plan, and there will not be a602// fast unwind plan.603if (lang_runtime_plan_sp.get()) {604active_row =605lang_runtime_plan_sp->GetRowForFunctionOffset(m_current_offset);606row_register_kind = lang_runtime_plan_sp->GetRegisterKind();607if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(),608m_cfa)) {609UnwindLogMsg("Cannot set cfa");610} else {611m_full_unwind_plan_sp = lang_runtime_plan_sp;612if (log) {613StreamString active_row_strm;614active_row->Dump(active_row_strm, lang_runtime_plan_sp.get(), &m_thread,615m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));616UnwindLogMsg("async active row: %s", active_row_strm.GetData());617}618UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);619UnwindLogMsg(620"initialized async frame current pc is 0x%" PRIx64621" cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,622(uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),623(uint64_t)m_cfa, (uint64_t)m_afa);624625return;626}627}628629// We've set m_frame_type and m_sym_ctx before this call.630m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame();631632// Try to get by with just the fast UnwindPlan if possible - the full633// UnwindPlan may be expensive to get (e.g. if we have to parse the entire634// eh_frame section of an ObjectFile for the first time.)635636if (m_fast_unwind_plan_sp &&637m_fast_unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {638active_row =639m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);640row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind();641PropagateTrapHandlerFlagFromUnwindPlan(m_fast_unwind_plan_sp);642if (active_row.get() && log) {643StreamString active_row_strm;644active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread,645m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));646UnwindLogMsg("Using fast unwind plan '%s'",647m_fast_unwind_plan_sp->GetSourceName().AsCString());648UnwindLogMsg("active row: %s", active_row_strm.GetData());649}650} else {651m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();652if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp)) {653active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset(654m_current_offset_backed_up_one);655row_register_kind = m_full_unwind_plan_sp->GetRegisterKind();656PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);657if (active_row.get() && log) {658StreamString active_row_strm;659active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),660&m_thread,661m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));662UnwindLogMsg("Using full unwind plan '%s'",663m_full_unwind_plan_sp->GetSourceName().AsCString());664UnwindLogMsg("active row: %s", active_row_strm.GetData());665}666}667}668669if (!active_row.get()) {670m_frame_type = eNotAValidFrame;671UnwindLogMsg("could not find unwind row for this pc");672return;673}674675if (!ReadFrameAddress(row_register_kind, active_row->GetCFAValue(), m_cfa)) {676UnwindLogMsg("failed to get cfa");677m_frame_type = eNotAValidFrame;678return;679}680681ReadFrameAddress(row_register_kind, active_row->GetAFAValue(), m_afa);682683UnwindLogMsg("m_cfa = 0x%" PRIx64 " m_afa = 0x%" PRIx64, m_cfa, m_afa);684685if (CheckIfLoopingStack()) {686TryFallbackUnwindPlan();687if (CheckIfLoopingStack()) {688UnwindLogMsg("same CFA address as next frame, assuming the unwind is "689"looping - stopping");690m_frame_type = eNotAValidFrame;691return;692}693}694695UnwindLogMsg("initialized frame current pc is 0x%" PRIx64696" cfa is 0x%" PRIx64 " afa is 0x%" PRIx64,697(uint64_t)m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr()),698(uint64_t)m_cfa,699(uint64_t)m_afa);700}701702bool RegisterContextUnwind::CheckIfLoopingStack() {703// If we have a bad stack setup, we can get the same CFA value multiple times704// -- or even more devious, we can actually oscillate between two CFA values.705// Detect that here and break out to avoid a possible infinite loop in lldb706// trying to unwind the stack. To detect when we have the same CFA value707// multiple times, we compare the708// CFA of the current709// frame with the 2nd next frame because in some specail case (e.g. signal710// hanlders, hand written assembly without ABI compliance) we can have 2711// frames with the same712// CFA (in theory we713// can have arbitrary number of frames with the same CFA, but more then 2 is714// very unlikely)715716RegisterContextUnwind::SharedPtr next_frame = GetNextFrame();717if (next_frame) {718RegisterContextUnwind::SharedPtr next_next_frame =719next_frame->GetNextFrame();720addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;721if (next_next_frame && next_next_frame->GetCFA(next_next_frame_cfa)) {722if (next_next_frame_cfa == m_cfa) {723// We have a loop in the stack unwind724return true;725}726}727}728return false;729}730731bool RegisterContextUnwind::IsFrameZero() const { return m_frame_number == 0; }732733bool RegisterContextUnwind::BehavesLikeZerothFrame() const {734if (m_frame_number == 0)735return true;736if (m_behaves_like_zeroth_frame)737return true;738return false;739}740741// Find a fast unwind plan for this frame, if possible.742//743// On entry to this method,744//745// 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame746// if either of those are correct,747// 2. m_sym_ctx should already be filled in, and748// 3. m_current_pc should have the current pc value for this frame749// 4. m_current_offset_backed_up_one should have the current byte offset into750// the function, maybe backed up by 1, -1 if unknown751752UnwindPlanSP RegisterContextUnwind::GetFastUnwindPlanForFrame() {753UnwindPlanSP unwind_plan_sp;754ModuleSP pc_module_sp(m_current_pc.GetModule());755756if (!m_current_pc.IsValid() || !pc_module_sp ||757pc_module_sp->GetObjectFile() == nullptr)758return unwind_plan_sp;759760if (IsFrameZero())761return unwind_plan_sp;762763FuncUnwindersSP func_unwinders_sp(764pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(765m_current_pc, m_sym_ctx));766if (!func_unwinders_sp)767return unwind_plan_sp;768769// If we're in _sigtramp(), unwinding past this frame requires special770// knowledge.771if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)772return unwind_plan_sp;773774unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind(775*m_thread.CalculateTarget(), m_thread);776if (unwind_plan_sp) {777if (unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {778m_frame_type = eNormalFrame;779return unwind_plan_sp;780} else {781unwind_plan_sp.reset();782}783}784return unwind_plan_sp;785}786787// On entry to this method,788//789// 1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame790// if either of those are correct,791// 2. m_sym_ctx should already be filled in, and792// 3. m_current_pc should have the current pc value for this frame793// 4. m_current_offset_backed_up_one should have the current byte offset into794// the function, maybe backed up by 1, -1 if unknown795796UnwindPlanSP RegisterContextUnwind::GetFullUnwindPlanForFrame() {797UnwindPlanSP unwind_plan_sp;798UnwindPlanSP arch_default_unwind_plan_sp;799ExecutionContext exe_ctx(m_thread.shared_from_this());800Process *process = exe_ctx.GetProcessPtr();801ABI *abi = process ? process->GetABI().get() : nullptr;802if (abi) {803arch_default_unwind_plan_sp =804std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);805abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);806} else {807UnwindLogMsg(808"unable to get architectural default UnwindPlan from ABI plugin");809}810811if (IsFrameZero() || GetNextFrame()->m_frame_type == eTrapHandlerFrame ||812GetNextFrame()->m_frame_type == eDebuggerFrame) {813m_behaves_like_zeroth_frame = true;814// If this frame behaves like a 0th frame (currently executing or815// interrupted asynchronously), all registers can be retrieved.816m_all_registers_available = true;817}818819// If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer)820// so the pc is 0x0 in the zeroth frame, we need to use the "unwind at first821// instruction" arch default UnwindPlan Also, if this Process can report on822// memory region attributes, any non-executable region means we jumped823// through a bad function pointer - handle the same way as 0x0. Note, if we824// have a symbol context & a symbol, we don't want to follow this code path.825// This is for jumping to memory regions without any information available.826827if ((!m_sym_ctx_valid ||828(m_sym_ctx.function == nullptr && m_sym_ctx.symbol == nullptr)) &&829m_behaves_like_zeroth_frame && m_current_pc.IsValid()) {830uint32_t permissions;831addr_t current_pc_addr =832m_current_pc.GetLoadAddress(exe_ctx.GetTargetPtr());833if (current_pc_addr == 0 ||834(process &&835process->GetLoadAddressPermissions(current_pc_addr, permissions) &&836(permissions & ePermissionsExecutable) == 0)) {837if (abi) {838unwind_plan_sp =839std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);840abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);841m_frame_type = eNormalFrame;842return unwind_plan_sp;843}844}845}846847// No Module for the current pc, try using the architecture default unwind.848ModuleSP pc_module_sp(m_current_pc.GetModule());849if (!m_current_pc.IsValid() || !pc_module_sp ||850pc_module_sp->GetObjectFile() == nullptr) {851m_frame_type = eNormalFrame;852return arch_default_unwind_plan_sp;853}854855FuncUnwindersSP func_unwinders_sp;856if (m_sym_ctx_valid) {857func_unwinders_sp =858pc_module_sp->GetUnwindTable().GetFuncUnwindersContainingAddress(859m_current_pc, m_sym_ctx);860}861862// No FuncUnwinders available for this pc (stripped function symbols, lldb863// could not augment its function table with another source, like864// LC_FUNCTION_STARTS or eh_frame in ObjectFileMachO). See if eh_frame or the865// .ARM.exidx tables have unwind information for this address, else fall back866// to the architectural default unwind.867if (!func_unwinders_sp) {868m_frame_type = eNormalFrame;869870if (!pc_module_sp || !pc_module_sp->GetObjectFile() ||871!m_current_pc.IsValid())872return arch_default_unwind_plan_sp;873874// Even with -fomit-frame-pointer, we can try eh_frame to get back on875// track.876DWARFCallFrameInfo *eh_frame =877pc_module_sp->GetUnwindTable().GetEHFrameInfo();878if (eh_frame) {879unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);880if (eh_frame->GetUnwindPlan(m_current_pc, *unwind_plan_sp))881return unwind_plan_sp;882else883unwind_plan_sp.reset();884}885886ArmUnwindInfo *arm_exidx =887pc_module_sp->GetUnwindTable().GetArmUnwindInfo();888if (arm_exidx) {889unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);890if (arm_exidx->GetUnwindPlan(exe_ctx.GetTargetRef(), m_current_pc,891*unwind_plan_sp))892return unwind_plan_sp;893else894unwind_plan_sp.reset();895}896897CallFrameInfo *object_file_unwind =898pc_module_sp->GetUnwindTable().GetObjectFileUnwindInfo();899if (object_file_unwind) {900unwind_plan_sp = std::make_shared<UnwindPlan>(lldb::eRegisterKindGeneric);901if (object_file_unwind->GetUnwindPlan(m_current_pc, *unwind_plan_sp))902return unwind_plan_sp;903else904unwind_plan_sp.reset();905}906907return arch_default_unwind_plan_sp;908}909910if (m_frame_type == eTrapHandlerFrame && process) {911m_fast_unwind_plan_sp.reset();912913// On some platforms the unwind information for signal handlers is not914// present or correct. Give the platform plugins a chance to provide915// substitute plan. Otherwise, use eh_frame.916if (m_sym_ctx_valid) {917lldb::PlatformSP platform = process->GetTarget().GetPlatform();918unwind_plan_sp = platform->GetTrapHandlerUnwindPlan(919process->GetTarget().GetArchitecture().GetTriple(),920GetSymbolOrFunctionName(m_sym_ctx));921922if (unwind_plan_sp)923return unwind_plan_sp;924}925926unwind_plan_sp =927func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());928if (!unwind_plan_sp)929unwind_plan_sp =930func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());931if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc) &&932unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes) {933return unwind_plan_sp;934}935}936937// Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame938// even when it's frame zero This comes up if we have hand-written functions939// in a Module and hand-written eh_frame. The assembly instruction940// inspection may fail and the eh_frame CFI were probably written with some941// care to do the right thing. It'd be nice if there was a way to ask the942// eh_frame directly if it is asynchronous (can be trusted at every943// instruction point) or synchronous (the normal case - only at call sites).944// But there is not.945if (process && process->GetDynamicLoader() &&946process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo(m_sym_ctx)) {947// We must specifically call the GetEHFrameUnwindPlan() method here --948// normally we would call GetUnwindPlanAtCallSite() -- because CallSite may949// return an unwind plan sourced from either eh_frame (that's what we950// intend) or compact unwind (this won't work)951unwind_plan_sp =952func_unwinders_sp->GetEHFrameUnwindPlan(process->GetTarget());953if (!unwind_plan_sp)954unwind_plan_sp =955func_unwinders_sp->GetObjectFileUnwindPlan(process->GetTarget());956if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {957UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because the "958"DynamicLoader suggested we prefer it",959unwind_plan_sp->GetSourceName().GetCString());960return unwind_plan_sp;961}962}963964// Typically the NonCallSite UnwindPlan is the unwind created by inspecting965// the assembly language instructions966if (m_behaves_like_zeroth_frame && process) {967unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(968process->GetTarget(), m_thread);969if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress(m_current_pc)) {970if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {971// We probably have an UnwindPlan created by inspecting assembly972// instructions. The assembly profilers work really well with compiler-973// generated functions but hand- written assembly can be problematic.974// We set the eh_frame based unwind plan as our fallback unwind plan if975// instruction emulation doesn't work out even for non call sites if it976// is available and use the architecture default unwind plan if it is977// not available. The eh_frame unwind plan is more reliable even on non978// call sites then the architecture default plan and for hand written979// assembly code it is often written in a way that it valid at all980// location what helps in the most common cases when the instruction981// emulation fails.982UnwindPlanSP call_site_unwind_plan =983func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),984m_thread);985if (call_site_unwind_plan &&986call_site_unwind_plan.get() != unwind_plan_sp.get() &&987call_site_unwind_plan->GetSourceName() !=988unwind_plan_sp->GetSourceName()) {989m_fallback_unwind_plan_sp = call_site_unwind_plan;990} else {991m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;992}993}994UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "995"is the non-call site unwind plan and this is a "996"zeroth frame",997unwind_plan_sp->GetSourceName().GetCString());998return unwind_plan_sp;999}10001001// If we're on the first instruction of a function, and we have an1002// architectural default UnwindPlan for the initial instruction of a1003// function, use that.1004if (m_current_offset == 0) {1005unwind_plan_sp =1006func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry(1007m_thread);1008if (unwind_plan_sp) {1009UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we are at "1010"the first instruction of a function",1011unwind_plan_sp->GetSourceName().GetCString());1012return unwind_plan_sp;1013}1014}1015}10161017// Typically this is unwind info from an eh_frame section intended for1018// exception handling; only valid at call sites1019if (process) {1020unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite(1021process->GetTarget(), m_thread);1022}1023if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp)) {1024UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because this "1025"is the call-site unwind plan",1026unwind_plan_sp->GetSourceName().GetCString());1027return unwind_plan_sp;1028}10291030// We'd prefer to use an UnwindPlan intended for call sites when we're at a1031// call site but if we've struck out on that, fall back to using the non-1032// call-site assembly inspection UnwindPlan if possible.1033if (process) {1034unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite(1035process->GetTarget(), m_thread);1036}1037if (unwind_plan_sp &&1038unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo) {1039// We probably have an UnwindPlan created by inspecting assembly1040// instructions. The assembly profilers work really well with compiler-1041// generated functions but hand- written assembly can be problematic. We1042// set the eh_frame based unwind plan as our fallback unwind plan if1043// instruction emulation doesn't work out even for non call sites if it is1044// available and use the architecture default unwind plan if it is not1045// available. The eh_frame unwind plan is more reliable even on non call1046// sites then the architecture default plan and for hand written assembly1047// code it is often written in a way that it valid at all location what1048// helps in the most common cases when the instruction emulation fails.1049UnwindPlanSP call_site_unwind_plan =1050func_unwinders_sp->GetUnwindPlanAtCallSite(process->GetTarget(),1051m_thread);1052if (call_site_unwind_plan &&1053call_site_unwind_plan.get() != unwind_plan_sp.get() &&1054call_site_unwind_plan->GetSourceName() !=1055unwind_plan_sp->GetSourceName()) {1056m_fallback_unwind_plan_sp = call_site_unwind_plan;1057} else {1058m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;1059}1060}10611062if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp)) {1063UnwindLogMsgVerbose("frame uses %s for full UnwindPlan because we "1064"failed to find a call-site unwind plan that would work",1065unwind_plan_sp->GetSourceName().GetCString());1066return unwind_plan_sp;1067}10681069// If nothing else, use the architectural default UnwindPlan and hope that1070// does the job.1071if (arch_default_unwind_plan_sp)1072UnwindLogMsgVerbose(1073"frame uses %s for full UnwindPlan because we are falling back "1074"to the arch default plan",1075arch_default_unwind_plan_sp->GetSourceName().GetCString());1076else1077UnwindLogMsg(1078"Unable to find any UnwindPlan for full unwind of this frame.");10791080return arch_default_unwind_plan_sp;1081}10821083void RegisterContextUnwind::InvalidateAllRegisters() {1084m_frame_type = eNotAValidFrame;1085}10861087size_t RegisterContextUnwind::GetRegisterCount() {1088return m_thread.GetRegisterContext()->GetRegisterCount();1089}10901091const RegisterInfo *RegisterContextUnwind::GetRegisterInfoAtIndex(size_t reg) {1092return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex(reg);1093}10941095size_t RegisterContextUnwind::GetRegisterSetCount() {1096return m_thread.GetRegisterContext()->GetRegisterSetCount();1097}10981099const RegisterSet *RegisterContextUnwind::GetRegisterSet(size_t reg_set) {1100return m_thread.GetRegisterContext()->GetRegisterSet(reg_set);1101}11021103uint32_t RegisterContextUnwind::ConvertRegisterKindToRegisterNumber(1104lldb::RegisterKind kind, uint32_t num) {1105return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber(1106kind, num);1107}11081109bool RegisterContextUnwind::ReadRegisterValueFromRegisterLocation(1110lldb_private::UnwindLLDB::RegisterLocation regloc,1111const RegisterInfo *reg_info, RegisterValue &value) {1112if (!IsValid())1113return false;1114bool success = false;11151116switch (regloc.type) {1117case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {1118const RegisterInfo *other_reg_info =1119GetRegisterInfoAtIndex(regloc.location.register_number);11201121if (!other_reg_info)1122return false;11231124success =1125m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);1126} break;1127case UnwindLLDB::RegisterLocation::eRegisterInRegister: {1128const RegisterInfo *other_reg_info =1129GetRegisterInfoAtIndex(regloc.location.register_number);11301131if (!other_reg_info)1132return false;11331134if (IsFrameZero()) {1135success =1136m_thread.GetRegisterContext()->ReadRegister(other_reg_info, value);1137} else {1138success = GetNextFrame()->ReadRegister(other_reg_info, value);1139}1140} break;1141case UnwindLLDB::RegisterLocation::eRegisterValueInferred:1142success =1143value.SetUInt(regloc.location.inferred_value, reg_info->byte_size);1144break;11451146case UnwindLLDB::RegisterLocation::eRegisterNotSaved:1147break;1148case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:1149llvm_unreachable("FIXME debugger inferior function call unwind");1150case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {1151Status error(ReadRegisterValueFromMemory(1152reg_info, regloc.location.target_memory_location, reg_info->byte_size,1153value));1154success = error.Success();1155} break;1156default:1157llvm_unreachable("Unknown RegisterLocation type.");1158}1159return success;1160}11611162bool RegisterContextUnwind::WriteRegisterValueToRegisterLocation(1163lldb_private::UnwindLLDB::RegisterLocation regloc,1164const RegisterInfo *reg_info, const RegisterValue &value) {1165if (!IsValid())1166return false;11671168bool success = false;11691170switch (regloc.type) {1171case UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext: {1172const RegisterInfo *other_reg_info =1173GetRegisterInfoAtIndex(regloc.location.register_number);1174success =1175m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);1176} break;1177case UnwindLLDB::RegisterLocation::eRegisterInRegister: {1178const RegisterInfo *other_reg_info =1179GetRegisterInfoAtIndex(regloc.location.register_number);1180if (IsFrameZero()) {1181success =1182m_thread.GetRegisterContext()->WriteRegister(other_reg_info, value);1183} else {1184success = GetNextFrame()->WriteRegister(other_reg_info, value);1185}1186} break;1187case UnwindLLDB::RegisterLocation::eRegisterValueInferred:1188case UnwindLLDB::RegisterLocation::eRegisterNotSaved:1189break;1190case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:1191llvm_unreachable("FIXME debugger inferior function call unwind");1192case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation: {1193Status error(WriteRegisterValueToMemory(1194reg_info, regloc.location.target_memory_location, reg_info->byte_size,1195value));1196success = error.Success();1197} break;1198default:1199llvm_unreachable("Unknown RegisterLocation type.");1200}1201return success;1202}12031204bool RegisterContextUnwind::IsValid() const {1205return m_frame_type != eNotAValidFrame;1206}12071208// After the final stack frame in a stack walk we'll get one invalid1209// (eNotAValidFrame) stack frame -- one past the end of the stack walk. But1210// higher-level code will need to tell the difference between "the unwind plan1211// below this frame failed" versus "we successfully completed the stack walk"1212// so this method helps to disambiguate that.12131214bool RegisterContextUnwind::IsTrapHandlerFrame() const {1215return m_frame_type == eTrapHandlerFrame;1216}12171218// A skip frame is a bogus frame on the stack -- but one where we're likely to1219// find a real frame farther1220// up the stack if we keep looking. It's always the second frame in an unwind1221// (i.e. the first frame after frame zero) where unwinding can be the1222// trickiest. Ideally we'll mark up this frame in some way so the user knows1223// we're displaying bad data and we may have skipped one frame of their real1224// program in the process of getting back on track.12251226bool RegisterContextUnwind::IsSkipFrame() const {1227return m_frame_type == eSkipFrame;1228}12291230bool RegisterContextUnwind::IsTrapHandlerSymbol(1231lldb_private::Process *process,1232const lldb_private::SymbolContext &m_sym_ctx) const {1233PlatformSP platform_sp(process->GetTarget().GetPlatform());1234if (platform_sp) {1235const std::vector<ConstString> trap_handler_names(1236platform_sp->GetTrapHandlerSymbolNames());1237for (ConstString name : trap_handler_names) {1238if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||1239(m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {1240return true;1241}1242}1243}1244const std::vector<ConstString> user_specified_trap_handler_names(1245m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());1246for (ConstString name : user_specified_trap_handler_names) {1247if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||1248(m_sym_ctx.symbol && m_sym_ctx.symbol->GetName() == name)) {1249return true;1250}1251}12521253return false;1254}12551256// Answer the question: Where did THIS frame save the CALLER frame ("previous"1257// frame)'s register value?12581259enum UnwindLLDB::RegisterSearchResult1260RegisterContextUnwind::SavedLocationForRegister(1261uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation ®loc) {1262RegisterNumber regnum(m_thread, eRegisterKindLLDB, lldb_regnum);1263Log *log = GetLog(LLDBLog::Unwind);12641265// Have we already found this register location?1266if (!m_registers.empty()) {1267std::map<uint32_t,1268lldb_private::UnwindLLDB::RegisterLocation>::const_iterator1269iterator;1270iterator = m_registers.find(regnum.GetAsKind(eRegisterKindLLDB));1271if (iterator != m_registers.end()) {1272regloc = iterator->second;1273UnwindLogMsg("supplying caller's saved %s (%d)'s location, cached",1274regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1275return UnwindLLDB::RegisterSearchResult::eRegisterFound;1276}1277}12781279// Look through the available UnwindPlans for the register location.12801281UnwindPlan::Row::RegisterLocation unwindplan_regloc;1282bool have_unwindplan_regloc = false;1283RegisterKind unwindplan_registerkind = kNumRegisterKinds;12841285if (m_fast_unwind_plan_sp) {1286UnwindPlan::RowSP active_row =1287m_fast_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);1288unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind();1289if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {1290UnwindLogMsg("could not convert lldb regnum %s (%d) into %d RegisterKind "1291"reg numbering scheme",1292regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1293(int)unwindplan_registerkind);1294return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1295}1296// The architecture default unwind plan marks unknown registers as1297// Undefined so that we don't forward them up the stack when a1298// jitted stack frame may have overwritten them. But when the1299// arch default unwind plan is used as the Fast Unwind Plan, we1300// need to recognize this & switch over to the Full Unwind Plan1301// to see what unwind rule that (more knoweldgeable, probably)1302// UnwindPlan has. If the full UnwindPlan says the register1303// location is Undefined, then it really is.1304if (active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),1305unwindplan_regloc) &&1306!unwindplan_regloc.IsUndefined()) {1307UnwindLogMsg(1308"supplying caller's saved %s (%d)'s location using FastUnwindPlan",1309regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1310have_unwindplan_regloc = true;1311}1312}13131314if (!have_unwindplan_regloc) {1315// m_full_unwind_plan_sp being NULL means that we haven't tried to find a1316// full UnwindPlan yet1317bool got_new_full_unwindplan = false;1318if (!m_full_unwind_plan_sp) {1319m_full_unwind_plan_sp = GetFullUnwindPlanForFrame();1320got_new_full_unwindplan = true;1321}13221323if (m_full_unwind_plan_sp) {1324RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,1325LLDB_REGNUM_GENERIC_PC);13261327UnwindPlan::RowSP active_row =1328m_full_unwind_plan_sp->GetRowForFunctionOffset(1329m_current_offset_backed_up_one);1330unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();13311332if (got_new_full_unwindplan && active_row.get() && log) {1333StreamString active_row_strm;1334ExecutionContext exe_ctx(m_thread.shared_from_this());1335active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(),1336&m_thread,1337m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));1338UnwindLogMsg("Using full unwind plan '%s'",1339m_full_unwind_plan_sp->GetSourceName().AsCString());1340UnwindLogMsg("active row: %s", active_row_strm.GetData());1341}1342RegisterNumber return_address_reg;13431344// If we're fetching the saved pc and this UnwindPlan defines a1345// ReturnAddress register (e.g. lr on arm), look for the return address1346// register number in the UnwindPlan's row.1347if (pc_regnum.IsValid() && pc_regnum == regnum &&1348m_full_unwind_plan_sp->GetReturnAddressRegister() !=1349LLDB_INVALID_REGNUM) {1350// If this is a trap handler frame, we should have access to1351// the complete register context when the interrupt/async1352// signal was received, we should fetch the actual saved $pc1353// value instead of the Return Address register.1354// If $pc is not available, fall back to the RA reg.1355UnwindPlan::Row::RegisterLocation scratch;1356if (m_frame_type == eTrapHandlerFrame &&1357active_row->GetRegisterInfo1358(pc_regnum.GetAsKind (unwindplan_registerkind), scratch)) {1359UnwindLogMsg("Providing pc register instead of rewriting to "1360"RA reg because this is a trap handler and there is "1361"a location for the saved pc register value.");1362} else {1363return_address_reg.init(1364m_thread, m_full_unwind_plan_sp->GetRegisterKind(),1365m_full_unwind_plan_sp->GetReturnAddressRegister());1366regnum = return_address_reg;1367UnwindLogMsg("requested caller's saved PC but this UnwindPlan uses a "1368"RA reg; getting %s (%d) instead",1369return_address_reg.GetName(),1370return_address_reg.GetAsKind(eRegisterKindLLDB));1371}1372} else {1373if (regnum.GetAsKind(unwindplan_registerkind) == LLDB_INVALID_REGNUM) {1374if (unwindplan_registerkind == eRegisterKindGeneric) {1375UnwindLogMsg("could not convert lldb regnum %s (%d) into "1376"eRegisterKindGeneric reg numbering scheme",1377regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1378} else {1379UnwindLogMsg("could not convert lldb regnum %s (%d) into %d "1380"RegisterKind reg numbering scheme",1381regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1382(int)unwindplan_registerkind);1383}1384return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1385}1386}13871388if (regnum.IsValid() &&1389active_row->GetRegisterInfo(regnum.GetAsKind(unwindplan_registerkind),1390unwindplan_regloc)) {1391have_unwindplan_regloc = true;1392UnwindLogMsg(1393"supplying caller's saved %s (%d)'s location using %s UnwindPlan",1394regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1395m_full_unwind_plan_sp->GetSourceName().GetCString());1396}13971398// This is frame 0 and we're retrieving the PC and it's saved in a Return1399// Address register and it hasn't been saved anywhere yet -- that is,1400// it's still live in the actual register. Handle this specially.14011402if (!have_unwindplan_regloc && return_address_reg.IsValid() &&1403BehavesLikeZerothFrame()) {1404if (return_address_reg.GetAsKind(eRegisterKindLLDB) !=1405LLDB_INVALID_REGNUM) {1406lldb_private::UnwindLLDB::RegisterLocation new_regloc;1407new_regloc.type =1408UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;1409new_regloc.location.register_number =1410return_address_reg.GetAsKind(eRegisterKindLLDB);1411m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;1412regloc = new_regloc;1413UnwindLogMsg("supplying caller's register %s (%d) from the live "1414"RegisterContext at frame 0, saved in %d",1415return_address_reg.GetName(),1416return_address_reg.GetAsKind(eRegisterKindLLDB),1417return_address_reg.GetAsKind(eRegisterKindLLDB));1418return UnwindLLDB::RegisterSearchResult::eRegisterFound;1419}1420}14211422// If this architecture stores the return address in a register (it1423// defines a Return Address register) and we're on a non-zero stack frame1424// and the Full UnwindPlan says that the pc is stored in the1425// RA registers (e.g. lr on arm), then we know that the full unwindplan is1426// not trustworthy -- this1427// is an impossible situation and the instruction emulation code has1428// likely been misled. If this stack frame meets those criteria, we need1429// to throw away the Full UnwindPlan that the instruction emulation came1430// up with and fall back to the architecture's Default UnwindPlan so the1431// stack walk can get past this point.14321433// Special note: If the Full UnwindPlan was generated from the compiler,1434// don't second-guess it when we're at a call site location.14351436// arch_default_ra_regnum is the return address register # in the Full1437// UnwindPlan register numbering1438RegisterNumber arch_default_ra_regnum(m_thread, eRegisterKindGeneric,1439LLDB_REGNUM_GENERIC_RA);14401441if (arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) !=1442LLDB_INVALID_REGNUM &&1443pc_regnum == regnum && unwindplan_regloc.IsInOtherRegister() &&1444unwindplan_regloc.GetRegisterNumber() ==1445arch_default_ra_regnum.GetAsKind(unwindplan_registerkind) &&1446m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes &&1447!m_all_registers_available) {1448UnwindLogMsg("%s UnwindPlan tried to restore the pc from the link "1449"register but this is a non-zero frame",1450m_full_unwind_plan_sp->GetSourceName().GetCString());14511452// Throw away the full unwindplan; install the arch default unwindplan1453if (ForceSwitchToFallbackUnwindPlan()) {1454// Update for the possibly new unwind plan1455unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind();1456UnwindPlan::RowSP active_row =1457m_full_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);14581459// Sanity check: Verify that we can fetch a pc value and CFA value1460// with this unwind plan14611462RegisterNumber arch_default_pc_reg(m_thread, eRegisterKindGeneric,1463LLDB_REGNUM_GENERIC_PC);1464bool can_fetch_pc_value = false;1465bool can_fetch_cfa = false;1466addr_t cfa_value;1467if (active_row) {1468if (arch_default_pc_reg.GetAsKind(unwindplan_registerkind) !=1469LLDB_INVALID_REGNUM &&1470active_row->GetRegisterInfo(1471arch_default_pc_reg.GetAsKind(unwindplan_registerkind),1472unwindplan_regloc)) {1473can_fetch_pc_value = true;1474}1475if (ReadFrameAddress(unwindplan_registerkind,1476active_row->GetCFAValue(), cfa_value)) {1477can_fetch_cfa = true;1478}1479}14801481have_unwindplan_regloc = can_fetch_pc_value && can_fetch_cfa;1482} else {1483// We were unable to fall back to another unwind plan1484have_unwindplan_regloc = false;1485}1486}1487}1488}14891490ExecutionContext exe_ctx(m_thread.shared_from_this());1491Process *process = exe_ctx.GetProcessPtr();1492if (!have_unwindplan_regloc) {1493// If the UnwindPlan failed to give us an unwind location for this1494// register, we may be able to fall back to some ABI-defined default. For1495// example, some ABIs allow to determine the caller's SP via the CFA. Also,1496// the ABI may set volatile registers to the undefined state.1497ABI *abi = process ? process->GetABI().get() : nullptr;1498if (abi) {1499const RegisterInfo *reg_info =1500GetRegisterInfoAtIndex(regnum.GetAsKind(eRegisterKindLLDB));1501if (reg_info &&1502abi->GetFallbackRegisterLocation(reg_info, unwindplan_regloc)) {1503UnwindLogMsg(1504"supplying caller's saved %s (%d)'s location using ABI default",1505regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1506have_unwindplan_regloc = true;1507}1508}1509}15101511if (!have_unwindplan_regloc) {1512if (IsFrameZero()) {1513// This is frame 0 - we should return the actual live register context1514// value1515lldb_private::UnwindLLDB::RegisterLocation new_regloc;1516new_regloc.type =1517UnwindLLDB::RegisterLocation::eRegisterInLiveRegisterContext;1518new_regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);1519m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;1520regloc = new_regloc;1521UnwindLogMsg("supplying caller's register %s (%d) from the live "1522"RegisterContext at frame 0",1523regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1524return UnwindLLDB::RegisterSearchResult::eRegisterFound;1525} else {1526std::string unwindplan_name;1527if (m_full_unwind_plan_sp) {1528unwindplan_name += "via '";1529unwindplan_name += m_full_unwind_plan_sp->GetSourceName().AsCString();1530unwindplan_name += "'";1531}1532UnwindLogMsg("no save location for %s (%d) %s", regnum.GetName(),1533regnum.GetAsKind(eRegisterKindLLDB),1534unwindplan_name.c_str());1535}1536return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1537}15381539// unwindplan_regloc has valid contents about where to retrieve the register1540if (unwindplan_regloc.IsUnspecified()) {1541lldb_private::UnwindLLDB::RegisterLocation new_regloc = {};1542new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;1543m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = new_regloc;1544UnwindLogMsg("save location for %s (%d) is unspecified, continue searching",1545regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1546return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1547}15481549if (unwindplan_regloc.IsUndefined()) {1550UnwindLogMsg(1551"did not supply reg location for %s (%d) because it is volatile",1552regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1553return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;1554}15551556if (unwindplan_regloc.IsSame()) {1557if (!m_all_registers_available &&1558(regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_PC ||1559regnum.GetAsKind(eRegisterKindGeneric) == LLDB_REGNUM_GENERIC_RA)) {1560UnwindLogMsg("register %s (%d) is marked as 'IsSame' - it is a pc or "1561"return address reg on a frame which does not have all "1562"registers available -- treat as if we have no information",1563regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1564return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1565} else {1566regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;1567regloc.location.register_number = regnum.GetAsKind(eRegisterKindLLDB);1568m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1569UnwindLogMsg(1570"supplying caller's register %s (%d), saved in register %s (%d)",1571regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1572regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1573return UnwindLLDB::RegisterSearchResult::eRegisterFound;1574}1575}15761577if (unwindplan_regloc.IsCFAPlusOffset()) {1578int offset = unwindplan_regloc.GetOffset();1579regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;1580regloc.location.inferred_value = m_cfa + offset;1581m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1582UnwindLogMsg("supplying caller's register %s (%d), value is CFA plus "1583"offset %d [value is 0x%" PRIx64 "]",1584regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1585regloc.location.inferred_value);1586return UnwindLLDB::RegisterSearchResult::eRegisterFound;1587}15881589if (unwindplan_regloc.IsAtCFAPlusOffset()) {1590int offset = unwindplan_regloc.GetOffset();1591regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;1592regloc.location.target_memory_location = m_cfa + offset;1593m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1594UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "1595"CFA plus offset %d [saved at 0x%" PRIx64 "]",1596regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1597regloc.location.target_memory_location);1598return UnwindLLDB::RegisterSearchResult::eRegisterFound;1599}16001601if (unwindplan_regloc.IsAFAPlusOffset()) {1602if (m_afa == LLDB_INVALID_ADDRESS)1603return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;16041605int offset = unwindplan_regloc.GetOffset();1606regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;1607regloc.location.inferred_value = m_afa + offset;1608m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1609UnwindLogMsg("supplying caller's register %s (%d), value is AFA plus "1610"offset %d [value is 0x%" PRIx64 "]",1611regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1612regloc.location.inferred_value);1613return UnwindLLDB::RegisterSearchResult::eRegisterFound;1614}16151616if (unwindplan_regloc.IsAtAFAPlusOffset()) {1617if (m_afa == LLDB_INVALID_ADDRESS)1618return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;16191620int offset = unwindplan_regloc.GetOffset();1621regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;1622regloc.location.target_memory_location = m_afa + offset;1623m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1624UnwindLogMsg("supplying caller's register %s (%d) from the stack, saved at "1625"AFA plus offset %d [saved at 0x%" PRIx64 "]",1626regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB), offset,1627regloc.location.target_memory_location);1628return UnwindLLDB::RegisterSearchResult::eRegisterFound;1629}16301631if (unwindplan_regloc.IsInOtherRegister()) {1632uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();1633RegisterNumber row_regnum(m_thread, unwindplan_registerkind,1634unwindplan_regnum);1635if (row_regnum.GetAsKind(eRegisterKindLLDB) == LLDB_INVALID_REGNUM) {1636UnwindLogMsg("could not supply caller's %s (%d) location - was saved in "1637"another reg but couldn't convert that regnum",1638regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1639return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1640}1641regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;1642regloc.location.register_number = row_regnum.GetAsKind(eRegisterKindLLDB);1643m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1644UnwindLogMsg(1645"supplying caller's register %s (%d), saved in register %s (%d)",1646regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB),1647row_regnum.GetName(), row_regnum.GetAsKind(eRegisterKindLLDB));1648return UnwindLLDB::RegisterSearchResult::eRegisterFound;1649}16501651if (unwindplan_regloc.IsDWARFExpression() ||1652unwindplan_regloc.IsAtDWARFExpression()) {1653DataExtractor dwarfdata(unwindplan_regloc.GetDWARFExpressionBytes(),1654unwindplan_regloc.GetDWARFExpressionLength(),1655process->GetByteOrder(),1656process->GetAddressByteSize());1657ModuleSP opcode_ctx;1658DWARFExpressionList dwarfexpr(opcode_ctx, dwarfdata, nullptr);1659dwarfexpr.GetMutableExpressionAtAddress()->SetRegisterKind(1660unwindplan_registerkind);1661Value cfa_val = Scalar(m_cfa);1662cfa_val.SetValueType(Value::ValueType::LoadAddress);1663llvm::Expected<Value> result =1664dwarfexpr.Evaluate(&exe_ctx, this, 0, &cfa_val, nullptr);1665if (!result) {1666LLDB_LOG_ERROR(log, result.takeError(),1667"DWARF expression failed to evaluate: {0}");1668} else {1669addr_t val;1670val = result->GetScalar().ULongLong();1671if (unwindplan_regloc.IsDWARFExpression()) {1672regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;1673regloc.location.inferred_value = val;1674m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1675UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "1676"(IsDWARFExpression)",1677regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1678return UnwindLLDB::RegisterSearchResult::eRegisterFound;1679} else {1680regloc.type =1681UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;1682regloc.location.target_memory_location = val;1683m_registers[regnum.GetAsKind(eRegisterKindLLDB)] = regloc;1684UnwindLogMsg("supplying caller's register %s (%d) via DWARF expression "1685"(IsAtDWARFExpression)",1686regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1687return UnwindLLDB::RegisterSearchResult::eRegisterFound;1688}1689}1690UnwindLogMsg("tried to use IsDWARFExpression or IsAtDWARFExpression for %s "1691"(%d) but failed",1692regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));1693return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1694}16951696UnwindLogMsg("no save location for %s (%d) in this stack frame",1697regnum.GetName(), regnum.GetAsKind(eRegisterKindLLDB));16981699// FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are1700// unsupported.17011702return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;1703}17041705// TryFallbackUnwindPlan() -- this method is a little tricky.1706//1707// When this is called, the frame above -- the caller frame, the "previous"1708// frame -- is invalid or bad.1709//1710// Instead of stopping the stack walk here, we'll try a different UnwindPlan1711// and see if we can get a valid frame above us.1712//1713// This most often happens when an unwind plan based on assembly instruction1714// inspection is not correct -- mostly with hand-written assembly functions or1715// functions where the stack frame is set up "out of band", e.g. the kernel1716// saved the register context and then called an asynchronous trap handler like1717// _sigtramp.1718//1719// Often in these cases, if we just do a dumb stack walk we'll get past this1720// tricky frame and our usual techniques can continue to be used.17211722bool RegisterContextUnwind::TryFallbackUnwindPlan() {1723if (m_fallback_unwind_plan_sp.get() == nullptr)1724return false;17251726if (m_full_unwind_plan_sp.get() == nullptr)1727return false;17281729if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||1730m_full_unwind_plan_sp->GetSourceName() ==1731m_fallback_unwind_plan_sp->GetSourceName()) {1732return false;1733}17341735// If a compiler generated unwind plan failed, trying the arch default1736// unwindplan isn't going to do any better.1737if (m_full_unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)1738return false;17391740// Get the caller's pc value and our own CFA value. Swap in the fallback1741// unwind plan, re-fetch the caller's pc value and CFA value. If they're the1742// same, then the fallback unwind plan provides no benefit.17431744RegisterNumber pc_regnum(m_thread, eRegisterKindGeneric,1745LLDB_REGNUM_GENERIC_PC);17461747addr_t old_caller_pc_value = LLDB_INVALID_ADDRESS;1748addr_t new_caller_pc_value = LLDB_INVALID_ADDRESS;1749UnwindLLDB::RegisterLocation regloc = {};1750if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),1751regloc) ==1752UnwindLLDB::RegisterSearchResult::eRegisterFound) {1753const RegisterInfo *reg_info =1754GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));1755if (reg_info) {1756RegisterValue reg_value;1757if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {1758old_caller_pc_value = reg_value.GetAsUInt64();1759if (ProcessSP process_sp = m_thread.GetProcess()) {1760if (ABISP abi_sp = process_sp->GetABI())1761old_caller_pc_value = abi_sp->FixCodeAddress(old_caller_pc_value);1762}1763}1764}1765}17661767// This is a tricky wrinkle! If SavedLocationForRegister() detects a really1768// impossible register location for the full unwind plan, it may call1769// ForceSwitchToFallbackUnwindPlan() which in turn replaces the full1770// unwindplan with the fallback... in short, we're done, we're using the1771// fallback UnwindPlan. We checked if m_fallback_unwind_plan_sp was nullptr1772// at the top -- the only way it became nullptr since then is via1773// SavedLocationForRegister().1774if (m_fallback_unwind_plan_sp.get() == nullptr)1775return true;17761777// Switch the full UnwindPlan to be the fallback UnwindPlan. If we decide1778// this isn't working, we need to restore. We'll also need to save & restore1779// the value of the m_cfa ivar. Save is down below a bit in 'old_cfa'.1780UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;1781addr_t old_cfa = m_cfa;1782addr_t old_afa = m_afa;17831784m_registers.clear();17851786m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;17871788UnwindPlan::RowSP active_row =1789m_fallback_unwind_plan_sp->GetRowForFunctionOffset(1790m_current_offset_backed_up_one);17911792if (active_row &&1793active_row->GetCFAValue().GetValueType() !=1794UnwindPlan::Row::FAValue::unspecified) {1795addr_t new_cfa;1796if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1797active_row->GetCFAValue(), new_cfa) ||1798new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {1799UnwindLogMsg("failed to get cfa with fallback unwindplan");1800m_fallback_unwind_plan_sp.reset();1801m_full_unwind_plan_sp = original_full_unwind_plan_sp;1802return false;1803}1804m_cfa = new_cfa;18051806ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1807active_row->GetAFAValue(), m_afa);18081809if (SavedLocationForRegister(pc_regnum.GetAsKind(eRegisterKindLLDB),1810regloc) ==1811UnwindLLDB::RegisterSearchResult::eRegisterFound) {1812const RegisterInfo *reg_info =1813GetRegisterInfoAtIndex(pc_regnum.GetAsKind(eRegisterKindLLDB));1814if (reg_info) {1815RegisterValue reg_value;1816if (ReadRegisterValueFromRegisterLocation(regloc, reg_info,1817reg_value)) {1818new_caller_pc_value = reg_value.GetAsUInt64();1819if (ProcessSP process_sp = m_thread.GetProcess()) {1820if (ABISP abi_sp = process_sp->GetABI())1821new_caller_pc_value = abi_sp->FixCodeAddress(new_caller_pc_value);1822}1823}1824}1825}18261827if (new_caller_pc_value == LLDB_INVALID_ADDRESS) {1828UnwindLogMsg("failed to get a pc value for the caller frame with the "1829"fallback unwind plan");1830m_fallback_unwind_plan_sp.reset();1831m_full_unwind_plan_sp = original_full_unwind_plan_sp;1832m_cfa = old_cfa;1833m_afa = old_afa;1834return false;1835}18361837if (old_caller_pc_value == new_caller_pc_value &&1838m_cfa == old_cfa &&1839m_afa == old_afa) {1840UnwindLogMsg("fallback unwind plan got the same values for this frame "1841"CFA and caller frame pc, not using");1842m_fallback_unwind_plan_sp.reset();1843m_full_unwind_plan_sp = original_full_unwind_plan_sp;1844return false;1845}18461847UnwindLogMsg("trying to unwind from this function with the UnwindPlan '%s' "1848"because UnwindPlan '%s' failed.",1849m_fallback_unwind_plan_sp->GetSourceName().GetCString(),1850original_full_unwind_plan_sp->GetSourceName().GetCString());18511852// We've copied the fallback unwind plan into the full - now clear the1853// fallback.1854m_fallback_unwind_plan_sp.reset();1855PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);1856}18571858return true;1859}18601861bool RegisterContextUnwind::ForceSwitchToFallbackUnwindPlan() {1862if (m_fallback_unwind_plan_sp.get() == nullptr)1863return false;18641865if (m_full_unwind_plan_sp.get() == nullptr)1866return false;18671868if (m_full_unwind_plan_sp.get() == m_fallback_unwind_plan_sp.get() ||1869m_full_unwind_plan_sp->GetSourceName() ==1870m_fallback_unwind_plan_sp->GetSourceName()) {1871return false;1872}18731874UnwindPlan::RowSP active_row =1875m_fallback_unwind_plan_sp->GetRowForFunctionOffset(m_current_offset);18761877if (active_row &&1878active_row->GetCFAValue().GetValueType() !=1879UnwindPlan::Row::FAValue::unspecified) {1880addr_t new_cfa;1881if (!ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1882active_row->GetCFAValue(), new_cfa) ||1883new_cfa == 0 || new_cfa == 1 || new_cfa == LLDB_INVALID_ADDRESS) {1884UnwindLogMsg("failed to get cfa with fallback unwindplan");1885m_fallback_unwind_plan_sp.reset();1886return false;1887}18881889ReadFrameAddress(m_fallback_unwind_plan_sp->GetRegisterKind(),1890active_row->GetAFAValue(), m_afa);18911892m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;1893m_fallback_unwind_plan_sp.reset();18941895m_registers.clear();18961897m_cfa = new_cfa;18981899PropagateTrapHandlerFlagFromUnwindPlan(m_full_unwind_plan_sp);19001901UnwindLogMsg("switched unconditionally to the fallback unwindplan %s",1902m_full_unwind_plan_sp->GetSourceName().GetCString());1903return true;1904}1905return false;1906}19071908void RegisterContextUnwind::PropagateTrapHandlerFlagFromUnwindPlan(1909lldb::UnwindPlanSP unwind_plan) {1910if (unwind_plan->GetUnwindPlanForSignalTrap() != eLazyBoolYes) {1911// Unwind plan does not indicate trap handler. Do nothing. We may1912// already be flagged as trap handler flag due to the symbol being1913// in the trap handler symbol list, and that should take precedence.1914return;1915} else if (m_frame_type != eNormalFrame) {1916// If this is already a trap handler frame, nothing to do.1917// If this is a skip or debug or invalid frame, don't override that.1918return;1919}19201921m_frame_type = eTrapHandlerFrame;19221923if (m_current_offset_backed_up_one != m_current_offset) {1924// We backed up the pc by 1 to compute the symbol context, but1925// now need to undo that because the pc of the trap handler1926// frame may in fact be the first instruction of a signal return1927// trampoline, rather than the instruction after a call. This1928// happens on systems where the signal handler dispatch code, rather1929// than calling the handler and being returned to, jumps to the1930// handler after pushing the address of a return trampoline on the1931// stack -- on these systems, when the handler returns, control will1932// be transferred to the return trampoline, so that's the best1933// symbol we can present in the callstack.1934UnwindLogMsg("Resetting current offset and re-doing symbol lookup; "1935"old symbol was %s",1936GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));1937m_current_offset_backed_up_one = m_current_offset;19381939AddressRange addr_range;1940m_sym_ctx_valid = m_current_pc.ResolveFunctionScope(m_sym_ctx, &addr_range);19411942UnwindLogMsg("Symbol is now %s",1943GetSymbolOrFunctionName(m_sym_ctx).AsCString(""));19441945ExecutionContext exe_ctx(m_thread.shared_from_this());1946Process *process = exe_ctx.GetProcessPtr();1947Target *target = &process->GetTarget();19481949m_start_pc = addr_range.GetBaseAddress();1950m_current_offset =1951m_current_pc.GetLoadAddress(target) - m_start_pc.GetLoadAddress(target);1952}1953}19541955bool RegisterContextUnwind::ReadFrameAddress(1956lldb::RegisterKind row_register_kind, UnwindPlan::Row::FAValue &fa,1957addr_t &address) {1958RegisterValue reg_value;19591960address = LLDB_INVALID_ADDRESS;1961addr_t cfa_reg_contents;1962ABISP abi_sp = m_thread.GetProcess()->GetABI();19631964switch (fa.GetValueType()) {1965case UnwindPlan::Row::FAValue::isRegisterDereferenced: {1966RegisterNumber cfa_reg(m_thread, row_register_kind,1967fa.GetRegisterNumber());1968if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {1969const RegisterInfo *reg_info =1970GetRegisterInfoAtIndex(cfa_reg.GetAsKind(eRegisterKindLLDB));1971RegisterValue reg_value;1972if (reg_info) {1973if (abi_sp)1974cfa_reg_contents = abi_sp->FixDataAddress(cfa_reg_contents);1975Status error = ReadRegisterValueFromMemory(1976reg_info, cfa_reg_contents, reg_info->byte_size, reg_value);1977if (error.Success()) {1978address = reg_value.GetAsUInt64();1979if (abi_sp)1980address = abi_sp->FixCodeAddress(address);1981UnwindLogMsg(1982"CFA value via dereferencing reg %s (%d): reg has val 0x%" PRIx641983", CFA value is 0x%" PRIx64,1984cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),1985cfa_reg_contents, address);1986return true;1987} else {1988UnwindLogMsg("Tried to deref reg %s (%d) [0x%" PRIx641989"] but memory read failed.",1990cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),1991cfa_reg_contents);1992}1993}1994}1995break;1996}1997case UnwindPlan::Row::FAValue::isRegisterPlusOffset: {1998RegisterNumber cfa_reg(m_thread, row_register_kind,1999fa.GetRegisterNumber());2000if (ReadGPRValue(cfa_reg, cfa_reg_contents)) {2001if (abi_sp)2002cfa_reg_contents = abi_sp->FixDataAddress(cfa_reg_contents);2003if (cfa_reg_contents == LLDB_INVALID_ADDRESS || cfa_reg_contents == 0 ||2004cfa_reg_contents == 1) {2005UnwindLogMsg(2006"Got an invalid CFA register value - reg %s (%d), value 0x%" PRIx64,2007cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),2008cfa_reg_contents);2009cfa_reg_contents = LLDB_INVALID_ADDRESS;2010return false;2011}2012address = cfa_reg_contents + fa.GetOffset();2013UnwindLogMsg(2014"CFA is 0x%" PRIx64 ": Register %s (%d) contents are 0x%" PRIx642015", offset is %d",2016address, cfa_reg.GetName(), cfa_reg.GetAsKind(eRegisterKindLLDB),2017cfa_reg_contents, fa.GetOffset());2018return true;2019}2020break;2021}2022case UnwindPlan::Row::FAValue::isDWARFExpression: {2023ExecutionContext exe_ctx(m_thread.shared_from_this());2024Process *process = exe_ctx.GetProcessPtr();2025DataExtractor dwarfdata(fa.GetDWARFExpressionBytes(),2026fa.GetDWARFExpressionLength(),2027process->GetByteOrder(),2028process->GetAddressByteSize());2029ModuleSP opcode_ctx;2030DWARFExpressionList dwarfexpr(opcode_ctx, dwarfdata, nullptr);2031dwarfexpr.GetMutableExpressionAtAddress()->SetRegisterKind(2032row_register_kind);2033llvm::Expected<Value> result =2034dwarfexpr.Evaluate(&exe_ctx, this, 0, nullptr, nullptr);2035if (result) {2036address = result->GetScalar().ULongLong();2037if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2038address = abi_sp->FixCodeAddress(address);20392040UnwindLogMsg("CFA value set by DWARF expression is 0x%" PRIx64,2041address);2042return true;2043}2044UnwindLogMsg("Failed to set CFA value via DWARF expression: %s",2045llvm::toString(result.takeError()).c_str());2046break;2047}2048case UnwindPlan::Row::FAValue::isRaSearch: {2049Process &process = *m_thread.GetProcess();2050lldb::addr_t return_address_hint = GetReturnAddressHint(fa.GetOffset());2051if (return_address_hint == LLDB_INVALID_ADDRESS)2052return false;2053const unsigned max_iterations = 256;2054for (unsigned i = 0; i < max_iterations; ++i) {2055Status st;2056lldb::addr_t candidate_addr =2057return_address_hint + i * process.GetAddressByteSize();2058lldb::addr_t candidate =2059process.ReadPointerFromMemory(candidate_addr, st);2060if (st.Fail()) {2061UnwindLogMsg("Cannot read memory at 0x%" PRIx64 ": %s", candidate_addr,2062st.AsCString());2063return false;2064}2065Address addr;2066uint32_t permissions;2067if (process.GetLoadAddressPermissions(candidate, permissions) &&2068permissions & lldb::ePermissionsExecutable) {2069address = candidate_addr;2070UnwindLogMsg("Heuristically found CFA: 0x%" PRIx64, address);2071return true;2072}2073}2074UnwindLogMsg("No suitable CFA found");2075break;2076}2077default:2078return false;2079}2080return false;2081}20822083lldb::addr_t RegisterContextUnwind::GetReturnAddressHint(int32_t plan_offset) {2084addr_t hint;2085if (!ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, hint))2086return LLDB_INVALID_ADDRESS;2087if (!m_sym_ctx.module_sp || !m_sym_ctx.symbol)2088return LLDB_INVALID_ADDRESS;2089if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2090hint = abi_sp->FixCodeAddress(hint);20912092hint += plan_offset;20932094if (auto next = GetNextFrame()) {2095if (!next->m_sym_ctx.module_sp || !next->m_sym_ctx.symbol)2096return LLDB_INVALID_ADDRESS;2097if (auto expected_size =2098next->m_sym_ctx.module_sp->GetSymbolFile()->GetParameterStackSize(2099*next->m_sym_ctx.symbol))2100hint += *expected_size;2101else {2102UnwindLogMsgVerbose("Could not retrieve parameter size: %s",2103llvm::toString(expected_size.takeError()).c_str());2104return LLDB_INVALID_ADDRESS;2105}2106}2107return hint;2108}21092110// Retrieve a general purpose register value for THIS frame, as saved by the2111// NEXT frame, i.e. the frame that2112// this frame called. e.g.2113//2114// foo () { }2115// bar () { foo (); }2116// main () { bar (); }2117//2118// stopped in foo() so2119// frame 0 - foo2120// frame 1 - bar2121// frame 2 - main2122// and this RegisterContext is for frame 1 (bar) - if we want to get the pc2123// value for frame 1, we need to ask2124// where frame 0 (the "next" frame) saved that and retrieve the value.21252126bool RegisterContextUnwind::ReadGPRValue(lldb::RegisterKind register_kind,2127uint32_t regnum, addr_t &value) {2128if (!IsValid())2129return false;21302131uint32_t lldb_regnum;2132if (register_kind == eRegisterKindLLDB) {2133lldb_regnum = regnum;2134} else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(2135register_kind, regnum, eRegisterKindLLDB, lldb_regnum)) {2136return false;2137}21382139const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);2140assert(reg_info);2141if (!reg_info) {2142UnwindLogMsg(2143"Could not find RegisterInfo definition for lldb register number %d",2144lldb_regnum);2145return false;2146}21472148uint32_t generic_regnum = LLDB_INVALID_REGNUM;2149if (register_kind == eRegisterKindGeneric)2150generic_regnum = regnum;2151else2152m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds(2153register_kind, regnum, eRegisterKindGeneric, generic_regnum);2154ABISP abi_sp = m_thread.GetProcess()->GetABI();21552156RegisterValue reg_value;2157// if this is frame 0 (currently executing frame), get the requested reg2158// contents from the actual thread registers2159if (IsFrameZero()) {2160if (m_thread.GetRegisterContext()->ReadRegister(reg_info, reg_value)) {2161value = reg_value.GetAsUInt64();2162if (abi_sp && generic_regnum != LLDB_INVALID_REGNUM) {2163if (generic_regnum == LLDB_REGNUM_GENERIC_PC ||2164generic_regnum == LLDB_REGNUM_GENERIC_RA)2165value = abi_sp->FixCodeAddress(value);2166if (generic_regnum == LLDB_REGNUM_GENERIC_SP ||2167generic_regnum == LLDB_REGNUM_GENERIC_FP)2168value = abi_sp->FixDataAddress(value);2169}2170return true;2171}2172return false;2173}21742175bool pc_register = false;2176if (generic_regnum != LLDB_INVALID_REGNUM &&2177(generic_regnum == LLDB_REGNUM_GENERIC_PC ||2178generic_regnum == LLDB_REGNUM_GENERIC_RA))2179pc_register = true;21802181lldb_private::UnwindLLDB::RegisterLocation regloc;2182if (!m_parent_unwind.SearchForSavedLocationForRegister(2183lldb_regnum, regloc, m_frame_number - 1, pc_register)) {2184return false;2185}2186if (ReadRegisterValueFromRegisterLocation(regloc, reg_info, reg_value)) {2187value = reg_value.GetAsUInt64();2188if (pc_register) {2189if (ABISP abi_sp = m_thread.GetProcess()->GetABI()) {2190value = abi_sp->FixCodeAddress(value);2191}2192}2193return true;2194}2195return false;2196}21972198bool RegisterContextUnwind::ReadGPRValue(const RegisterNumber ®num,2199addr_t &value) {2200return ReadGPRValue(regnum.GetRegisterKind(), regnum.GetRegisterNumber(),2201value);2202}22032204// Find the value of a register in THIS frame22052206bool RegisterContextUnwind::ReadRegister(const RegisterInfo *reg_info,2207RegisterValue &value) {2208if (!IsValid())2209return false;22102211const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];2212UnwindLogMsgVerbose("looking for register saved location for reg %d",2213lldb_regnum);22142215// If this is the 0th frame, hand this over to the live register context2216if (IsFrameZero()) {2217UnwindLogMsgVerbose("passing along to the live register context for reg %d",2218lldb_regnum);2219return m_thread.GetRegisterContext()->ReadRegister(reg_info, value);2220}22212222bool is_pc_regnum = false;2223if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_PC ||2224reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA) {2225is_pc_regnum = true;2226}22272228lldb_private::UnwindLLDB::RegisterLocation regloc;2229// Find out where the NEXT frame saved THIS frame's register contents2230if (!m_parent_unwind.SearchForSavedLocationForRegister(2231lldb_regnum, regloc, m_frame_number - 1, is_pc_regnum))2232return false;22332234bool result = ReadRegisterValueFromRegisterLocation(regloc, reg_info, value);2235if (result) {2236if (is_pc_regnum && value.GetType() == RegisterValue::eTypeUInt64) {2237addr_t reg_value = value.GetAsUInt64(LLDB_INVALID_ADDRESS);2238if (reg_value != LLDB_INVALID_ADDRESS) {2239if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2240value = abi_sp->FixCodeAddress(reg_value);2241}2242}2243}2244return result;2245}22462247bool RegisterContextUnwind::WriteRegister(const RegisterInfo *reg_info,2248const RegisterValue &value) {2249if (!IsValid())2250return false;22512252const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];2253UnwindLogMsgVerbose("looking for register saved location for reg %d",2254lldb_regnum);22552256// If this is the 0th frame, hand this over to the live register context2257if (IsFrameZero()) {2258UnwindLogMsgVerbose("passing along to the live register context for reg %d",2259lldb_regnum);2260return m_thread.GetRegisterContext()->WriteRegister(reg_info, value);2261}22622263lldb_private::UnwindLLDB::RegisterLocation regloc;2264// Find out where the NEXT frame saved THIS frame's register contents2265if (!m_parent_unwind.SearchForSavedLocationForRegister(2266lldb_regnum, regloc, m_frame_number - 1, false))2267return false;22682269return WriteRegisterValueToRegisterLocation(regloc, reg_info, value);2270}22712272// Don't need to implement this one2273bool RegisterContextUnwind::ReadAllRegisterValues(2274lldb::WritableDataBufferSP &data_sp) {2275return false;2276}22772278// Don't need to implement this one2279bool RegisterContextUnwind::WriteAllRegisterValues(2280const lldb::DataBufferSP &data_sp) {2281return false;2282}22832284// Retrieve the pc value for THIS from22852286bool RegisterContextUnwind::GetCFA(addr_t &cfa) {2287if (!IsValid()) {2288return false;2289}2290if (m_cfa == LLDB_INVALID_ADDRESS) {2291return false;2292}2293cfa = m_cfa;2294return true;2295}22962297RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetNextFrame() const {2298RegisterContextUnwind::SharedPtr regctx;2299if (m_frame_number == 0)2300return regctx;2301return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number - 1);2302}23032304RegisterContextUnwind::SharedPtr RegisterContextUnwind::GetPrevFrame() const {2305RegisterContextUnwind::SharedPtr regctx;2306return m_parent_unwind.GetRegisterContextForFrameNum(m_frame_number + 1);2307}23082309// Retrieve the address of the start of the function of THIS frame23102311bool RegisterContextUnwind::GetStartPC(addr_t &start_pc) {2312if (!IsValid())2313return false;23142315if (!m_start_pc.IsValid()) {2316bool read_successfully = ReadPC (start_pc);2317if (read_successfully)2318{2319ProcessSP process_sp (m_thread.GetProcess());2320if (process_sp)2321{2322if (ABISP abi_sp = process_sp->GetABI())2323start_pc = abi_sp->FixCodeAddress(start_pc);2324}2325}2326return read_successfully;2327}2328start_pc = m_start_pc.GetLoadAddress(CalculateTarget().get());2329return true;2330}23312332// Retrieve the current pc value for THIS frame, as saved by the NEXT frame.23332334bool RegisterContextUnwind::ReadPC(addr_t &pc) {2335if (!IsValid())2336return false;23372338bool above_trap_handler = false;2339if (GetNextFrame().get() && GetNextFrame()->IsValid() &&2340GetNextFrame()->IsTrapHandlerFrame())2341above_trap_handler = true;23422343if (ReadGPRValue(eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc)) {2344// A pc value of 0 or 1 is impossible in the middle of the stack -- it2345// indicates the end of a stack walk.2346// On the currently executing frame (or such a frame interrupted2347// asynchronously by sigtramp et al) this may occur if code has jumped2348// through a NULL pointer -- we want to be able to unwind past that frame2349// to help find the bug.23502351if (ABISP abi_sp = m_thread.GetProcess()->GetABI())2352pc = abi_sp->FixCodeAddress(pc);23532354return !(m_all_registers_available == false &&2355above_trap_handler == false && (pc == 0 || pc == 1));2356} else {2357return false;2358}2359}23602361void RegisterContextUnwind::UnwindLogMsg(const char *fmt, ...) {2362Log *log = GetLog(LLDBLog::Unwind);2363if (!log)2364return;23652366va_list args;2367va_start(args, fmt);23682369llvm::SmallString<0> logmsg;2370if (VASprintf(logmsg, fmt, args)) {2371LLDB_LOGF(log, "%*sth%d/fr%u %s",2372m_frame_number < 100 ? m_frame_number : 100, "",2373m_thread.GetIndexID(), m_frame_number, logmsg.c_str());2374}2375va_end(args);2376}23772378void RegisterContextUnwind::UnwindLogMsgVerbose(const char *fmt, ...) {2379Log *log = GetLog(LLDBLog::Unwind);2380if (!log || !log->GetVerbose())2381return;23822383va_list args;2384va_start(args, fmt);23852386llvm::SmallString<0> logmsg;2387if (VASprintf(logmsg, fmt, args)) {2388LLDB_LOGF(log, "%*sth%d/fr%u %s",2389m_frame_number < 100 ? m_frame_number : 100, "",2390m_thread.GetIndexID(), m_frame_number, logmsg.c_str());2391}2392va_end(args);2393}239423952396