RegisterContextLLDB.cpp revision 269024
1107002Sschweikh//===-- RegisterContextLLDB.cpp --------------------------------*- C++ -*-===//
2174422Sdougb//
3174425Sdougb//                     The LLVM Compiler Infrastructure
4174425Sdougb//
5174425Sdougb// This file is distributed under the University of Illinois Open Source
6174425Sdougb// License. See LICENSE.TXT for details.
7174425Sdougb//
8174425Sdougb//===----------------------------------------------------------------------===//
9174425Sdougb
10174425Sdougb
11174425Sdougb#include "lldb/lldb-private.h"
12174425Sdougb#include "lldb/Core/Address.h"
13174425Sdougb#include "lldb/Core/AddressRange.h"
14174425Sdougb#include "lldb/Core/DataBufferHeap.h"
15174425Sdougb#include "lldb/Core/Log.h"
16174425Sdougb#include "lldb/Core/Module.h"
17174425Sdougb#include "lldb/Core/RegisterValue.h"
18174425Sdougb#include "lldb/Core/Value.h"
19174425Sdougb#include "lldb/Expression/DWARFExpression.h"
20174425Sdougb#include "lldb/Symbol/DWARFCallFrameInfo.h"
21174425Sdougb#include "lldb/Symbol/FuncUnwinders.h"
22174425Sdougb#include "lldb/Symbol/Function.h"
23174425Sdougb#include "lldb/Symbol/ObjectFile.h"
24174425Sdougb#include "lldb/Symbol/Symbol.h"
25174425Sdougb#include "lldb/Symbol/SymbolContext.h"
26174425Sdougb#include "lldb/Target/ABI.h"
27174425Sdougb#include "lldb/Target/DynamicLoader.h"
28174425Sdougb#include "lldb/Target/ExecutionContext.h"
29174425Sdougb#include "lldb/Target/Platform.h"
30174425Sdougb#include "lldb/Target/Process.h"
31174425Sdougb#include "lldb/Target/SectionLoadList.h"
32174425Sdougb#include "lldb/Target/StackFrame.h"
33174425Sdougb#include "lldb/Target/Target.h"
34174425Sdougb#include "lldb/Target/Thread.h"
35174425Sdougb
36174425Sdougb#include "RegisterContextLLDB.h"
37174425Sdougb
38174425Sdougbusing namespace lldb;
39174425Sdougbusing namespace lldb_private;
40174425Sdougb
41174425SdougbRegisterContextLLDB::RegisterContextLLDB
42174425Sdougb(
43174425Sdougb    Thread& thread,
44174425Sdougb    const SharedPtr &next_frame,
45174425Sdougb    SymbolContext& sym_ctx,
46174425Sdougb    uint32_t frame_number,
47174425Sdougb    UnwindLLDB& unwind_lldb
48174425Sdougb) :
49174425Sdougb    RegisterContext (thread, frame_number),
50174425Sdougb    m_thread(thread),
51174425Sdougb    m_fast_unwind_plan_sp (),
52174425Sdougb    m_full_unwind_plan_sp (),
53174425Sdougb    m_fallback_unwind_plan_sp (),
54174425Sdougb    m_all_registers_available(false),
55174425Sdougb    m_frame_type (-1),
56174425Sdougb    m_cfa (LLDB_INVALID_ADDRESS),
57174425Sdougb    m_start_pc (),
58174425Sdougb    m_current_pc (),
59174425Sdougb    m_current_offset (0),
60174425Sdougb    m_current_offset_backed_up_one (0),
61174425Sdougb    m_sym_ctx(sym_ctx),
62174425Sdougb    m_sym_ctx_valid (false),
63174425Sdougb    m_frame_number (frame_number),
64174425Sdougb    m_registers(),
65174425Sdougb    m_parent_unwind (unwind_lldb)
66174425Sdougb{
67174425Sdougb    m_sym_ctx.Clear(false);
68174425Sdougb    m_sym_ctx_valid = false;
69174425Sdougb
70174425Sdougb    if (IsFrameZero ())
71174425Sdougb    {
72174425Sdougb        InitializeZerothFrame ();
73174425Sdougb    }
74174425Sdougb    else
75174425Sdougb    {
76174425Sdougb        InitializeNonZerothFrame ();
77174425Sdougb    }
78174425Sdougb
79174425Sdougb    // This same code exists over in the GetFullUnwindPlanForFrame() but it may not have been executed yet
80174425Sdougb    if (IsFrameZero()
81174425Sdougb        || next_frame->m_frame_type == eTrapHandlerFrame
82174425Sdougb        || next_frame->m_frame_type == eDebuggerFrame)
83174425Sdougb    {
84174425Sdougb        m_all_registers_available = true;
85174425Sdougb    }
86174425Sdougb}
87174425Sdougb
88174425Sdougbbool
89174425SdougbRegisterContextLLDB::IsUnwindPlanValidForCurrentPC(lldb::UnwindPlanSP unwind_plan_sp, int &valid_pc_offset)
90174425Sdougb{
91174425Sdougb    if (!unwind_plan_sp)
92174425Sdougb        return false;
93174425Sdougb
94174425Sdougb    // check if m_current_pc is valid
95174425Sdougb    if (unwind_plan_sp->PlanValidAtAddress(m_current_pc))
96174425Sdougb    {
97174425Sdougb        // yes - current offset can be used as is
98174425Sdougb        valid_pc_offset = m_current_offset;
99174425Sdougb        return true;
100174425Sdougb    }
101174425Sdougb
102174425Sdougb    // if m_current_offset <= 0, we've got nothing else to try
103174425Sdougb    if (m_current_offset <= 0)
104174425Sdougb        return false;
105174425Sdougb
1062490Sjkh    // check pc - 1 to see if it's valid
1072490Sjkh    Address pc_minus_one (m_current_pc);
1082490Sjkh    pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);
1092490Sjkh    if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one))
1102490Sjkh    {
1112490Sjkh        // *valid_pc_offset = m_current_offset - 1;
1122490Sjkh        valid_pc_offset = m_current_pc.GetOffset() - 1;
1132490Sjkh        return true;
1142490Sjkh    }
1152490Sjkh
1162490Sjkh    return false;
1172490Sjkh}
1182490Sjkh
1192490Sjkh// Initialize a RegisterContextLLDB which is the first frame of a stack -- the zeroth frame or currently
1202490Sjkh// executing frame.
1212490Sjkh
1222490Sjkhvoid
1232490SjkhRegisterContextLLDB::InitializeZerothFrame()
1242490Sjkh{
1252490Sjkh    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1262490Sjkh    ExecutionContext exe_ctx(m_thread.shared_from_this());
1272490Sjkh    RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();
1282490Sjkh
1292490Sjkh    if (reg_ctx_sp.get() == NULL)
1302490Sjkh    {
1312490Sjkh        m_frame_type = eNotAValidFrame;
1322490Sjkh        UnwindLogMsg ("frame does not have a register context");
1332490Sjkh        return;
1342490Sjkh    }
1352490Sjkh
1362490Sjkh    addr_t current_pc = reg_ctx_sp->GetPC();
1372490Sjkh
1382490Sjkh    if (current_pc == LLDB_INVALID_ADDRESS)
1392490Sjkh    {
1402490Sjkh        m_frame_type = eNotAValidFrame;
1412490Sjkh        UnwindLogMsg ("frame does not have a pc");
1422490Sjkh        return;
1432490Sjkh    }
1442490Sjkh
1452490Sjkh    Process *process = exe_ctx.GetProcessPtr();
1462490Sjkh
1472490Sjkh    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
1482490Sjkh    // this will strip bit zero in case we read a PC from memory or from the LR.
1492490Sjkh    // (which would be a no-op in frame 0 where we get it from the register set,
1502490Sjkh    // but still a good idea to make the call here for other ABIs that may exist.)
1512490Sjkh    ABI *abi = process->GetABI().get();
1522490Sjkh    if (abi)
1532490Sjkh        current_pc = abi->FixCodeAddress(current_pc);
1542490Sjkh
1552490Sjkh    // Initialize m_current_pc, an Address object, based on current_pc, an addr_t.
1562490Sjkh    m_current_pc.SetLoadAddress (current_pc, &process->GetTarget());
1572490Sjkh
1582490Sjkh    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
1592490Sjkh    // stick in some reasonable defaults and hope we can unwind past this frame.
1602490Sjkh    ModuleSP pc_module_sp (m_current_pc.GetModule());
1612490Sjkh    if (!m_current_pc.IsValid() || !pc_module_sp)
1622490Sjkh    {
1632490Sjkh        UnwindLogMsg ("using architectural default unwind method");
1642490Sjkh    }
1652490Sjkh
1662490Sjkh    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
1672490Sjkh    if (pc_module_sp.get()
168162709Sschweikh        && (pc_module_sp->ResolveSymbolContextForAddress (m_current_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
1692490Sjkh    {
1702490Sjkh        m_sym_ctx_valid = true;
1712490Sjkh    }
1722490Sjkh
1732490Sjkh    AddressRange addr_range;
1742490Sjkh    m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range);
1752490Sjkh
1762490Sjkh    if (IsTrapHandlerSymbol (process, m_sym_ctx))
1772490Sjkh    {
1782490Sjkh        m_frame_type = eTrapHandlerFrame;
1792490Sjkh    }
1802490Sjkh    else
1812490Sjkh    {
1822490Sjkh        // FIXME:  Detect eDebuggerFrame here.
1832490Sjkh        m_frame_type = eNormalFrame;
184174425Sdougb    }
185174425Sdougb
186174425Sdougb    // If we were able to find a symbol/function, set addr_range to the bounds of that symbol/function.
1872490Sjkh    // else treat the current pc value as the start_pc and record no offset.
1882490Sjkh    if (addr_range.GetBaseAddress().IsValid())
1892490Sjkh    {
1902490Sjkh        m_start_pc = addr_range.GetBaseAddress();
1912490Sjkh        if (m_current_pc.GetSection() == m_start_pc.GetSection())
1922490Sjkh        {
1932490Sjkh            m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
1942490Sjkh        }
1952490Sjkh        else if (m_current_pc.GetModule() == m_start_pc.GetModule())
1962490Sjkh        {
1972490Sjkh            // This means that whatever symbol we kicked up isn't really correct
1982490Sjkh            // --- we should not cross section boundaries ... We really should NULL out
1992490Sjkh            // the function/symbol in this case unless there is a bad assumption
2002490Sjkh            // here due to inlined functions?
2012490Sjkh            m_current_offset = m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();
2022490Sjkh        }
2032490Sjkh        m_current_offset_backed_up_one = m_current_offset;
2042490Sjkh    }
2052490Sjkh    else
2062490Sjkh    {
2072490Sjkh        m_start_pc = m_current_pc;
2082490Sjkh        m_current_offset = -1;
2092490Sjkh        m_current_offset_backed_up_one = -1;
2102490Sjkh    }
2112490Sjkh
2122490Sjkh    // We've set m_frame_type and m_sym_ctx before these calls.
2132490Sjkh
2142490Sjkh    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
2152490Sjkh    m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
2162490Sjkh
2172490Sjkh    UnwindPlan::RowSP active_row;
2182490Sjkh    int cfa_offset = 0;
2192490Sjkh    int row_register_kind = -1;
2202490Sjkh    if (m_full_unwind_plan_sp && m_full_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
2212490Sjkh    {
2222490Sjkh        active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
2232490Sjkh        row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
2242490Sjkh        if (active_row.get() && log)
2252490Sjkh        {
226174425Sdougb            StreamString active_row_strm;
227174425Sdougb            active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
228174425Sdougb            UnwindLogMsg ("%s", active_row_strm.GetString().c_str());
2292490Sjkh        }
2302490Sjkh    }
2312490Sjkh
2322490Sjkh    if (!active_row.get())
2332490Sjkh    {
2342490Sjkh        UnwindLogMsg ("could not find an unwindplan row for this frame's pc");
2352490Sjkh        m_frame_type = eNotAValidFrame;
2362490Sjkh        return;
2372490Sjkh    }
2382490Sjkh
2392490Sjkh
2402490Sjkh    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
2412490Sjkh    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
2422490Sjkh    {
2432490Sjkh        UnwindLogMsg ("could not read CFA register for this frame.");
2442490Sjkh        m_frame_type = eNotAValidFrame;
2452490Sjkh        return;
2462490Sjkh    }
2472490Sjkh
2482490Sjkh    cfa_offset = active_row->GetCFAOffset ();
2492490Sjkh    m_cfa = cfa_regval + cfa_offset;
2502490Sjkh
2512490Sjkh    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
2522490Sjkh    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64 " using %s UnwindPlan",
2532490Sjkh            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()),
2542490Sjkh            (uint64_t) m_cfa,
2552490Sjkh            m_full_unwind_plan_sp->GetSourceName().GetCString());
2562490Sjkh}
2572490Sjkh
2582490Sjkh// Initialize a RegisterContextLLDB for the non-zeroth frame -- rely on the RegisterContextLLDB "below" it
2592490Sjkh// to provide things like its current pc value.
2602490Sjkh
2612490Sjkhvoid
2622490SjkhRegisterContextLLDB::InitializeNonZerothFrame()
2632490Sjkh{
2642490Sjkh    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
2652490Sjkh    if (IsFrameZero ())
2662490Sjkh    {
2672490Sjkh        m_frame_type = eNotAValidFrame;
2682490Sjkh        UnwindLogMsg ("non-zeroth frame tests positive for IsFrameZero -- that shouldn't happen.");
2692490Sjkh        return;
2702490Sjkh    }
2712490Sjkh
2722490Sjkh    if (!GetNextFrame().get() || !GetNextFrame()->IsValid())
2732490Sjkh    {
2742490Sjkh        m_frame_type = eNotAValidFrame;
2752490Sjkh        UnwindLogMsg ("Could not get next frame, marking this frame as invalid.");
2762490Sjkh        return;
2772490Sjkh    }
2782490Sjkh    if (!m_thread.GetRegisterContext())
2792490Sjkh    {
2802490Sjkh        m_frame_type = eNotAValidFrame;
2812490Sjkh        UnwindLogMsg ("Could not get register context for this thread, marking this frame as invalid.");
2822490Sjkh        return;
2832490Sjkh    }
2842490Sjkh
2852490Sjkh    addr_t pc;
2862490Sjkh    if (!ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
287174425Sdougb    {
288174425Sdougb        UnwindLogMsg ("could not get pc value");
289174425Sdougb        m_frame_type = eNotAValidFrame;
290174425Sdougb        return;
291174425Sdougb    }
292174425Sdougb
2932490Sjkh    if (log)
2942490Sjkh    {
2952490Sjkh        UnwindLogMsg ("pc = 0x%16.16" PRIx64, pc);
2962490Sjkh        addr_t reg_val;
2972490Sjkh        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))
2982490Sjkh            UnwindLogMsg ("fp = 0x%16.16" PRIx64, reg_val);
2992490Sjkh        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))
3002490Sjkh            UnwindLogMsg ("sp = 0x%16.16" PRIx64, reg_val);
3012490Sjkh    }
3022490Sjkh
3032490Sjkh    // A pc of 0x0 means it's the end of the stack crawl
3042490Sjkh    if (pc == 0)
3052490Sjkh    {
3062490Sjkh        m_frame_type = eNotAValidFrame;
3072490Sjkh        UnwindLogMsg ("this frame has a pc of 0x0");
3082490Sjkh        return;
3092490Sjkh    }
3102490Sjkh
3112490Sjkh    ExecutionContext exe_ctx(m_thread.shared_from_this());
3122490Sjkh    Process *process = exe_ctx.GetProcessPtr();
3132490Sjkh    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
3142490Sjkh    // this will strip bit zero in case we read a PC from memory or from the LR.
3152490Sjkh    ABI *abi = process->GetABI().get();
3162490Sjkh    if (abi)
3172490Sjkh        pc = abi->FixCodeAddress(pc);
3182490Sjkh
3192490Sjkh    m_current_pc.SetLoadAddress (pc, &process->GetTarget());
3202490Sjkh
3212490Sjkh    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
3222490Sjkh    // stick in some reasonable defaults and hope we can unwind past this frame.
3232490Sjkh    ModuleSP pc_module_sp (m_current_pc.GetModule());
3242490Sjkh    if (!m_current_pc.IsValid() || !pc_module_sp)
3252490Sjkh    {
3262490Sjkh        UnwindLogMsg ("using architectural default unwind method");
3272490Sjkh
3282490Sjkh        // Test the pc value to see if we know it's in an unmapped/non-executable region of memory.
3292490Sjkh        uint32_t permissions;
3302490Sjkh        if (process->GetLoadAddressPermissions(pc, permissions)
3312490Sjkh            && (permissions & ePermissionsExecutable) == 0)
3322490Sjkh        {
3332490Sjkh            // If this is the second frame off the stack, we may have unwound the first frame
3342490Sjkh            // incorrectly.  But using the architecture default unwind plan may get us back on
3352490Sjkh            // track -- albeit possibly skipping a real frame.  Give this frame a clearly-invalid
3362490Sjkh            // pc and see if we can get any further.
337149634Sschweikh            if (GetNextFrame().get() && GetNextFrame()->IsValid() && GetNextFrame()->IsFrameZero())
338149634Sschweikh            {
3392490Sjkh                UnwindLogMsg ("had a pc of 0x%" PRIx64 " which is not in executable memory but on frame 1 -- allowing it once.",
3402490Sjkh                         (uint64_t) pc);
3412490Sjkh                m_frame_type = eSkipFrame;
3422490Sjkh            }
3432490Sjkh            else
3442490Sjkh            {
3452490Sjkh                // anywhere other than the second frame, a non-executable pc means we're off in the weeds -- stop now.
346174425Sdougb                m_frame_type = eNotAValidFrame;
347174425Sdougb                UnwindLogMsg ("pc is in a non-executable section of memory and this isn't the 2nd frame in the stack walk.");
3482490Sjkh                return;
3492490Sjkh            }
3502490Sjkh        }
3512490Sjkh
3522490Sjkh        if (abi)
3532490Sjkh        {
3542490Sjkh            m_fast_unwind_plan_sp.reset ();
3552490Sjkh            m_full_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
3562490Sjkh            abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);
3572490Sjkh            if (m_frame_type != eSkipFrame)  // don't override eSkipFrame
3582490Sjkh            {
3592490Sjkh                m_frame_type = eNormalFrame;
3602490Sjkh            }
3612490Sjkh            m_all_registers_available = false;
3622490Sjkh            m_current_offset = -1;
3632490Sjkh            m_current_offset_backed_up_one = -1;
3642490Sjkh            addr_t cfa_regval = LLDB_INVALID_ADDRESS;
3652490Sjkh            int row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
3662490Sjkh            UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);
3672490Sjkh            if (row.get())
3682490Sjkh            {
3692490Sjkh                uint32_t cfa_regnum = row->GetCFARegister();
3702490Sjkh                int cfa_offset = row->GetCFAOffset();
3712490Sjkh                if (!ReadGPRValue (row_register_kind, cfa_regnum, cfa_regval))
3722490Sjkh                {
3732490Sjkh                    UnwindLogMsg ("failed to get cfa value");
3742490Sjkh                    if (m_frame_type != eSkipFrame)   // don't override eSkipFrame
3752490Sjkh                    {
3762490Sjkh                        m_frame_type = eNormalFrame;
3772490Sjkh                    }
378174422Sdougb                    return;
3792490Sjkh                }
3802490Sjkh                m_cfa = cfa_regval + cfa_offset;
3812490Sjkh
3822490Sjkh                // A couple of sanity checks..
3832490Sjkh                if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
3842490Sjkh                {
3852490Sjkh                    UnwindLogMsg ("could not find a valid cfa address");
3862490Sjkh                    m_frame_type = eNotAValidFrame;
3872490Sjkh                    return;
3882490Sjkh                }
3892490Sjkh
3902490Sjkh                // cfa_regval should point into the stack memory; if we can query memory region permissions,
3912490Sjkh                // see if the memory is allocated & readable.
3922490Sjkh                if (process->GetLoadAddressPermissions(cfa_regval, permissions)
3932490Sjkh                    && (permissions & ePermissionsReadable) == 0)
3942490Sjkh                {
3952490Sjkh                    m_frame_type = eNotAValidFrame;
3962490Sjkh                    UnwindLogMsg ("the CFA points to a region of memory that is not readable");
3972490Sjkh                    return;
3982490Sjkh                }
3992490Sjkh            }
4002490Sjkh            else
4012490Sjkh            {
4022490Sjkh                UnwindLogMsg ("could not find a row for function offset zero");
4032490Sjkh                m_frame_type = eNotAValidFrame;
4042490Sjkh                return;
4052490Sjkh            }
4062490Sjkh
4072490Sjkh            UnwindLogMsg ("initialized frame cfa is 0x%" PRIx64, (uint64_t) m_cfa);
4082490Sjkh            return;
4092490Sjkh        }
4102490Sjkh        m_frame_type = eNotAValidFrame;
4112490Sjkh        UnwindLogMsg ("could not find any symbol for this pc, or a default unwind plan, to continue unwind.");
4122490Sjkh        return;
4132490Sjkh    }
4142490Sjkh
4152490Sjkh    bool resolve_tail_call_address = true; // m_current_pc can be one past the address range of the function...
4162490Sjkh                                           // This will handle the case where the saved pc does not point to
4172490Sjkh                                           // a function/symbol because it is beyond the bounds of the correct
4182490Sjkh                                           // function and there's no symbol there.  ResolveSymbolContextForAddress
4192490Sjkh                                           // will fail to find a symbol, back up the pc by 1 and re-search.
4202490Sjkh    uint32_t resolved_scope = pc_module_sp->ResolveSymbolContextForAddress (m_current_pc,
4212490Sjkh                                                                            eSymbolContextFunction | eSymbolContextSymbol,
4222490Sjkh                                                                            m_sym_ctx, resolve_tail_call_address);
4232490Sjkh
4242490Sjkh    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
4252490Sjkh    if ((resolved_scope & eSymbolContextSymbol) == eSymbolContextSymbol)
4262490Sjkh    {
4272490Sjkh        m_sym_ctx_valid = true;
4282490Sjkh    }
4292490Sjkh
4302490Sjkh    AddressRange addr_range;
4312490Sjkh    if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
4322490Sjkh    {
4332490Sjkh        m_sym_ctx_valid = false;
4342490Sjkh    }
4352490Sjkh
4362490Sjkh    bool decr_pc_and_recompute_addr_range = false;
437108666Sschweikh
4382490Sjkh    // If the symbol lookup failed...
4392490Sjkh    if (m_sym_ctx_valid == false)
4402490Sjkh       decr_pc_and_recompute_addr_range = true;
4412490Sjkh
4422490Sjkh    // Or if we're in the middle of the stack (and not "above" an asynchronous event like sigtramp),
4432490Sjkh    // and our "current" pc is the start of a function...
4442490Sjkh    if (m_sym_ctx_valid
4452490Sjkh        && GetNextFrame()->m_frame_type != eTrapHandlerFrame
4462490Sjkh        && GetNextFrame()->m_frame_type != eDebuggerFrame
4472490Sjkh        && addr_range.GetBaseAddress().IsValid()
4482490Sjkh        && addr_range.GetBaseAddress().GetSection() == m_current_pc.GetSection()
4492490Sjkh        && addr_range.GetBaseAddress().GetOffset() == m_current_pc.GetOffset())
4502490Sjkh    {
4512490Sjkh        decr_pc_and_recompute_addr_range = true;
4522490Sjkh    }
4532490Sjkh
4542490Sjkh    // We need to back up the pc by 1 byte and re-search for the Symbol to handle the case where the "saved pc"
4552490Sjkh    // value is pointing to the next function, e.g. if a function ends with a CALL instruction.
4562490Sjkh    // FIXME this may need to be an architectural-dependent behavior; if so we'll need to add a member function
4572490Sjkh    // to the ABI plugin and consult that.
4582490Sjkh    if (decr_pc_and_recompute_addr_range)
4592490Sjkh    {
4602490Sjkh        Address temporary_pc(m_current_pc);
4612490Sjkh        temporary_pc.SetOffset(m_current_pc.GetOffset() - 1);
4622490Sjkh        m_sym_ctx.Clear(false);
4632490Sjkh        m_sym_ctx_valid = false;
4642490Sjkh        if ((pc_module_sp->ResolveSymbolContextForAddress (temporary_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
4652490Sjkh        {
4662490Sjkh            m_sym_ctx_valid = true;
4672490Sjkh        }
4682490Sjkh        if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false,  addr_range))
4692490Sjkh        {
4702490Sjkh            m_sym_ctx_valid = false;
4712490Sjkh        }
4722490Sjkh    }
4732490Sjkh
4742490Sjkh    // If we were able to find a symbol/function, set addr_range_ptr to the bounds of that symbol/function.
4752490Sjkh    // else treat the current pc value as the start_pc and record no offset.
4762490Sjkh    if (addr_range.GetBaseAddress().IsValid())
4772490Sjkh    {
4782490Sjkh        m_start_pc = addr_range.GetBaseAddress();
4792490Sjkh        m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
4802490Sjkh        m_current_offset_backed_up_one = m_current_offset;
4812490Sjkh        if (decr_pc_and_recompute_addr_range && m_current_offset_backed_up_one > 0)
4822490Sjkh        {
4832490Sjkh            m_current_offset_backed_up_one--;
4842490Sjkh            if (m_sym_ctx_valid)
4852490Sjkh                m_current_pc.SetOffset(m_current_pc.GetOffset() - 1);
4862490Sjkh        }
4872490Sjkh    }
4882490Sjkh    else
4892490Sjkh    {
4902490Sjkh        m_start_pc = m_current_pc;
4912490Sjkh        m_current_offset = -1;
4922490Sjkh        m_current_offset_backed_up_one = -1;
4932490Sjkh    }
4942490Sjkh
4952490Sjkh    if (IsTrapHandlerSymbol (process, m_sym_ctx))
4962490Sjkh    {
4972490Sjkh        m_frame_type = eTrapHandlerFrame;
4982490Sjkh    }
4992490Sjkh    else
5002490Sjkh    {
5012490Sjkh        // FIXME:  Detect eDebuggerFrame here.
5022490Sjkh        if (m_frame_type != eSkipFrame) // don't override eSkipFrame
5032490Sjkh        {
5042490Sjkh            m_frame_type = eNormalFrame;
5052490Sjkh        }
5062490Sjkh    }
5072490Sjkh
5082490Sjkh    // We've set m_frame_type and m_sym_ctx before this call.
5092490Sjkh    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
510205995Suqs
5112490Sjkh    UnwindPlan::RowSP active_row;
5122490Sjkh    int cfa_offset = 0;
5132490Sjkh    int row_register_kind = -1;
5142490Sjkh
5152490Sjkh    // Try to get by with just the fast UnwindPlan if possible - the full UnwindPlan may be expensive to get
5162490Sjkh    // (e.g. if we have to parse the entire eh_frame section of an ObjectFile for the first time.)
5172490Sjkh
5182490Sjkh    if (m_fast_unwind_plan_sp && m_fast_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
5192490Sjkh    {
5202490Sjkh        active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
5212490Sjkh        row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind ();
5222490Sjkh        if (active_row.get() && log)
5232490Sjkh        {
5242490Sjkh            StreamString active_row_strm;
5252490Sjkh            active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
5262490Sjkh            UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
5272490Sjkh        }
5282490Sjkh    }
5292490Sjkh    else
5302490Sjkh    {
5312490Sjkh        m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
5322490Sjkh        int valid_offset = -1;
5332490Sjkh        if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset))
5342490Sjkh        {
5352490Sjkh            active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (valid_offset);
5362490Sjkh            row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
5372490Sjkh            if (active_row.get() && log)
5382490Sjkh            {
5392490Sjkh                StreamString active_row_strm;
5402490Sjkh                active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
5412490Sjkh                UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
5422490Sjkh            }
5432490Sjkh        }
5442490Sjkh    }
5452490Sjkh
5462490Sjkh    if (!active_row.get())
5472490Sjkh    {
5482490Sjkh        m_frame_type = eNotAValidFrame;
5492490Sjkh        UnwindLogMsg ("could not find unwind row for this pc");
5502490Sjkh        return;
5512490Sjkh    }
5522490Sjkh
553145472Sschweikh    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
5542490Sjkh    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
5552490Sjkh    {
5562490Sjkh        UnwindLogMsg ("failed to get cfa reg %d/%d", row_register_kind, active_row->GetCFARegister());
5572490Sjkh        m_frame_type = eNotAValidFrame;
5582490Sjkh        return;
5592490Sjkh    }
5602490Sjkh
5612490Sjkh    cfa_offset = active_row->GetCFAOffset ();
5622490Sjkh    m_cfa = cfa_regval + cfa_offset;
5632490Sjkh
5642490Sjkh    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
5652490Sjkh
5662490Sjkh    // A couple of sanity checks..
5672490Sjkh    if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
5682490Sjkh    {
5692490Sjkh        UnwindLogMsg ("could not find a valid cfa address");
5702490Sjkh        m_frame_type = eNotAValidFrame;
5712490Sjkh        return;
5722490Sjkh    }
5732490Sjkh
5742490Sjkh    // If we have a bad stack setup, we can get the same CFA value multiple times -- or even
5752490Sjkh    // more devious, we can actually oscillate between two CFA values.  Detect that here and
5762490Sjkh    // break out to avoid a possible infinite loop in lldb trying to unwind the stack.
5772490Sjkh    addr_t next_frame_cfa;
5782490Sjkh    addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;
5792490Sjkh    if (GetNextFrame().get() && GetNextFrame()->GetCFA(next_frame_cfa))
5802490Sjkh    {
5812490Sjkh        bool repeating_frames = false;
5822490Sjkh        if (next_frame_cfa == m_cfa)
5832490Sjkh        {
5842490Sjkh            repeating_frames = true;
5852490Sjkh        }
5862490Sjkh        else
5872490Sjkh        {
5882490Sjkh            if (GetNextFrame()->GetNextFrame() && GetNextFrame()->GetNextFrame()->GetCFA(next_next_frame_cfa)
5892490Sjkh                && next_next_frame_cfa == m_cfa)
5902490Sjkh            {
5912490Sjkh                repeating_frames = true;
5922490Sjkh            }
5932490Sjkh        }
5942490Sjkh        if (repeating_frames && abi->FunctionCallsChangeCFA())
5952490Sjkh        {
5962490Sjkh            UnwindLogMsg ("same CFA address as next frame, assuming the unwind is looping - stopping");
5972490Sjkh            m_frame_type = eNotAValidFrame;
5982490Sjkh            return;
5992490Sjkh        }
6002490Sjkh    }
6012490Sjkh
6022490Sjkh    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64,
6032490Sjkh            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()), (uint64_t) m_cfa);
6042490Sjkh}
6052490Sjkh
6062490Sjkh
6072490Sjkhbool
6082490SjkhRegisterContextLLDB::IsFrameZero () const
6092490Sjkh{
6102490Sjkh    return m_frame_number == 0;
6112490Sjkh}
6122490Sjkh
6132490Sjkh
6142490Sjkh// Find a fast unwind plan for this frame, if possible.
6152490Sjkh//
6162490Sjkh// On entry to this method,
6172490Sjkh//
6182490Sjkh//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
6192490Sjkh//   2. m_sym_ctx should already be filled in, and
6202490Sjkh//   3. m_current_pc should have the current pc value for this frame
6212490Sjkh//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
6222490Sjkh
6232490SjkhUnwindPlanSP
6242490SjkhRegisterContextLLDB::GetFastUnwindPlanForFrame ()
6252490Sjkh{
626174425Sdougb    UnwindPlanSP unwind_plan_sp;
627174425Sdougb    ModuleSP pc_module_sp (m_current_pc.GetModule());
628174425Sdougb
629174425Sdougb    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
630174425Sdougb        return unwind_plan_sp;
631174425Sdougb
6322490Sjkh    if (IsFrameZero ())
6332490Sjkh        return unwind_plan_sp;
6342490Sjkh
6352490Sjkh    FuncUnwindersSP func_unwinders_sp (pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx));
6362490Sjkh    if (!func_unwinders_sp)
6372490Sjkh        return unwind_plan_sp;
6382490Sjkh
6392490Sjkh    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.
6402490Sjkh    if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)
6412490Sjkh        return unwind_plan_sp;
6422490Sjkh
6432490Sjkh    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind (m_thread);
6442490Sjkh    if (unwind_plan_sp)
6452490Sjkh    {
6462490Sjkh        if (unwind_plan_sp->PlanValidAtAddress (m_current_pc))
6472490Sjkh        {
6482490Sjkh            Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
6492490Sjkh            if (log && log->GetVerbose())
6502490Sjkh            {
6512490Sjkh                if (m_fast_unwind_plan_sp)
6522490Sjkh                    UnwindLogMsgVerbose ("frame, and has a fast UnwindPlan");
6532490Sjkh                else
6542490Sjkh                    UnwindLogMsgVerbose ("frame");
6552490Sjkh            }
6562490Sjkh            m_frame_type = eNormalFrame;
6572490Sjkh            return unwind_plan_sp;
6582490Sjkh        }
6592490Sjkh        else
660205995Suqs        {
6612490Sjkh            unwind_plan_sp.reset();
6622490Sjkh        }
6632490Sjkh    }
6642490Sjkh    return unwind_plan_sp;
6652490Sjkh}
6662490Sjkh
6672490Sjkh// On entry to this method,
6682490Sjkh//
6692490Sjkh//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
6702490Sjkh//   2. m_sym_ctx should already be filled in, and
6712490Sjkh//   3. m_current_pc should have the current pc value for this frame
6722490Sjkh//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
6732490Sjkh
6742490SjkhUnwindPlanSP
6752490SjkhRegisterContextLLDB::GetFullUnwindPlanForFrame ()
6762490Sjkh{
6772490Sjkh    UnwindPlanSP unwind_plan_sp;
6782490Sjkh    UnwindPlanSP arch_default_unwind_plan_sp;
6792490Sjkh    ExecutionContext exe_ctx(m_thread.shared_from_this());
6802490Sjkh    Process *process = exe_ctx.GetProcessPtr();
6812490Sjkh    ABI *abi = process ? process->GetABI().get() : NULL;
6822490Sjkh    if (abi)
6832490Sjkh    {
6842490Sjkh        arch_default_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
6852490Sjkh        abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);
6862490Sjkh    }
6872490Sjkh    else
6882490Sjkh    {
6892490Sjkh        UnwindLogMsg ("unable to get architectural default UnwindPlan from ABI plugin");
6902490Sjkh    }
6912490Sjkh
6922490Sjkh    bool behaves_like_zeroth_frame = false;
693205995Suqs    if (IsFrameZero ()
6942490Sjkh        || GetNextFrame()->m_frame_type == eTrapHandlerFrame
6952490Sjkh        || GetNextFrame()->m_frame_type == eDebuggerFrame)
6962490Sjkh    {
6972490Sjkh        behaves_like_zeroth_frame = true;
6982490Sjkh        // If this frame behaves like a 0th frame (currently executing or
6992490Sjkh        // interrupted asynchronously), all registers can be retrieved.
7002490Sjkh        m_all_registers_available = true;
7012490Sjkh    }
7022490Sjkh
7032490Sjkh    // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer) so the pc is 0x0
7042490Sjkh    // in the zeroth frame, we need to use the "unwind at first instruction" arch default UnwindPlan
7052490Sjkh    // Also, if this Process can report on memory region attributes, any non-executable region means
7062490Sjkh    // we jumped through a bad function pointer - handle the same way as 0x0.
707174425Sdougb    // Note, if we have a symbol context & a symbol, we don't want to follow this code path.  This is
708174425Sdougb    // for jumping to memory regions without any information available.
709174425Sdougb
7102490Sjkh    if ((!m_sym_ctx_valid || m_sym_ctx.symbol == NULL) && behaves_like_zeroth_frame && m_current_pc.IsValid())
7112490Sjkh    {
7122490Sjkh        uint32_t permissions;
7132490Sjkh        addr_t current_pc_addr = m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr());
7142490Sjkh        if (current_pc_addr == 0
7152490Sjkh            || (process->GetLoadAddressPermissions (current_pc_addr, permissions)
7162490Sjkh                && (permissions & ePermissionsExecutable) == 0))
7172490Sjkh        {
7182490Sjkh            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
7192490Sjkh            abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);
7202490Sjkh            m_frame_type = eNormalFrame;
7212490Sjkh            return unwind_plan_sp;
7222490Sjkh        }
7232490Sjkh    }
7242490Sjkh
7252490Sjkh    // No Module for the current pc, try using the architecture default unwind.
7262490Sjkh    ModuleSP pc_module_sp (m_current_pc.GetModule());
7272490Sjkh    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
7282490Sjkh    {
7292490Sjkh        m_frame_type = eNormalFrame;
7302490Sjkh        return arch_default_unwind_plan_sp;
7312490Sjkh    }
7322490Sjkh
7332490Sjkh    FuncUnwindersSP func_unwinders_sp;
7342490Sjkh    if (m_sym_ctx_valid)
7352490Sjkh    {
7362490Sjkh        func_unwinders_sp = pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
7372490Sjkh    }
7382490Sjkh
7392490Sjkh    // No FuncUnwinders available for this pc (i.e. a stripped function symbol and -fomit-frame-pointer).
7402490Sjkh    // Try using the eh_frame information relative to the current PC,
7412490Sjkh    // and finally fall back on the architectural default unwind.
7422490Sjkh    if (!func_unwinders_sp)
7432490Sjkh    {
7442490Sjkh        DWARFCallFrameInfo *eh_frame = pc_module_sp && pc_module_sp->GetObjectFile() ?
7452490Sjkh            pc_module_sp->GetObjectFile()->GetUnwindTable().GetEHFrameInfo() : nullptr;
7462490Sjkh
7472490Sjkh        m_frame_type = eNormalFrame;
7482490Sjkh        if (eh_frame && m_current_pc.IsValid())
7492490Sjkh        {
7502490Sjkh            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
7512490Sjkh            // Even with -fomit-frame-pointer, we can try eh_frame to get back on track.
7522490Sjkh            if (eh_frame->GetUnwindPlan (m_current_pc, *unwind_plan_sp))
7532490Sjkh                return unwind_plan_sp;
7542490Sjkh            else
7552490Sjkh                unwind_plan_sp.reset();
7562490Sjkh        }
7572490Sjkh        return arch_default_unwind_plan_sp;
7582490Sjkh    }
759174422Sdougb
760    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.  On Mac OS X this knowledge
761    // is properly encoded in the eh_frame section, so prefer that if available.
762    // On other platforms we may need to provide a platform-specific UnwindPlan which encodes the details of
763    // how to unwind out of sigtramp.
764    if (m_frame_type == eTrapHandlerFrame)
765    {
766        m_fast_unwind_plan_sp.reset();
767        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
768        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc) && unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
769        {
770            return unwind_plan_sp;
771        }
772    }
773
774    // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame even when it's frame zero
775    // This comes up if we have hand-written functions in a Module and hand-written eh_frame.  The assembly
776    // instruction inspection may fail and the eh_frame CFI were probably written with some care to do the
777    // right thing.  It'd be nice if there was a way to ask the eh_frame directly if it is asynchronous
778    // (can be trusted at every instruction point) or synchronous (the normal case - only at call sites).
779    // But there is not.
780    if (process && process->GetDynamicLoader() && process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo (m_sym_ctx))
781    {
782        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
783        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
784        {
785            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan because the DynamicLoader suggested we prefer it",
786                           unwind_plan_sp->GetSourceName().GetCString());
787            return unwind_plan_sp;
788        }
789    }
790
791    // Typically the NonCallSite UnwindPlan is the unwind created by inspecting the assembly language instructions
792    if (behaves_like_zeroth_frame)
793    {
794        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
795        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
796        {
797            if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
798            {
799                // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
800                // don't have any eh_frame instructions available.
801                // The assembly profilers work really well with compiler-generated functions but hand-written
802                // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
803                // UnwindPlan in case this doesn't work out when we try to unwind.
804                m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
805            }
806            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
807            return unwind_plan_sp;
808        }
809    }
810
811    // Typically this is unwind info from an eh_frame section intended for exception handling; only valid at call sites
812    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
813    int valid_offset = -1;
814    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
815    {
816        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
817        return unwind_plan_sp;
818    }
819
820    // We'd prefer to use an UnwindPlan intended for call sites when we're at a call site but if we've
821    // struck out on that, fall back to using the non-call-site assembly inspection UnwindPlan if possible.
822    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
823    if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
824    {
825        // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
826        // don't have any eh_frame instructions available.
827        // The assembly profilers work really well with compiler-generated functions but hand-written
828        // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
829        // UnwindPlan in case this doesn't work out when we try to unwind.
830        m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
831    }
832
833    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
834    {
835        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
836        return unwind_plan_sp;
837    }
838
839    // If we're on the first instruction of a function, and we have an architectural default UnwindPlan
840    // for the initial instruction of a function, use that.
841    if (m_current_offset_backed_up_one == 0)
842    {
843        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry (m_thread);
844        if (unwind_plan_sp)
845        {
846            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
847            return unwind_plan_sp;
848        }
849    }
850
851    // If nothing else, use the architectural default UnwindPlan and hope that does the job.
852    if (arch_default_unwind_plan_sp)
853        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", arch_default_unwind_plan_sp->GetSourceName().GetCString());
854    else
855        UnwindLogMsg ("Unable to find any UnwindPlan for full unwind of this frame.");
856
857    return arch_default_unwind_plan_sp;
858}
859
860
861void
862RegisterContextLLDB::InvalidateAllRegisters ()
863{
864    m_frame_type = eNotAValidFrame;
865}
866
867size_t
868RegisterContextLLDB::GetRegisterCount ()
869{
870    return m_thread.GetRegisterContext()->GetRegisterCount();
871}
872
873const RegisterInfo *
874RegisterContextLLDB::GetRegisterInfoAtIndex (size_t reg)
875{
876    return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex (reg);
877}
878
879size_t
880RegisterContextLLDB::GetRegisterSetCount ()
881{
882    return m_thread.GetRegisterContext()->GetRegisterSetCount ();
883}
884
885const RegisterSet *
886RegisterContextLLDB::GetRegisterSet (size_t reg_set)
887{
888    return m_thread.GetRegisterContext()->GetRegisterSet (reg_set);
889}
890
891uint32_t
892RegisterContextLLDB::ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num)
893{
894    return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber (kind, num);
895}
896
897bool
898RegisterContextLLDB::ReadRegisterValueFromRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
899                                                            const RegisterInfo *reg_info,
900                                                            RegisterValue &value)
901{
902    if (!IsValid())
903        return false;
904    bool success = false;
905
906    switch (regloc.type)
907    {
908    case UnwindLLDB::RegisterLocation::eRegisterInRegister:
909        {
910            const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
911
912            if (!other_reg_info)
913                return false;
914
915            if (IsFrameZero ())
916            {
917                success = m_thread.GetRegisterContext()->ReadRegister (other_reg_info, value);
918            }
919            else
920            {
921                success = GetNextFrame()->ReadRegister (other_reg_info, value);
922            }
923        }
924        break;
925    case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
926        success = value.SetUInt (regloc.location.inferred_value, reg_info->byte_size);
927        break;
928
929    case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
930        break;
931    case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
932        assert ("FIXME debugger inferior function call unwind");
933        break;
934    case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
935        {
936            Error error (ReadRegisterValueFromMemory(reg_info,
937                                                     regloc.location.target_memory_location,
938                                                     reg_info->byte_size,
939                                                     value));
940            success = error.Success();
941        }
942        break;
943    default:
944        assert ("Unknown RegisterLocation type.");
945        break;
946    }
947    return success;
948}
949
950bool
951RegisterContextLLDB::WriteRegisterValueToRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
952                                                           const RegisterInfo *reg_info,
953                                                           const RegisterValue &value)
954{
955    if (!IsValid())
956        return false;
957
958    bool success = false;
959
960    switch (regloc.type)
961    {
962        case UnwindLLDB::RegisterLocation::eRegisterInRegister:
963            {
964                const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
965                if (IsFrameZero ())
966                {
967                    success = m_thread.GetRegisterContext()->WriteRegister (other_reg_info, value);
968                }
969                else
970                {
971                    success = GetNextFrame()->WriteRegister (other_reg_info, value);
972                }
973            }
974            break;
975        case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
976        case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
977            break;
978        case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
979            assert ("FIXME debugger inferior function call unwind");
980            break;
981        case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
982            {
983                Error error (WriteRegisterValueToMemory (reg_info,
984                                                         regloc.location.target_memory_location,
985                                                         reg_info->byte_size,
986                                                         value));
987                success = error.Success();
988            }
989            break;
990        default:
991            assert ("Unknown RegisterLocation type.");
992            break;
993    }
994    return success;
995}
996
997
998bool
999RegisterContextLLDB::IsValid () const
1000{
1001    return m_frame_type != eNotAValidFrame;
1002}
1003
1004bool
1005RegisterContextLLDB::IsTrapHandlerFrame () const
1006{
1007    return m_frame_type == eTrapHandlerFrame;
1008}
1009
1010// A skip frame is a bogus frame on the stack -- but one where we're likely to find a real frame farther
1011// up the stack if we keep looking.  It's always the second frame in an unwind (i.e. the first frame after
1012// frame zero) where unwinding can be the trickiest.  Ideally we'll mark up this frame in some way so the
1013// user knows we're displaying bad data and we may have skipped one frame of their real program in the
1014// process of getting back on track.
1015
1016bool
1017RegisterContextLLDB::IsSkipFrame () const
1018{
1019    return m_frame_type == eSkipFrame;
1020}
1021
1022bool
1023RegisterContextLLDB::IsTrapHandlerSymbol (lldb_private::Process *process, const lldb_private::SymbolContext &m_sym_ctx) const
1024{
1025    PlatformSP platform_sp (process->GetTarget().GetPlatform());
1026    if (platform_sp)
1027    {
1028        const std::vector<ConstString> trap_handler_names (platform_sp->GetTrapHandlerSymbolNames());
1029        for (ConstString name : trap_handler_names)
1030        {
1031            if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1032                (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1033            {
1034                return true;
1035            }
1036        }
1037    }
1038    const std::vector<ConstString> user_specified_trap_handler_names (m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1039    for (ConstString name : user_specified_trap_handler_names)
1040    {
1041        if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1042            (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1043        {
1044            return true;
1045        }
1046    }
1047
1048    return false;
1049}
1050
1051// Answer the question: Where did THIS frame save the CALLER frame ("previous" frame)'s register value?
1052
1053enum UnwindLLDB::RegisterSearchResult
1054RegisterContextLLDB::SavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc)
1055{
1056    // Have we already found this register location?
1057    if (!m_registers.empty())
1058    {
1059        std::map<uint32_t, lldb_private::UnwindLLDB::RegisterLocation>::const_iterator iterator;
1060        iterator = m_registers.find (lldb_regnum);
1061        if (iterator != m_registers.end())
1062        {
1063            regloc = iterator->second;
1064            UnwindLogMsg ("supplying caller's saved reg %d's location, cached", lldb_regnum);
1065            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1066        }
1067    }
1068
1069    uint32_t sp_regnum = LLDB_INVALID_REGNUM;
1070    uint32_t pc_regnum = LLDB_INVALID_REGNUM;
1071    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, eRegisterKindLLDB, sp_regnum);
1072    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, eRegisterKindLLDB, pc_regnum);
1073
1074    // Are we looking for the CALLER's stack pointer?  The stack pointer is defined to be the same as THIS frame's
1075    // CFA so just return the CFA value.  This is true on x86-32/x86-64 at least.
1076    if (sp_regnum != LLDB_INVALID_REGNUM && sp_regnum == lldb_regnum)
1077    {
1078        // make sure we won't lose precision copying an addr_t (m_cfa) into a uint64_t (.inferred_value)
1079        assert (sizeof (addr_t) <= sizeof (uint64_t));
1080        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1081        regloc.location.inferred_value = m_cfa;
1082        m_registers[lldb_regnum] = regloc;
1083        UnwindLogMsg ("supplying caller's stack pointer (%d) value, computed from CFA", lldb_regnum);
1084        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1085    }
1086
1087    // Look through the available UnwindPlans for the register location.
1088
1089    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1090    bool have_unwindplan_regloc = false;
1091    RegisterKind unwindplan_registerkind = (RegisterKind)-1;
1092
1093    if (m_fast_unwind_plan_sp)
1094    {
1095        UnwindPlan::RowSP active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1096        unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind ();
1097        uint32_t row_regnum;
1098        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1099        {
1100            UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1101                    lldb_regnum, (int) unwindplan_registerkind);
1102            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1103        }
1104        if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1105        {
1106            UnwindLogMsg ("supplying caller's saved reg %d's location using FastUnwindPlan", lldb_regnum);
1107            have_unwindplan_regloc = true;
1108        }
1109    }
1110
1111    if (!have_unwindplan_regloc)
1112    {
1113        // m_full_unwind_plan_sp being NULL means that we haven't tried to find a full UnwindPlan yet
1114        if (!m_full_unwind_plan_sp)
1115            m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
1116
1117        if (m_full_unwind_plan_sp)
1118        {
1119            UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1120            unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind ();
1121            uint32_t row_regnum;
1122            bool row_register_rewritten_to_return_address_reg = false;
1123
1124            // If we're fetching the saved pc and this UnwindPlan defines a ReturnAddress register (e.g. lr on arm),
1125            // look for the return address register number in the UnwindPlan's row.
1126            if (lldb_regnum == pc_regnum && m_full_unwind_plan_sp->GetReturnAddressRegister() != LLDB_INVALID_REGNUM)
1127            {
1128               row_regnum = m_full_unwind_plan_sp->GetReturnAddressRegister();
1129               row_register_rewritten_to_return_address_reg = true;
1130               UnwindLogMsg ("requested caller's saved PC but this UnwindPlan uses a RA reg; getting reg %d instead",
1131                       row_regnum);
1132            }
1133            else
1134            {
1135                if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1136                {
1137                    if (unwindplan_registerkind == eRegisterKindGeneric)
1138                        UnwindLogMsg ("could not convert lldb regnum %d into eRegisterKindGeneric reg numbering scheme", lldb_regnum);
1139                    else
1140                        UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1141                                lldb_regnum, (int) unwindplan_registerkind);
1142                    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1143                }
1144            }
1145
1146            if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1147            {
1148                have_unwindplan_regloc = true;
1149                UnwindLogMsg ("supplying caller's saved reg %d's location using %s UnwindPlan", lldb_regnum,
1150                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1151            }
1152
1153            // This is frame 0 and we're retrieving the PC and it's saved in a Return Address register and
1154            // it hasn't been saved anywhere yet -- that is, it's still live in the actual register.
1155            // Handle this specially.
1156
1157            if (have_unwindplan_regloc == false
1158                && row_register_rewritten_to_return_address_reg == true
1159                && IsFrameZero()
1160                && row_regnum != LLDB_INVALID_REGNUM)
1161            {
1162                uint32_t ra_regnum_in_lldb_reg_numbering;
1163                if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, row_regnum, eRegisterKindLLDB, ra_regnum_in_lldb_reg_numbering))
1164                {
1165                    lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1166                    new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1167                    new_regloc.location.register_number = ra_regnum_in_lldb_reg_numbering;
1168                    m_registers[lldb_regnum] = new_regloc;
1169                    regloc = new_regloc;
1170                    UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0, saved in %d", lldb_regnum, ra_regnum_in_lldb_reg_numbering);
1171                    return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1172                }
1173            }
1174
1175            // If this architecture stores the return address in a register (it defines a Return Address register)
1176            // and we're on a non-zero stack frame and the Full UnwindPlan says that the pc is stored in the
1177            // RA registers (e.g. lr on arm), then we know that the full unwindplan is not trustworthy -- this
1178            // is an impossible situation and the instruction emulation code has likely been misled.
1179            // If this stack frame meets those criteria, we need to throw away the Full UnwindPlan that the
1180            // instruction emulation came up with and fall back to the architecture's Default UnwindPlan so
1181            // the stack walk can get past this point.
1182
1183            // Special note:  If the Full UnwindPlan was generated from the compiler, don't second-guess it
1184            // when we're at a call site location.
1185
1186            // arch_default_ra_regnum is the return address register # in the Full UnwindPlan register numbering
1187            uint32_t arch_default_ra_regnum = LLDB_INVALID_REGNUM;
1188            if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_RA, unwindplan_registerkind, arch_default_ra_regnum)
1189                && arch_default_ra_regnum != LLDB_INVALID_REGNUM
1190                && pc_regnum != LLDB_INVALID_REGNUM
1191                && pc_regnum == lldb_regnum
1192                && unwindplan_regloc.IsInOtherRegister()
1193                && unwindplan_regloc.GetRegisterNumber() == arch_default_ra_regnum
1194                && m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes
1195                && !m_all_registers_available)
1196            {
1197                UnwindLogMsg ("%s UnwindPlan tried to restore the pc from the link register but this is a non-zero frame",
1198                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1199
1200                // Throw away the full unwindplan; install the arch default unwindplan
1201                if (TryFallbackUnwindPlan())
1202                {
1203                    // Now re-fetch the pc value we're searching for
1204                    uint32_t arch_default_pc_reg = LLDB_INVALID_REGNUM;
1205                    UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1206                    if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, m_full_unwind_plan_sp->GetRegisterKind(), arch_default_pc_reg)
1207                        && arch_default_pc_reg != LLDB_INVALID_REGNUM
1208                        && active_row
1209                        && active_row->GetRegisterInfo (arch_default_pc_reg, unwindplan_regloc))
1210                    {
1211                        have_unwindplan_regloc = true;
1212                    }
1213                    else
1214                    {
1215                        have_unwindplan_regloc = false;
1216                    }
1217                }
1218            }
1219        }
1220    }
1221
1222
1223    ExecutionContext exe_ctx(m_thread.shared_from_this());
1224    Process *process = exe_ctx.GetProcessPtr();
1225    if (have_unwindplan_regloc == false)
1226    {
1227        // If a volatile register is being requested, we don't want to forward the next frame's register contents
1228        // up the stack -- the register is not retrievable at this frame.
1229        ABI *abi = process ? process->GetABI().get() : NULL;
1230        if (abi)
1231        {
1232            const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1233            if (reg_info && abi->RegisterIsVolatile (reg_info))
1234            {
1235                UnwindLogMsg ("did not supply reg location for %d (%s) because it is volatile",
1236                    lldb_regnum, reg_info->name ? reg_info->name : "??");
1237                return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;
1238            }
1239        }
1240
1241        if (IsFrameZero ())
1242        {
1243            // This is frame 0 - we should return the actual live register context value
1244            lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1245            new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1246            new_regloc.location.register_number = lldb_regnum;
1247            m_registers[lldb_regnum] = new_regloc;
1248            regloc = new_regloc;
1249            UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0", lldb_regnum);
1250            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1251        }
1252        else
1253        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1254        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1255    }
1256
1257    // unwindplan_regloc has valid contents about where to retrieve the register
1258    if (unwindplan_regloc.IsUnspecified())
1259    {
1260        lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1261        new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;
1262        m_registers[lldb_regnum] = new_regloc;
1263        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1264        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1265    }
1266
1267    if (unwindplan_regloc.IsSame())
1268    {
1269        if (IsFrameZero ())
1270        {
1271            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1272            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1273        }
1274        else
1275        {
1276            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1277        }
1278    }
1279
1280    if (unwindplan_regloc.IsCFAPlusOffset())
1281    {
1282        int offset = unwindplan_regloc.GetOffset();
1283        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1284        regloc.location.inferred_value = m_cfa + offset;
1285        m_registers[lldb_regnum] = regloc;
1286        UnwindLogMsg ("supplying caller's register %d, value is CFA plus offset %d", lldb_regnum, offset);
1287        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1288    }
1289
1290    if (unwindplan_regloc.IsAtCFAPlusOffset())
1291    {
1292        int offset = unwindplan_regloc.GetOffset();
1293        regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1294        regloc.location.target_memory_location = m_cfa + offset;
1295        m_registers[lldb_regnum] = regloc;
1296        UnwindLogMsg ("supplying caller's register %d from the stack, saved at CFA plus offset %d", lldb_regnum, offset);
1297        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1298    }
1299
1300    if (unwindplan_regloc.IsInOtherRegister())
1301    {
1302        uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();
1303        uint32_t row_regnum_in_lldb;
1304        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, unwindplan_regnum, eRegisterKindLLDB, row_regnum_in_lldb))
1305        {
1306            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1307            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1308        }
1309        regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1310        regloc.location.register_number = row_regnum_in_lldb;
1311        m_registers[lldb_regnum] = regloc;
1312        UnwindLogMsg ("supplying caller's register %d, saved in register %d", lldb_regnum, row_regnum_in_lldb);
1313        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1314    }
1315
1316    if (unwindplan_regloc.IsDWARFExpression() || unwindplan_regloc.IsAtDWARFExpression())
1317    {
1318        DataExtractor dwarfdata (unwindplan_regloc.GetDWARFExpressionBytes(),
1319                                 unwindplan_regloc.GetDWARFExpressionLength(),
1320                                 process->GetByteOrder(), process->GetAddressByteSize());
1321        ModuleSP opcode_ctx;
1322        DWARFExpression dwarfexpr (opcode_ctx, dwarfdata, 0, unwindplan_regloc.GetDWARFExpressionLength());
1323        dwarfexpr.SetRegisterKind (unwindplan_registerkind);
1324        Value result;
1325        Error error;
1326        if (dwarfexpr.Evaluate (&exe_ctx, NULL, NULL, this, 0, NULL, result, &error))
1327        {
1328            addr_t val;
1329            val = result.GetScalar().ULongLong();
1330            if (unwindplan_regloc.IsDWARFExpression())
1331             {
1332                regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1333                regloc.location.inferred_value = val;
1334                m_registers[lldb_regnum] = regloc;
1335                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsDWARFExpression)", lldb_regnum);
1336                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1337            }
1338            else
1339            {
1340                regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1341                regloc.location.target_memory_location = val;
1342                m_registers[lldb_regnum] = regloc;
1343                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsAtDWARFExpression)", lldb_regnum);
1344                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1345            }
1346        }
1347        UnwindLogMsg ("tried to use IsDWARFExpression or IsAtDWARFExpression for reg %d but failed", lldb_regnum);
1348        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1349    }
1350
1351    UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1352
1353    // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are unsupported.
1354
1355    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1356}
1357
1358// If the Full unwindplan has been determined to be incorrect, this method will
1359// replace it with the architecture's default unwindplan, if one is defined.
1360// It will also find the FuncUnwinders object for this function and replace the
1361// Full unwind method for the function there so we don't use the errant Full unwindplan
1362// again in the future of this debug session.
1363// We're most likely doing this because the Full unwindplan was generated by assembly
1364// instruction profiling and the profiler got something wrong.
1365
1366bool
1367RegisterContextLLDB::TryFallbackUnwindPlan ()
1368{
1369    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1370    if (m_fallback_unwind_plan_sp.get() == NULL)
1371        return false;
1372
1373    UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1374    UnwindPlan::RowSP active_row = m_fallback_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1375
1376    if (active_row && active_row->GetCFARegister() != LLDB_INVALID_REGNUM)
1377    {
1378        FuncUnwindersSP func_unwinders_sp;
1379        if (m_sym_ctx_valid && m_current_pc.IsValid() && m_current_pc.GetModule())
1380        {
1381            func_unwinders_sp = m_current_pc.GetModule()->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
1382            if (func_unwinders_sp)
1383            {
1384                func_unwinders_sp->InvalidateNonCallSiteUnwindPlan (m_thread);
1385            }
1386        }
1387        m_registers.clear();
1388        m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1389        addr_t cfa_regval = LLDB_INVALID_ADDRESS;
1390        if (ReadGPRValue (m_fallback_unwind_plan_sp->GetRegisterKind(), active_row->GetCFARegister(), cfa_regval))
1391        {
1392            m_cfa = cfa_regval + active_row->GetCFAOffset ();
1393        }
1394
1395        UnwindLogMsg ("full unwind plan '%s' has been replaced by architecture default unwind plan '%s' for this function from now on.",
1396                      original_full_unwind_plan_sp->GetSourceName().GetCString(), m_fallback_unwind_plan_sp->GetSourceName().GetCString());
1397        m_fallback_unwind_plan_sp.reset();
1398    }
1399
1400    return true;
1401}
1402
1403// Retrieve a general purpose register value for THIS frame, as saved by the NEXT frame, i.e. the frame that
1404// this frame called.  e.g.
1405//
1406//  foo () { }
1407//  bar () { foo (); }
1408//  main () { bar (); }
1409//
1410//  stopped in foo() so
1411//     frame 0 - foo
1412//     frame 1 - bar
1413//     frame 2 - main
1414//  and this RegisterContext is for frame 1 (bar) - if we want to get the pc value for frame 1, we need to ask
1415//  where frame 0 (the "next" frame) saved that and retrieve the value.
1416
1417bool
1418RegisterContextLLDB::ReadGPRValue (int register_kind, uint32_t regnum, addr_t &value)
1419{
1420    if (!IsValid())
1421        return false;
1422
1423    uint32_t lldb_regnum;
1424    if (register_kind == eRegisterKindLLDB)
1425    {
1426        lldb_regnum = regnum;
1427    }
1428    else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindLLDB, lldb_regnum))
1429    {
1430        return false;
1431    }
1432
1433    const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1434    RegisterValue reg_value;
1435    // if this is frame 0 (currently executing frame), get the requested reg contents from the actual thread registers
1436    if (IsFrameZero ())
1437    {
1438        if (m_thread.GetRegisterContext()->ReadRegister (reg_info, reg_value))
1439        {
1440            value = reg_value.GetAsUInt64();
1441            return true;
1442        }
1443        return false;
1444    }
1445
1446    bool pc_register = false;
1447    uint32_t generic_regnum;
1448    if (register_kind == eRegisterKindGeneric && regnum == LLDB_REGNUM_GENERIC_PC)
1449    {
1450        pc_register = true;
1451    }
1452    else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindGeneric, generic_regnum)
1453             && generic_regnum == LLDB_REGNUM_GENERIC_PC)
1454    {
1455        pc_register = true;
1456    }
1457
1458    lldb_private::UnwindLLDB::RegisterLocation regloc;
1459    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, pc_register))
1460    {
1461        return false;
1462    }
1463    if (ReadRegisterValueFromRegisterLocation (regloc, reg_info, reg_value))
1464    {
1465        value = reg_value.GetAsUInt64();
1466        return true;
1467    }
1468    return false;
1469}
1470
1471// Find the value of a register in THIS frame
1472
1473bool
1474RegisterContextLLDB::ReadRegister (const RegisterInfo *reg_info, RegisterValue &value)
1475{
1476    if (!IsValid())
1477        return false;
1478
1479    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1480    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1481
1482    // If this is the 0th frame, hand this over to the live register context
1483    if (IsFrameZero ())
1484    {
1485        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1486        return m_thread.GetRegisterContext()->ReadRegister (reg_info, value);
1487    }
1488
1489    lldb_private::UnwindLLDB::RegisterLocation regloc;
1490    // Find out where the NEXT frame saved THIS frame's register contents
1491    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1492        return false;
1493
1494    return ReadRegisterValueFromRegisterLocation (regloc, reg_info, value);
1495}
1496
1497bool
1498RegisterContextLLDB::WriteRegister (const RegisterInfo *reg_info, const RegisterValue &value)
1499{
1500    if (!IsValid())
1501        return false;
1502
1503    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1504    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1505
1506    // If this is the 0th frame, hand this over to the live register context
1507    if (IsFrameZero ())
1508    {
1509        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1510        return m_thread.GetRegisterContext()->WriteRegister (reg_info, value);
1511    }
1512
1513    lldb_private::UnwindLLDB::RegisterLocation regloc;
1514    // Find out where the NEXT frame saved THIS frame's register contents
1515    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1516        return false;
1517
1518    return WriteRegisterValueToRegisterLocation (regloc, reg_info, value);
1519}
1520
1521// Don't need to implement this one
1522bool
1523RegisterContextLLDB::ReadAllRegisterValues (lldb::DataBufferSP &data_sp)
1524{
1525    return false;
1526}
1527
1528// Don't need to implement this one
1529bool
1530RegisterContextLLDB::WriteAllRegisterValues (const lldb::DataBufferSP& data_sp)
1531{
1532    return false;
1533}
1534
1535// Retrieve the pc value for THIS from
1536
1537bool
1538RegisterContextLLDB::GetCFA (addr_t& cfa)
1539{
1540    if (!IsValid())
1541    {
1542        return false;
1543    }
1544    if (m_cfa == LLDB_INVALID_ADDRESS)
1545    {
1546        return false;
1547    }
1548    cfa = m_cfa;
1549    return true;
1550}
1551
1552
1553RegisterContextLLDB::SharedPtr
1554RegisterContextLLDB::GetNextFrame () const
1555{
1556    RegisterContextLLDB::SharedPtr regctx;
1557    if (m_frame_number == 0)
1558      return regctx;
1559    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number - 1);
1560}
1561
1562RegisterContextLLDB::SharedPtr
1563RegisterContextLLDB::GetPrevFrame () const
1564{
1565    RegisterContextLLDB::SharedPtr regctx;
1566    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number + 1);
1567}
1568
1569// Retrieve the address of the start of the function of THIS frame
1570
1571bool
1572RegisterContextLLDB::GetStartPC (addr_t& start_pc)
1573{
1574    if (!IsValid())
1575        return false;
1576
1577    if (!m_start_pc.IsValid())
1578    {
1579        return ReadPC (start_pc);
1580    }
1581    start_pc = m_start_pc.GetLoadAddress (CalculateTarget().get());
1582    return true;
1583}
1584
1585// Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
1586
1587bool
1588RegisterContextLLDB::ReadPC (addr_t& pc)
1589{
1590    if (!IsValid())
1591        return false;
1592
1593    if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
1594    {
1595        // A pc value of 0 or 1 is impossible in the middle of the stack -- it indicates the end of a stack walk.
1596        // On the currently executing frame (or such a frame interrupted asynchronously by sigtramp et al) this may
1597        // occur if code has jumped through a NULL pointer -- we want to be able to unwind past that frame to help
1598        // find the bug.
1599
1600        if (m_all_registers_available == false
1601            && (pc == 0 || pc == 1))
1602        {
1603            return false;
1604        }
1605        else
1606        {
1607            return true;
1608        }
1609    }
1610    else
1611    {
1612        return false;
1613    }
1614}
1615
1616
1617void
1618RegisterContextLLDB::UnwindLogMsg (const char *fmt, ...)
1619{
1620    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1621    if (log)
1622    {
1623        va_list args;
1624        va_start (args, fmt);
1625
1626        char *logmsg;
1627        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1628        {
1629            if (logmsg)
1630                free (logmsg);
1631            va_end (args);
1632            return;
1633        }
1634        va_end (args);
1635
1636        log->Printf ("%*sth%d/fr%u %s",
1637                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1638                      logmsg);
1639        free (logmsg);
1640    }
1641}
1642
1643void
1644RegisterContextLLDB::UnwindLogMsgVerbose (const char *fmt, ...)
1645{
1646    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1647    if (log && log->GetVerbose())
1648    {
1649        va_list args;
1650        va_start (args, fmt);
1651
1652        char *logmsg;
1653        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1654        {
1655            if (logmsg)
1656                free (logmsg);
1657            va_end (args);
1658            return;
1659        }
1660        va_end (args);
1661
1662        log->Printf ("%*sth%d/fr%u %s",
1663                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1664                      logmsg);
1665        free (logmsg);
1666    }
1667}
1668
1669
1670