1254721Semaste//===-- RegisterContextLLDB.cpp --------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste
11254721Semaste#include "lldb/lldb-private.h"
12254721Semaste#include "lldb/Core/Address.h"
13254721Semaste#include "lldb/Core/AddressRange.h"
14254721Semaste#include "lldb/Core/DataBufferHeap.h"
15254721Semaste#include "lldb/Core/Log.h"
16254721Semaste#include "lldb/Core/Module.h"
17254721Semaste#include "lldb/Core/RegisterValue.h"
18254721Semaste#include "lldb/Core/Value.h"
19254721Semaste#include "lldb/Expression/DWARFExpression.h"
20254721Semaste#include "lldb/Symbol/DWARFCallFrameInfo.h"
21254721Semaste#include "lldb/Symbol/FuncUnwinders.h"
22254721Semaste#include "lldb/Symbol/Function.h"
23254721Semaste#include "lldb/Symbol/ObjectFile.h"
24269024Semaste#include "lldb/Symbol/Symbol.h"
25254721Semaste#include "lldb/Symbol/SymbolContext.h"
26254721Semaste#include "lldb/Target/ABI.h"
27269024Semaste#include "lldb/Target/DynamicLoader.h"
28254721Semaste#include "lldb/Target/ExecutionContext.h"
29269024Semaste#include "lldb/Target/Platform.h"
30254721Semaste#include "lldb/Target/Process.h"
31269024Semaste#include "lldb/Target/SectionLoadList.h"
32254721Semaste#include "lldb/Target/StackFrame.h"
33254721Semaste#include "lldb/Target/Target.h"
34254721Semaste#include "lldb/Target/Thread.h"
35254721Semaste
36254721Semaste#include "RegisterContextLLDB.h"
37254721Semaste
38254721Semasteusing namespace lldb;
39254721Semasteusing namespace lldb_private;
40254721Semaste
41254721SemasteRegisterContextLLDB::RegisterContextLLDB
42254721Semaste(
43254721Semaste    Thread& thread,
44254721Semaste    const SharedPtr &next_frame,
45254721Semaste    SymbolContext& sym_ctx,
46254721Semaste    uint32_t frame_number,
47254721Semaste    UnwindLLDB& unwind_lldb
48254721Semaste) :
49254721Semaste    RegisterContext (thread, frame_number),
50254721Semaste    m_thread(thread),
51254721Semaste    m_fast_unwind_plan_sp (),
52254721Semaste    m_full_unwind_plan_sp (),
53269024Semaste    m_fallback_unwind_plan_sp (),
54254721Semaste    m_all_registers_available(false),
55254721Semaste    m_frame_type (-1),
56254721Semaste    m_cfa (LLDB_INVALID_ADDRESS),
57254721Semaste    m_start_pc (),
58254721Semaste    m_current_pc (),
59254721Semaste    m_current_offset (0),
60254721Semaste    m_current_offset_backed_up_one (0),
61254721Semaste    m_sym_ctx(sym_ctx),
62254721Semaste    m_sym_ctx_valid (false),
63254721Semaste    m_frame_number (frame_number),
64254721Semaste    m_registers(),
65254721Semaste    m_parent_unwind (unwind_lldb)
66254721Semaste{
67254721Semaste    m_sym_ctx.Clear(false);
68254721Semaste    m_sym_ctx_valid = false;
69254721Semaste
70254721Semaste    if (IsFrameZero ())
71254721Semaste    {
72254721Semaste        InitializeZerothFrame ();
73254721Semaste    }
74254721Semaste    else
75254721Semaste    {
76254721Semaste        InitializeNonZerothFrame ();
77254721Semaste    }
78254721Semaste
79254721Semaste    // This same code exists over in the GetFullUnwindPlanForFrame() but it may not have been executed yet
80254721Semaste    if (IsFrameZero()
81269024Semaste        || next_frame->m_frame_type == eTrapHandlerFrame
82254721Semaste        || next_frame->m_frame_type == eDebuggerFrame)
83254721Semaste    {
84254721Semaste        m_all_registers_available = true;
85254721Semaste    }
86254721Semaste}
87254721Semaste
88269024Semastebool
89269024SemasteRegisterContextLLDB::IsUnwindPlanValidForCurrentPC(lldb::UnwindPlanSP unwind_plan_sp, int &valid_pc_offset)
90269024Semaste{
91269024Semaste    if (!unwind_plan_sp)
92269024Semaste        return false;
93269024Semaste
94269024Semaste    // check if m_current_pc is valid
95269024Semaste    if (unwind_plan_sp->PlanValidAtAddress(m_current_pc))
96269024Semaste    {
97269024Semaste        // yes - current offset can be used as is
98269024Semaste        valid_pc_offset = m_current_offset;
99269024Semaste        return true;
100269024Semaste    }
101269024Semaste
102269024Semaste    // if m_current_offset <= 0, we've got nothing else to try
103269024Semaste    if (m_current_offset <= 0)
104269024Semaste        return false;
105269024Semaste
106269024Semaste    // check pc - 1 to see if it's valid
107269024Semaste    Address pc_minus_one (m_current_pc);
108269024Semaste    pc_minus_one.SetOffset(m_current_pc.GetOffset() - 1);
109269024Semaste    if (unwind_plan_sp->PlanValidAtAddress(pc_minus_one))
110269024Semaste    {
111269024Semaste        // *valid_pc_offset = m_current_offset - 1;
112269024Semaste        valid_pc_offset = m_current_pc.GetOffset() - 1;
113269024Semaste        return true;
114269024Semaste    }
115269024Semaste
116269024Semaste    return false;
117269024Semaste}
118269024Semaste
119254721Semaste// Initialize a RegisterContextLLDB which is the first frame of a stack -- the zeroth frame or currently
120254721Semaste// executing frame.
121254721Semaste
122254721Semastevoid
123254721SemasteRegisterContextLLDB::InitializeZerothFrame()
124254721Semaste{
125254721Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
126254721Semaste    ExecutionContext exe_ctx(m_thread.shared_from_this());
127254721Semaste    RegisterContextSP reg_ctx_sp = m_thread.GetRegisterContext();
128254721Semaste
129254721Semaste    if (reg_ctx_sp.get() == NULL)
130254721Semaste    {
131254721Semaste        m_frame_type = eNotAValidFrame;
132269024Semaste        UnwindLogMsg ("frame does not have a register context");
133254721Semaste        return;
134254721Semaste    }
135254721Semaste
136254721Semaste    addr_t current_pc = reg_ctx_sp->GetPC();
137254721Semaste
138254721Semaste    if (current_pc == LLDB_INVALID_ADDRESS)
139254721Semaste    {
140254721Semaste        m_frame_type = eNotAValidFrame;
141269024Semaste        UnwindLogMsg ("frame does not have a pc");
142254721Semaste        return;
143254721Semaste    }
144254721Semaste
145254721Semaste    Process *process = exe_ctx.GetProcessPtr();
146254721Semaste
147254721Semaste    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
148254721Semaste    // this will strip bit zero in case we read a PC from memory or from the LR.
149254721Semaste    // (which would be a no-op in frame 0 where we get it from the register set,
150254721Semaste    // but still a good idea to make the call here for other ABIs that may exist.)
151254721Semaste    ABI *abi = process->GetABI().get();
152254721Semaste    if (abi)
153254721Semaste        current_pc = abi->FixCodeAddress(current_pc);
154254721Semaste
155254721Semaste    // Initialize m_current_pc, an Address object, based on current_pc, an addr_t.
156269024Semaste    m_current_pc.SetLoadAddress (current_pc, &process->GetTarget());
157254721Semaste
158254721Semaste    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
159254721Semaste    // stick in some reasonable defaults and hope we can unwind past this frame.
160254721Semaste    ModuleSP pc_module_sp (m_current_pc.GetModule());
161254721Semaste    if (!m_current_pc.IsValid() || !pc_module_sp)
162254721Semaste    {
163254721Semaste        UnwindLogMsg ("using architectural default unwind method");
164254721Semaste    }
165254721Semaste
166254721Semaste    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
167254721Semaste    if (pc_module_sp.get()
168254721Semaste        && (pc_module_sp->ResolveSymbolContextForAddress (m_current_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
169254721Semaste    {
170254721Semaste        m_sym_ctx_valid = true;
171254721Semaste    }
172254721Semaste
173254721Semaste    AddressRange addr_range;
174254721Semaste    m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range);
175254721Semaste
176269024Semaste    if (IsTrapHandlerSymbol (process, m_sym_ctx))
177254721Semaste    {
178269024Semaste        m_frame_type = eTrapHandlerFrame;
179254721Semaste    }
180254721Semaste    else
181254721Semaste    {
182254721Semaste        // FIXME:  Detect eDebuggerFrame here.
183254721Semaste        m_frame_type = eNormalFrame;
184254721Semaste    }
185254721Semaste
186254721Semaste    // If we were able to find a symbol/function, set addr_range to the bounds of that symbol/function.
187254721Semaste    // else treat the current pc value as the start_pc and record no offset.
188254721Semaste    if (addr_range.GetBaseAddress().IsValid())
189254721Semaste    {
190254721Semaste        m_start_pc = addr_range.GetBaseAddress();
191254721Semaste        if (m_current_pc.GetSection() == m_start_pc.GetSection())
192254721Semaste        {
193254721Semaste            m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
194254721Semaste        }
195254721Semaste        else if (m_current_pc.GetModule() == m_start_pc.GetModule())
196254721Semaste        {
197254721Semaste            // This means that whatever symbol we kicked up isn't really correct
198254721Semaste            // --- we should not cross section boundaries ... We really should NULL out
199254721Semaste            // the function/symbol in this case unless there is a bad assumption
200254721Semaste            // here due to inlined functions?
201254721Semaste            m_current_offset = m_current_pc.GetFileAddress() - m_start_pc.GetFileAddress();
202254721Semaste        }
203254721Semaste        m_current_offset_backed_up_one = m_current_offset;
204254721Semaste    }
205254721Semaste    else
206254721Semaste    {
207254721Semaste        m_start_pc = m_current_pc;
208254721Semaste        m_current_offset = -1;
209254721Semaste        m_current_offset_backed_up_one = -1;
210254721Semaste    }
211254721Semaste
212254721Semaste    // We've set m_frame_type and m_sym_ctx before these calls.
213254721Semaste
214254721Semaste    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
215254721Semaste    m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
216254721Semaste
217254721Semaste    UnwindPlan::RowSP active_row;
218254721Semaste    int cfa_offset = 0;
219254721Semaste    int row_register_kind = -1;
220254721Semaste    if (m_full_unwind_plan_sp && m_full_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
221254721Semaste    {
222254721Semaste        active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
223254721Semaste        row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
224254721Semaste        if (active_row.get() && log)
225254721Semaste        {
226254721Semaste            StreamString active_row_strm;
227254721Semaste            active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
228254721Semaste            UnwindLogMsg ("%s", active_row_strm.GetString().c_str());
229254721Semaste        }
230254721Semaste    }
231254721Semaste
232254721Semaste    if (!active_row.get())
233254721Semaste    {
234269024Semaste        UnwindLogMsg ("could not find an unwindplan row for this frame's pc");
235254721Semaste        m_frame_type = eNotAValidFrame;
236254721Semaste        return;
237254721Semaste    }
238254721Semaste
239254721Semaste
240254721Semaste    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
241254721Semaste    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
242254721Semaste    {
243269024Semaste        UnwindLogMsg ("could not read CFA register for this frame.");
244254721Semaste        m_frame_type = eNotAValidFrame;
245254721Semaste        return;
246254721Semaste    }
247254721Semaste
248254721Semaste    cfa_offset = active_row->GetCFAOffset ();
249254721Semaste    m_cfa = cfa_regval + cfa_offset;
250254721Semaste
251254721Semaste    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
252254721Semaste    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64 " using %s UnwindPlan",
253254721Semaste            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()),
254254721Semaste            (uint64_t) m_cfa,
255254721Semaste            m_full_unwind_plan_sp->GetSourceName().GetCString());
256254721Semaste}
257254721Semaste
258254721Semaste// Initialize a RegisterContextLLDB for the non-zeroth frame -- rely on the RegisterContextLLDB "below" it
259254721Semaste// to provide things like its current pc value.
260254721Semaste
261254721Semastevoid
262254721SemasteRegisterContextLLDB::InitializeNonZerothFrame()
263254721Semaste{
264254721Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
265254721Semaste    if (IsFrameZero ())
266254721Semaste    {
267254721Semaste        m_frame_type = eNotAValidFrame;
268269024Semaste        UnwindLogMsg ("non-zeroth frame tests positive for IsFrameZero -- that shouldn't happen.");
269254721Semaste        return;
270254721Semaste    }
271254721Semaste
272254721Semaste    if (!GetNextFrame().get() || !GetNextFrame()->IsValid())
273254721Semaste    {
274254721Semaste        m_frame_type = eNotAValidFrame;
275269024Semaste        UnwindLogMsg ("Could not get next frame, marking this frame as invalid.");
276254721Semaste        return;
277254721Semaste    }
278254721Semaste    if (!m_thread.GetRegisterContext())
279254721Semaste    {
280254721Semaste        m_frame_type = eNotAValidFrame;
281269024Semaste        UnwindLogMsg ("Could not get register context for this thread, marking this frame as invalid.");
282254721Semaste        return;
283254721Semaste    }
284254721Semaste
285254721Semaste    addr_t pc;
286254721Semaste    if (!ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
287254721Semaste    {
288254721Semaste        UnwindLogMsg ("could not get pc value");
289254721Semaste        m_frame_type = eNotAValidFrame;
290254721Semaste        return;
291254721Semaste    }
292254721Semaste
293254721Semaste    if (log)
294254721Semaste    {
295254721Semaste        UnwindLogMsg ("pc = 0x%16.16" PRIx64, pc);
296254721Semaste        addr_t reg_val;
297254721Semaste        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP, reg_val))
298254721Semaste            UnwindLogMsg ("fp = 0x%16.16" PRIx64, reg_val);
299254721Semaste        if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, reg_val))
300254721Semaste            UnwindLogMsg ("sp = 0x%16.16" PRIx64, reg_val);
301254721Semaste    }
302254721Semaste
303254721Semaste    // A pc of 0x0 means it's the end of the stack crawl
304254721Semaste    if (pc == 0)
305254721Semaste    {
306254721Semaste        m_frame_type = eNotAValidFrame;
307269024Semaste        UnwindLogMsg ("this frame has a pc of 0x0");
308254721Semaste        return;
309254721Semaste    }
310254721Semaste
311254721Semaste    ExecutionContext exe_ctx(m_thread.shared_from_this());
312254721Semaste    Process *process = exe_ctx.GetProcessPtr();
313254721Semaste    // Let ABIs fixup code addresses to make sure they are valid. In ARM ABIs
314254721Semaste    // this will strip bit zero in case we read a PC from memory or from the LR.
315254721Semaste    ABI *abi = process->GetABI().get();
316254721Semaste    if (abi)
317254721Semaste        pc = abi->FixCodeAddress(pc);
318254721Semaste
319269024Semaste    m_current_pc.SetLoadAddress (pc, &process->GetTarget());
320254721Semaste
321254721Semaste    // If we don't have a Module for some reason, we're not going to find symbol/function information - just
322254721Semaste    // stick in some reasonable defaults and hope we can unwind past this frame.
323254721Semaste    ModuleSP pc_module_sp (m_current_pc.GetModule());
324254721Semaste    if (!m_current_pc.IsValid() || !pc_module_sp)
325254721Semaste    {
326254721Semaste        UnwindLogMsg ("using architectural default unwind method");
327254721Semaste
328254721Semaste        // Test the pc value to see if we know it's in an unmapped/non-executable region of memory.
329254721Semaste        uint32_t permissions;
330254721Semaste        if (process->GetLoadAddressPermissions(pc, permissions)
331254721Semaste            && (permissions & ePermissionsExecutable) == 0)
332254721Semaste        {
333254721Semaste            // If this is the second frame off the stack, we may have unwound the first frame
334254721Semaste            // incorrectly.  But using the architecture default unwind plan may get us back on
335254721Semaste            // track -- albeit possibly skipping a real frame.  Give this frame a clearly-invalid
336254721Semaste            // pc and see if we can get any further.
337254721Semaste            if (GetNextFrame().get() && GetNextFrame()->IsValid() && GetNextFrame()->IsFrameZero())
338254721Semaste            {
339254721Semaste                UnwindLogMsg ("had a pc of 0x%" PRIx64 " which is not in executable memory but on frame 1 -- allowing it once.",
340254721Semaste                         (uint64_t) pc);
341254721Semaste                m_frame_type = eSkipFrame;
342254721Semaste            }
343254721Semaste            else
344254721Semaste            {
345254721Semaste                // anywhere other than the second frame, a non-executable pc means we're off in the weeds -- stop now.
346254721Semaste                m_frame_type = eNotAValidFrame;
347269024Semaste                UnwindLogMsg ("pc is in a non-executable section of memory and this isn't the 2nd frame in the stack walk.");
348254721Semaste                return;
349254721Semaste            }
350254721Semaste        }
351254721Semaste
352254721Semaste        if (abi)
353254721Semaste        {
354254721Semaste            m_fast_unwind_plan_sp.reset ();
355254721Semaste            m_full_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
356254721Semaste            abi->CreateDefaultUnwindPlan(*m_full_unwind_plan_sp);
357254721Semaste            if (m_frame_type != eSkipFrame)  // don't override eSkipFrame
358254721Semaste            {
359254721Semaste                m_frame_type = eNormalFrame;
360254721Semaste            }
361254721Semaste            m_all_registers_available = false;
362254721Semaste            m_current_offset = -1;
363254721Semaste            m_current_offset_backed_up_one = -1;
364254721Semaste            addr_t cfa_regval = LLDB_INVALID_ADDRESS;
365254721Semaste            int row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
366254721Semaste            UnwindPlan::RowSP row = m_full_unwind_plan_sp->GetRowForFunctionOffset(0);
367254721Semaste            if (row.get())
368254721Semaste            {
369254721Semaste                uint32_t cfa_regnum = row->GetCFARegister();
370254721Semaste                int cfa_offset = row->GetCFAOffset();
371254721Semaste                if (!ReadGPRValue (row_register_kind, cfa_regnum, cfa_regval))
372254721Semaste                {
373254721Semaste                    UnwindLogMsg ("failed to get cfa value");
374254721Semaste                    if (m_frame_type != eSkipFrame)   // don't override eSkipFrame
375254721Semaste                    {
376254721Semaste                        m_frame_type = eNormalFrame;
377254721Semaste                    }
378254721Semaste                    return;
379254721Semaste                }
380254721Semaste                m_cfa = cfa_regval + cfa_offset;
381254721Semaste
382254721Semaste                // A couple of sanity checks..
383254721Semaste                if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
384254721Semaste                {
385254721Semaste                    UnwindLogMsg ("could not find a valid cfa address");
386254721Semaste                    m_frame_type = eNotAValidFrame;
387254721Semaste                    return;
388254721Semaste                }
389254721Semaste
390254721Semaste                // cfa_regval should point into the stack memory; if we can query memory region permissions,
391254721Semaste                // see if the memory is allocated & readable.
392254721Semaste                if (process->GetLoadAddressPermissions(cfa_regval, permissions)
393254721Semaste                    && (permissions & ePermissionsReadable) == 0)
394254721Semaste                {
395254721Semaste                    m_frame_type = eNotAValidFrame;
396269024Semaste                    UnwindLogMsg ("the CFA points to a region of memory that is not readable");
397254721Semaste                    return;
398254721Semaste                }
399254721Semaste            }
400254721Semaste            else
401254721Semaste            {
402254721Semaste                UnwindLogMsg ("could not find a row for function offset zero");
403254721Semaste                m_frame_type = eNotAValidFrame;
404254721Semaste                return;
405254721Semaste            }
406254721Semaste
407254721Semaste            UnwindLogMsg ("initialized frame cfa is 0x%" PRIx64, (uint64_t) m_cfa);
408254721Semaste            return;
409254721Semaste        }
410254721Semaste        m_frame_type = eNotAValidFrame;
411269024Semaste        UnwindLogMsg ("could not find any symbol for this pc, or a default unwind plan, to continue unwind.");
412254721Semaste        return;
413254721Semaste    }
414254721Semaste
415263363Semaste    bool resolve_tail_call_address = true; // m_current_pc can be one past the address range of the function...
416269024Semaste                                           // This will handle the case where the saved pc does not point to
417269024Semaste                                           // a function/symbol because it is beyond the bounds of the correct
418269024Semaste                                           // function and there's no symbol there.  ResolveSymbolContextForAddress
419269024Semaste                                           // will fail to find a symbol, back up the pc by 1 and re-search.
420263363Semaste    uint32_t resolved_scope = pc_module_sp->ResolveSymbolContextForAddress (m_current_pc,
421263363Semaste                                                                            eSymbolContextFunction | eSymbolContextSymbol,
422263363Semaste                                                                            m_sym_ctx, resolve_tail_call_address);
423263363Semaste
424254721Semaste    // We require that eSymbolContextSymbol be successfully filled in or this context is of no use to us.
425263363Semaste    if ((resolved_scope & eSymbolContextSymbol) == eSymbolContextSymbol)
426254721Semaste    {
427254721Semaste        m_sym_ctx_valid = true;
428254721Semaste    }
429254721Semaste
430254721Semaste    AddressRange addr_range;
431254721Semaste    if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false, addr_range))
432254721Semaste    {
433254721Semaste        m_sym_ctx_valid = false;
434254721Semaste    }
435254721Semaste
436254721Semaste    bool decr_pc_and_recompute_addr_range = false;
437254721Semaste
438254721Semaste    // If the symbol lookup failed...
439254721Semaste    if (m_sym_ctx_valid == false)
440254721Semaste       decr_pc_and_recompute_addr_range = true;
441254721Semaste
442269024Semaste    // Or if we're in the middle of the stack (and not "above" an asynchronous event like sigtramp),
443269024Semaste    // and our "current" pc is the start of a function...
444254721Semaste    if (m_sym_ctx_valid
445269024Semaste        && GetNextFrame()->m_frame_type != eTrapHandlerFrame
446254721Semaste        && GetNextFrame()->m_frame_type != eDebuggerFrame
447254721Semaste        && addr_range.GetBaseAddress().IsValid()
448269024Semaste        && addr_range.GetBaseAddress().GetSection() == m_current_pc.GetSection()
449269024Semaste        && addr_range.GetBaseAddress().GetOffset() == m_current_pc.GetOffset())
450254721Semaste    {
451269024Semaste        decr_pc_and_recompute_addr_range = true;
452269024Semaste    }
453269024Semaste
454269024Semaste    // We need to back up the pc by 1 byte and re-search for the Symbol to handle the case where the "saved pc"
455269024Semaste    // value is pointing to the next function, e.g. if a function ends with a CALL instruction.
456269024Semaste    // FIXME this may need to be an architectural-dependent behavior; if so we'll need to add a member function
457269024Semaste    // to the ABI plugin and consult that.
458269024Semaste    if (decr_pc_and_recompute_addr_range)
459269024Semaste    {
460269024Semaste        Address temporary_pc(m_current_pc);
461269024Semaste        temporary_pc.SetOffset(m_current_pc.GetOffset() - 1);
462269024Semaste        m_sym_ctx.Clear(false);
463269024Semaste        m_sym_ctx_valid = false;
464269024Semaste        if ((pc_module_sp->ResolveSymbolContextForAddress (temporary_pc, eSymbolContextFunction| eSymbolContextSymbol, m_sym_ctx) & eSymbolContextSymbol) == eSymbolContextSymbol)
465254721Semaste        {
466269024Semaste            m_sym_ctx_valid = true;
467254721Semaste        }
468269024Semaste        if (!m_sym_ctx.GetAddressRange (eSymbolContextFunction | eSymbolContextSymbol, 0, false,  addr_range))
469269024Semaste        {
470269024Semaste            m_sym_ctx_valid = false;
471269024Semaste        }
472254721Semaste    }
473254721Semaste
474254721Semaste    // If we were able to find a symbol/function, set addr_range_ptr to the bounds of that symbol/function.
475254721Semaste    // else treat the current pc value as the start_pc and record no offset.
476254721Semaste    if (addr_range.GetBaseAddress().IsValid())
477254721Semaste    {
478254721Semaste        m_start_pc = addr_range.GetBaseAddress();
479254721Semaste        m_current_offset = m_current_pc.GetOffset() - m_start_pc.GetOffset();
480254721Semaste        m_current_offset_backed_up_one = m_current_offset;
481254721Semaste        if (decr_pc_and_recompute_addr_range && m_current_offset_backed_up_one > 0)
482254721Semaste        {
483254721Semaste            m_current_offset_backed_up_one--;
484254721Semaste            if (m_sym_ctx_valid)
485254721Semaste                m_current_pc.SetOffset(m_current_pc.GetOffset() - 1);
486254721Semaste        }
487254721Semaste    }
488254721Semaste    else
489254721Semaste    {
490254721Semaste        m_start_pc = m_current_pc;
491254721Semaste        m_current_offset = -1;
492254721Semaste        m_current_offset_backed_up_one = -1;
493254721Semaste    }
494254721Semaste
495269024Semaste    if (IsTrapHandlerSymbol (process, m_sym_ctx))
496254721Semaste    {
497269024Semaste        m_frame_type = eTrapHandlerFrame;
498254721Semaste    }
499254721Semaste    else
500254721Semaste    {
501254721Semaste        // FIXME:  Detect eDebuggerFrame here.
502254721Semaste        if (m_frame_type != eSkipFrame) // don't override eSkipFrame
503254721Semaste        {
504254721Semaste            m_frame_type = eNormalFrame;
505254721Semaste        }
506254721Semaste    }
507254721Semaste
508254721Semaste    // We've set m_frame_type and m_sym_ctx before this call.
509254721Semaste    m_fast_unwind_plan_sp = GetFastUnwindPlanForFrame ();
510254721Semaste
511254721Semaste    UnwindPlan::RowSP active_row;
512254721Semaste    int cfa_offset = 0;
513254721Semaste    int row_register_kind = -1;
514254721Semaste
515254721Semaste    // Try to get by with just the fast UnwindPlan if possible - the full UnwindPlan may be expensive to get
516254721Semaste    // (e.g. if we have to parse the entire eh_frame section of an ObjectFile for the first time.)
517254721Semaste
518254721Semaste    if (m_fast_unwind_plan_sp && m_fast_unwind_plan_sp->PlanValidAtAddress (m_current_pc))
519254721Semaste    {
520254721Semaste        active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
521254721Semaste        row_register_kind = m_fast_unwind_plan_sp->GetRegisterKind ();
522254721Semaste        if (active_row.get() && log)
523254721Semaste        {
524254721Semaste            StreamString active_row_strm;
525254721Semaste            active_row->Dump(active_row_strm, m_fast_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
526254721Semaste            UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
527254721Semaste        }
528254721Semaste    }
529254721Semaste    else
530254721Semaste    {
531254721Semaste        m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
532269024Semaste        int valid_offset = -1;
533269024Semaste        if (IsUnwindPlanValidForCurrentPC(m_full_unwind_plan_sp, valid_offset))
534254721Semaste        {
535269024Semaste            active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (valid_offset);
536254721Semaste            row_register_kind = m_full_unwind_plan_sp->GetRegisterKind ();
537254721Semaste            if (active_row.get() && log)
538254721Semaste            {
539254721Semaste                StreamString active_row_strm;
540254721Semaste                active_row->Dump(active_row_strm, m_full_unwind_plan_sp.get(), &m_thread, m_start_pc.GetLoadAddress(exe_ctx.GetTargetPtr()));
541254721Semaste                UnwindLogMsg ("active row: %s", active_row_strm.GetString().c_str());
542254721Semaste            }
543254721Semaste        }
544254721Semaste    }
545254721Semaste
546254721Semaste    if (!active_row.get())
547254721Semaste    {
548254721Semaste        m_frame_type = eNotAValidFrame;
549269024Semaste        UnwindLogMsg ("could not find unwind row for this pc");
550254721Semaste        return;
551254721Semaste    }
552254721Semaste
553254721Semaste    addr_t cfa_regval = LLDB_INVALID_ADDRESS;
554254721Semaste    if (!ReadGPRValue (row_register_kind, active_row->GetCFARegister(), cfa_regval))
555254721Semaste    {
556254721Semaste        UnwindLogMsg ("failed to get cfa reg %d/%d", row_register_kind, active_row->GetCFARegister());
557254721Semaste        m_frame_type = eNotAValidFrame;
558254721Semaste        return;
559254721Semaste    }
560254721Semaste
561254721Semaste    cfa_offset = active_row->GetCFAOffset ();
562254721Semaste    m_cfa = cfa_regval + cfa_offset;
563254721Semaste
564254721Semaste    UnwindLogMsg ("cfa_regval = 0x%16.16" PRIx64 " (cfa_regval = 0x%16.16" PRIx64 ", cfa_offset = %i)", m_cfa, cfa_regval, cfa_offset);
565254721Semaste
566254721Semaste    // A couple of sanity checks..
567254721Semaste    if (cfa_regval == LLDB_INVALID_ADDRESS || cfa_regval == 0 || cfa_regval == 1)
568254721Semaste    {
569254721Semaste        UnwindLogMsg ("could not find a valid cfa address");
570254721Semaste        m_frame_type = eNotAValidFrame;
571254721Semaste        return;
572254721Semaste    }
573254721Semaste
574254721Semaste    // If we have a bad stack setup, we can get the same CFA value multiple times -- or even
575254721Semaste    // more devious, we can actually oscillate between two CFA values.  Detect that here and
576254721Semaste    // break out to avoid a possible infinite loop in lldb trying to unwind the stack.
577254721Semaste    addr_t next_frame_cfa;
578254721Semaste    addr_t next_next_frame_cfa = LLDB_INVALID_ADDRESS;
579254721Semaste    if (GetNextFrame().get() && GetNextFrame()->GetCFA(next_frame_cfa))
580254721Semaste    {
581254721Semaste        bool repeating_frames = false;
582254721Semaste        if (next_frame_cfa == m_cfa)
583254721Semaste        {
584254721Semaste            repeating_frames = true;
585254721Semaste        }
586254721Semaste        else
587254721Semaste        {
588254721Semaste            if (GetNextFrame()->GetNextFrame() && GetNextFrame()->GetNextFrame()->GetCFA(next_next_frame_cfa)
589254721Semaste                && next_next_frame_cfa == m_cfa)
590254721Semaste            {
591254721Semaste                repeating_frames = true;
592254721Semaste            }
593254721Semaste        }
594254721Semaste        if (repeating_frames && abi->FunctionCallsChangeCFA())
595254721Semaste        {
596254721Semaste            UnwindLogMsg ("same CFA address as next frame, assuming the unwind is looping - stopping");
597254721Semaste            m_frame_type = eNotAValidFrame;
598254721Semaste            return;
599254721Semaste        }
600254721Semaste    }
601254721Semaste
602254721Semaste    UnwindLogMsg ("initialized frame current pc is 0x%" PRIx64 " cfa is 0x%" PRIx64,
603254721Semaste            (uint64_t) m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr()), (uint64_t) m_cfa);
604254721Semaste}
605254721Semaste
606254721Semaste
607254721Semastebool
608254721SemasteRegisterContextLLDB::IsFrameZero () const
609254721Semaste{
610254721Semaste    return m_frame_number == 0;
611254721Semaste}
612254721Semaste
613254721Semaste
614254721Semaste// Find a fast unwind plan for this frame, if possible.
615254721Semaste//
616254721Semaste// On entry to this method,
617254721Semaste//
618269024Semaste//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
619254721Semaste//   2. m_sym_ctx should already be filled in, and
620254721Semaste//   3. m_current_pc should have the current pc value for this frame
621254721Semaste//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
622254721Semaste
623254721SemasteUnwindPlanSP
624254721SemasteRegisterContextLLDB::GetFastUnwindPlanForFrame ()
625254721Semaste{
626254721Semaste    UnwindPlanSP unwind_plan_sp;
627254721Semaste    ModuleSP pc_module_sp (m_current_pc.GetModule());
628254721Semaste
629254721Semaste    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
630254721Semaste        return unwind_plan_sp;
631254721Semaste
632254721Semaste    if (IsFrameZero ())
633254721Semaste        return unwind_plan_sp;
634254721Semaste
635254721Semaste    FuncUnwindersSP func_unwinders_sp (pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx));
636254721Semaste    if (!func_unwinders_sp)
637254721Semaste        return unwind_plan_sp;
638254721Semaste
639254721Semaste    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.
640269024Semaste    if (m_frame_type == eTrapHandlerFrame || m_frame_type == eDebuggerFrame)
641254721Semaste        return unwind_plan_sp;
642254721Semaste
643254721Semaste    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanFastUnwind (m_thread);
644254721Semaste    if (unwind_plan_sp)
645254721Semaste    {
646254721Semaste        if (unwind_plan_sp->PlanValidAtAddress (m_current_pc))
647254721Semaste        {
648254721Semaste            Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
649254721Semaste            if (log && log->GetVerbose())
650254721Semaste            {
651254721Semaste                if (m_fast_unwind_plan_sp)
652254721Semaste                    UnwindLogMsgVerbose ("frame, and has a fast UnwindPlan");
653254721Semaste                else
654254721Semaste                    UnwindLogMsgVerbose ("frame");
655254721Semaste            }
656254721Semaste            m_frame_type = eNormalFrame;
657254721Semaste            return unwind_plan_sp;
658254721Semaste        }
659254721Semaste        else
660254721Semaste        {
661254721Semaste            unwind_plan_sp.reset();
662254721Semaste        }
663254721Semaste    }
664254721Semaste    return unwind_plan_sp;
665254721Semaste}
666254721Semaste
667254721Semaste// On entry to this method,
668254721Semaste//
669269024Semaste//   1. m_frame_type should already be set to eTrapHandlerFrame/eDebuggerFrame if either of those are correct,
670254721Semaste//   2. m_sym_ctx should already be filled in, and
671254721Semaste//   3. m_current_pc should have the current pc value for this frame
672254721Semaste//   4. m_current_offset_backed_up_one should have the current byte offset into the function, maybe backed up by 1, -1 if unknown
673254721Semaste
674254721SemasteUnwindPlanSP
675254721SemasteRegisterContextLLDB::GetFullUnwindPlanForFrame ()
676254721Semaste{
677254721Semaste    UnwindPlanSP unwind_plan_sp;
678254721Semaste    UnwindPlanSP arch_default_unwind_plan_sp;
679254721Semaste    ExecutionContext exe_ctx(m_thread.shared_from_this());
680254721Semaste    Process *process = exe_ctx.GetProcessPtr();
681254721Semaste    ABI *abi = process ? process->GetABI().get() : NULL;
682254721Semaste    if (abi)
683254721Semaste    {
684254721Semaste        arch_default_unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
685254721Semaste        abi->CreateDefaultUnwindPlan(*arch_default_unwind_plan_sp);
686254721Semaste    }
687263363Semaste    else
688263363Semaste    {
689263363Semaste        UnwindLogMsg ("unable to get architectural default UnwindPlan from ABI plugin");
690263363Semaste    }
691254721Semaste
692254721Semaste    bool behaves_like_zeroth_frame = false;
693254721Semaste    if (IsFrameZero ()
694269024Semaste        || GetNextFrame()->m_frame_type == eTrapHandlerFrame
695254721Semaste        || GetNextFrame()->m_frame_type == eDebuggerFrame)
696254721Semaste    {
697254721Semaste        behaves_like_zeroth_frame = true;
698254721Semaste        // If this frame behaves like a 0th frame (currently executing or
699254721Semaste        // interrupted asynchronously), all registers can be retrieved.
700254721Semaste        m_all_registers_available = true;
701254721Semaste    }
702254721Semaste
703254721Semaste    // If we've done a jmp 0x0 / bl 0x0 (called through a null function pointer) so the pc is 0x0
704254721Semaste    // in the zeroth frame, we need to use the "unwind at first instruction" arch default UnwindPlan
705254721Semaste    // Also, if this Process can report on memory region attributes, any non-executable region means
706254721Semaste    // we jumped through a bad function pointer - handle the same way as 0x0.
707263363Semaste    // Note, if we have a symbol context & a symbol, we don't want to follow this code path.  This is
708263363Semaste    // for jumping to memory regions without any information available.
709254721Semaste
710263363Semaste    if ((!m_sym_ctx_valid || m_sym_ctx.symbol == NULL) && behaves_like_zeroth_frame && m_current_pc.IsValid())
711254721Semaste    {
712254721Semaste        uint32_t permissions;
713254721Semaste        addr_t current_pc_addr = m_current_pc.GetLoadAddress (exe_ctx.GetTargetPtr());
714254721Semaste        if (current_pc_addr == 0
715269024Semaste            || (process->GetLoadAddressPermissions (current_pc_addr, permissions)
716254721Semaste                && (permissions & ePermissionsExecutable) == 0))
717254721Semaste        {
718254721Semaste            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
719254721Semaste            abi->CreateFunctionEntryUnwindPlan(*unwind_plan_sp);
720254721Semaste            m_frame_type = eNormalFrame;
721254721Semaste            return unwind_plan_sp;
722254721Semaste        }
723254721Semaste    }
724254721Semaste
725254721Semaste    // No Module for the current pc, try using the architecture default unwind.
726254721Semaste    ModuleSP pc_module_sp (m_current_pc.GetModule());
727254721Semaste    if (!m_current_pc.IsValid() || !pc_module_sp || pc_module_sp->GetObjectFile() == NULL)
728254721Semaste    {
729254721Semaste        m_frame_type = eNormalFrame;
730254721Semaste        return arch_default_unwind_plan_sp;
731254721Semaste    }
732254721Semaste
733254721Semaste    FuncUnwindersSP func_unwinders_sp;
734254721Semaste    if (m_sym_ctx_valid)
735254721Semaste    {
736254721Semaste        func_unwinders_sp = pc_module_sp->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
737254721Semaste    }
738254721Semaste
739254721Semaste    // No FuncUnwinders available for this pc (i.e. a stripped function symbol and -fomit-frame-pointer).
740254721Semaste    // Try using the eh_frame information relative to the current PC,
741254721Semaste    // and finally fall back on the architectural default unwind.
742254721Semaste    if (!func_unwinders_sp)
743254721Semaste    {
744254721Semaste        DWARFCallFrameInfo *eh_frame = pc_module_sp && pc_module_sp->GetObjectFile() ?
745254721Semaste            pc_module_sp->GetObjectFile()->GetUnwindTable().GetEHFrameInfo() : nullptr;
746254721Semaste
747254721Semaste        m_frame_type = eNormalFrame;
748254721Semaste        if (eh_frame && m_current_pc.IsValid())
749254721Semaste        {
750254721Semaste            unwind_plan_sp.reset (new UnwindPlan (lldb::eRegisterKindGeneric));
751254721Semaste            // Even with -fomit-frame-pointer, we can try eh_frame to get back on track.
752254721Semaste            if (eh_frame->GetUnwindPlan (m_current_pc, *unwind_plan_sp))
753254721Semaste                return unwind_plan_sp;
754254721Semaste            else
755254721Semaste                unwind_plan_sp.reset();
756254721Semaste        }
757254721Semaste        return arch_default_unwind_plan_sp;
758254721Semaste    }
759254721Semaste
760254721Semaste    // If we're in _sigtramp(), unwinding past this frame requires special knowledge.  On Mac OS X this knowledge
761254721Semaste    // is properly encoded in the eh_frame section, so prefer that if available.
762254721Semaste    // On other platforms we may need to provide a platform-specific UnwindPlan which encodes the details of
763254721Semaste    // how to unwind out of sigtramp.
764269024Semaste    if (m_frame_type == eTrapHandlerFrame)
765254721Semaste    {
766254721Semaste        m_fast_unwind_plan_sp.reset();
767254721Semaste        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
768269024Semaste        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc) && unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolYes)
769269024Semaste        {
770254721Semaste            return unwind_plan_sp;
771269024Semaste        }
772254721Semaste    }
773254721Semaste
774254721Semaste    // Ask the DynamicLoader if the eh_frame CFI should be trusted in this frame even when it's frame zero
775254721Semaste    // This comes up if we have hand-written functions in a Module and hand-written eh_frame.  The assembly
776254721Semaste    // instruction inspection may fail and the eh_frame CFI were probably written with some care to do the
777254721Semaste    // right thing.  It'd be nice if there was a way to ask the eh_frame directly if it is asynchronous
778254721Semaste    // (can be trusted at every instruction point) or synchronous (the normal case - only at call sites).
779254721Semaste    // But there is not.
780254721Semaste    if (process && process->GetDynamicLoader() && process->GetDynamicLoader()->AlwaysRelyOnEHUnwindInfo (m_sym_ctx))
781254721Semaste    {
782254721Semaste        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
783254721Semaste        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
784254721Semaste        {
785254721Semaste            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan because the DynamicLoader suggested we prefer it",
786254721Semaste                           unwind_plan_sp->GetSourceName().GetCString());
787254721Semaste            return unwind_plan_sp;
788254721Semaste        }
789254721Semaste    }
790254721Semaste
791254721Semaste    // Typically the NonCallSite UnwindPlan is the unwind created by inspecting the assembly language instructions
792254721Semaste    if (behaves_like_zeroth_frame)
793254721Semaste    {
794254721Semaste        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
795254721Semaste        if (unwind_plan_sp && unwind_plan_sp->PlanValidAtAddress (m_current_pc))
796254721Semaste        {
797269024Semaste            if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
798269024Semaste            {
799269024Semaste                // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
800269024Semaste                // don't have any eh_frame instructions available.
801269024Semaste                // The assembly profilers work really well with compiler-generated functions but hand-written
802269024Semaste                // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
803269024Semaste                // UnwindPlan in case this doesn't work out when we try to unwind.
804269024Semaste                m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
805269024Semaste            }
806254721Semaste            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
807254721Semaste            return unwind_plan_sp;
808254721Semaste        }
809254721Semaste    }
810254721Semaste
811254721Semaste    // Typically this is unwind info from an eh_frame section intended for exception handling; only valid at call sites
812254721Semaste    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtCallSite (m_current_offset_backed_up_one);
813269024Semaste    int valid_offset = -1;
814269024Semaste    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
815254721Semaste    {
816254721Semaste        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
817254721Semaste        return unwind_plan_sp;
818254721Semaste    }
819254721Semaste
820254721Semaste    // We'd prefer to use an UnwindPlan intended for call sites when we're at a call site but if we've
821254721Semaste    // struck out on that, fall back to using the non-call-site assembly inspection UnwindPlan if possible.
822254721Semaste    unwind_plan_sp = func_unwinders_sp->GetUnwindPlanAtNonCallSite (m_thread);
823269024Semaste    if (unwind_plan_sp->GetSourcedFromCompiler() == eLazyBoolNo)
824254721Semaste    {
825269024Semaste        // We probably have an UnwindPlan created by inspecting assembly instructions, and we probably
826269024Semaste        // don't have any eh_frame instructions available.
827269024Semaste        // The assembly profilers work really well with compiler-generated functions but hand-written
828269024Semaste        // assembly can be problematic.  We'll set the architecture default UnwindPlan as our fallback
829269024Semaste        // UnwindPlan in case this doesn't work out when we try to unwind.
830269024Semaste        m_fallback_unwind_plan_sp = arch_default_unwind_plan_sp;
831269024Semaste    }
832269024Semaste
833269024Semaste    if (IsUnwindPlanValidForCurrentPC(unwind_plan_sp, valid_offset))
834269024Semaste    {
835254721Semaste        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
836254721Semaste        return unwind_plan_sp;
837254721Semaste    }
838254721Semaste
839263363Semaste    // If we're on the first instruction of a function, and we have an architectural default UnwindPlan
840263363Semaste    // for the initial instruction of a function, use that.
841263363Semaste    if (m_current_offset_backed_up_one == 0)
842263363Semaste    {
843263363Semaste        unwind_plan_sp = func_unwinders_sp->GetUnwindPlanArchitectureDefaultAtFunctionEntry (m_thread);
844263363Semaste        if (unwind_plan_sp)
845263363Semaste        {
846263363Semaste            UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", unwind_plan_sp->GetSourceName().GetCString());
847263363Semaste            return unwind_plan_sp;
848263363Semaste        }
849263363Semaste    }
850263363Semaste
851254721Semaste    // If nothing else, use the architectural default UnwindPlan and hope that does the job.
852263363Semaste    if (arch_default_unwind_plan_sp)
853263363Semaste        UnwindLogMsgVerbose ("frame uses %s for full UnwindPlan", arch_default_unwind_plan_sp->GetSourceName().GetCString());
854263363Semaste    else
855263363Semaste        UnwindLogMsg ("Unable to find any UnwindPlan for full unwind of this frame.");
856263363Semaste
857254721Semaste    return arch_default_unwind_plan_sp;
858254721Semaste}
859254721Semaste
860254721Semaste
861254721Semastevoid
862254721SemasteRegisterContextLLDB::InvalidateAllRegisters ()
863254721Semaste{
864254721Semaste    m_frame_type = eNotAValidFrame;
865254721Semaste}
866254721Semaste
867254721Semastesize_t
868254721SemasteRegisterContextLLDB::GetRegisterCount ()
869254721Semaste{
870254721Semaste    return m_thread.GetRegisterContext()->GetRegisterCount();
871254721Semaste}
872254721Semaste
873254721Semasteconst RegisterInfo *
874254721SemasteRegisterContextLLDB::GetRegisterInfoAtIndex (size_t reg)
875254721Semaste{
876254721Semaste    return m_thread.GetRegisterContext()->GetRegisterInfoAtIndex (reg);
877254721Semaste}
878254721Semaste
879254721Semastesize_t
880254721SemasteRegisterContextLLDB::GetRegisterSetCount ()
881254721Semaste{
882254721Semaste    return m_thread.GetRegisterContext()->GetRegisterSetCount ();
883254721Semaste}
884254721Semaste
885254721Semasteconst RegisterSet *
886254721SemasteRegisterContextLLDB::GetRegisterSet (size_t reg_set)
887254721Semaste{
888254721Semaste    return m_thread.GetRegisterContext()->GetRegisterSet (reg_set);
889254721Semaste}
890254721Semaste
891254721Semasteuint32_t
892254721SemasteRegisterContextLLDB::ConvertRegisterKindToRegisterNumber (uint32_t kind, uint32_t num)
893254721Semaste{
894254721Semaste    return m_thread.GetRegisterContext()->ConvertRegisterKindToRegisterNumber (kind, num);
895254721Semaste}
896254721Semaste
897254721Semastebool
898254721SemasteRegisterContextLLDB::ReadRegisterValueFromRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
899254721Semaste                                                            const RegisterInfo *reg_info,
900254721Semaste                                                            RegisterValue &value)
901254721Semaste{
902254721Semaste    if (!IsValid())
903254721Semaste        return false;
904254721Semaste    bool success = false;
905254721Semaste
906254721Semaste    switch (regloc.type)
907254721Semaste    {
908254721Semaste    case UnwindLLDB::RegisterLocation::eRegisterInRegister:
909254721Semaste        {
910254721Semaste            const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
911254721Semaste
912254721Semaste            if (!other_reg_info)
913254721Semaste                return false;
914254721Semaste
915254721Semaste            if (IsFrameZero ())
916254721Semaste            {
917254721Semaste                success = m_thread.GetRegisterContext()->ReadRegister (other_reg_info, value);
918254721Semaste            }
919254721Semaste            else
920254721Semaste            {
921254721Semaste                success = GetNextFrame()->ReadRegister (other_reg_info, value);
922254721Semaste            }
923254721Semaste        }
924254721Semaste        break;
925254721Semaste    case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
926254721Semaste        success = value.SetUInt (regloc.location.inferred_value, reg_info->byte_size);
927254721Semaste        break;
928254721Semaste
929254721Semaste    case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
930254721Semaste        break;
931254721Semaste    case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
932254721Semaste        assert ("FIXME debugger inferior function call unwind");
933254721Semaste        break;
934254721Semaste    case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
935254721Semaste        {
936254721Semaste            Error error (ReadRegisterValueFromMemory(reg_info,
937254721Semaste                                                     regloc.location.target_memory_location,
938254721Semaste                                                     reg_info->byte_size,
939254721Semaste                                                     value));
940254721Semaste            success = error.Success();
941254721Semaste        }
942254721Semaste        break;
943254721Semaste    default:
944254721Semaste        assert ("Unknown RegisterLocation type.");
945254721Semaste        break;
946254721Semaste    }
947254721Semaste    return success;
948254721Semaste}
949254721Semaste
950254721Semastebool
951254721SemasteRegisterContextLLDB::WriteRegisterValueToRegisterLocation (lldb_private::UnwindLLDB::RegisterLocation regloc,
952254721Semaste                                                           const RegisterInfo *reg_info,
953254721Semaste                                                           const RegisterValue &value)
954254721Semaste{
955254721Semaste    if (!IsValid())
956254721Semaste        return false;
957254721Semaste
958254721Semaste    bool success = false;
959254721Semaste
960254721Semaste    switch (regloc.type)
961254721Semaste    {
962254721Semaste        case UnwindLLDB::RegisterLocation::eRegisterInRegister:
963254721Semaste            {
964254721Semaste                const RegisterInfo *other_reg_info = GetRegisterInfoAtIndex(regloc.location.register_number);
965254721Semaste                if (IsFrameZero ())
966254721Semaste                {
967254721Semaste                    success = m_thread.GetRegisterContext()->WriteRegister (other_reg_info, value);
968254721Semaste                }
969254721Semaste                else
970254721Semaste                {
971254721Semaste                    success = GetNextFrame()->WriteRegister (other_reg_info, value);
972254721Semaste                }
973254721Semaste            }
974254721Semaste            break;
975254721Semaste        case UnwindLLDB::RegisterLocation::eRegisterValueInferred:
976254721Semaste        case UnwindLLDB::RegisterLocation::eRegisterNotSaved:
977254721Semaste            break;
978254721Semaste        case UnwindLLDB::RegisterLocation::eRegisterSavedAtHostMemoryLocation:
979254721Semaste            assert ("FIXME debugger inferior function call unwind");
980254721Semaste            break;
981254721Semaste        case UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation:
982254721Semaste            {
983254721Semaste                Error error (WriteRegisterValueToMemory (reg_info,
984254721Semaste                                                         regloc.location.target_memory_location,
985254721Semaste                                                         reg_info->byte_size,
986254721Semaste                                                         value));
987254721Semaste                success = error.Success();
988254721Semaste            }
989254721Semaste            break;
990254721Semaste        default:
991254721Semaste            assert ("Unknown RegisterLocation type.");
992254721Semaste            break;
993254721Semaste    }
994254721Semaste    return success;
995254721Semaste}
996254721Semaste
997254721Semaste
998254721Semastebool
999254721SemasteRegisterContextLLDB::IsValid () const
1000254721Semaste{
1001254721Semaste    return m_frame_type != eNotAValidFrame;
1002254721Semaste}
1003254721Semaste
1004269024Semastebool
1005269024SemasteRegisterContextLLDB::IsTrapHandlerFrame () const
1006269024Semaste{
1007269024Semaste    return m_frame_type == eTrapHandlerFrame;
1008269024Semaste}
1009269024Semaste
1010254721Semaste// A skip frame is a bogus frame on the stack -- but one where we're likely to find a real frame farther
1011254721Semaste// up the stack if we keep looking.  It's always the second frame in an unwind (i.e. the first frame after
1012254721Semaste// frame zero) where unwinding can be the trickiest.  Ideally we'll mark up this frame in some way so the
1013254721Semaste// user knows we're displaying bad data and we may have skipped one frame of their real program in the
1014254721Semaste// process of getting back on track.
1015254721Semaste
1016254721Semastebool
1017254721SemasteRegisterContextLLDB::IsSkipFrame () const
1018254721Semaste{
1019254721Semaste    return m_frame_type == eSkipFrame;
1020254721Semaste}
1021254721Semaste
1022269024Semastebool
1023269024SemasteRegisterContextLLDB::IsTrapHandlerSymbol (lldb_private::Process *process, const lldb_private::SymbolContext &m_sym_ctx) const
1024269024Semaste{
1025269024Semaste    PlatformSP platform_sp (process->GetTarget().GetPlatform());
1026269024Semaste    if (platform_sp)
1027269024Semaste    {
1028269024Semaste        const std::vector<ConstString> trap_handler_names (platform_sp->GetTrapHandlerSymbolNames());
1029269024Semaste        for (ConstString name : trap_handler_names)
1030269024Semaste        {
1031269024Semaste            if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1032269024Semaste                (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1033269024Semaste            {
1034269024Semaste                return true;
1035269024Semaste            }
1036269024Semaste        }
1037269024Semaste    }
1038269024Semaste    const std::vector<ConstString> user_specified_trap_handler_names (m_parent_unwind.GetUserSpecifiedTrapHandlerFunctionNames());
1039269024Semaste    for (ConstString name : user_specified_trap_handler_names)
1040269024Semaste    {
1041269024Semaste        if ((m_sym_ctx.function && m_sym_ctx.function->GetName() == name) ||
1042269024Semaste            (m_sym_ctx.symbol   && m_sym_ctx.symbol->GetName()   == name))
1043269024Semaste        {
1044269024Semaste            return true;
1045269024Semaste        }
1046269024Semaste    }
1047269024Semaste
1048269024Semaste    return false;
1049269024Semaste}
1050269024Semaste
1051254721Semaste// Answer the question: Where did THIS frame save the CALLER frame ("previous" frame)'s register value?
1052254721Semaste
1053254721Semasteenum UnwindLLDB::RegisterSearchResult
1054254721SemasteRegisterContextLLDB::SavedLocationForRegister (uint32_t lldb_regnum, lldb_private::UnwindLLDB::RegisterLocation &regloc)
1055254721Semaste{
1056254721Semaste    // Have we already found this register location?
1057254721Semaste    if (!m_registers.empty())
1058254721Semaste    {
1059254721Semaste        std::map<uint32_t, lldb_private::UnwindLLDB::RegisterLocation>::const_iterator iterator;
1060254721Semaste        iterator = m_registers.find (lldb_regnum);
1061254721Semaste        if (iterator != m_registers.end())
1062254721Semaste        {
1063254721Semaste            regloc = iterator->second;
1064254721Semaste            UnwindLogMsg ("supplying caller's saved reg %d's location, cached", lldb_regnum);
1065254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1066254721Semaste        }
1067254721Semaste    }
1068254721Semaste
1069254721Semaste    uint32_t sp_regnum = LLDB_INVALID_REGNUM;
1070254721Semaste    uint32_t pc_regnum = LLDB_INVALID_REGNUM;
1071254721Semaste    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, eRegisterKindLLDB, sp_regnum);
1072254721Semaste    m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, eRegisterKindLLDB, pc_regnum);
1073254721Semaste
1074254721Semaste    // Are we looking for the CALLER's stack pointer?  The stack pointer is defined to be the same as THIS frame's
1075254721Semaste    // CFA so just return the CFA value.  This is true on x86-32/x86-64 at least.
1076254721Semaste    if (sp_regnum != LLDB_INVALID_REGNUM && sp_regnum == lldb_regnum)
1077254721Semaste    {
1078254721Semaste        // make sure we won't lose precision copying an addr_t (m_cfa) into a uint64_t (.inferred_value)
1079254721Semaste        assert (sizeof (addr_t) <= sizeof (uint64_t));
1080254721Semaste        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1081254721Semaste        regloc.location.inferred_value = m_cfa;
1082254721Semaste        m_registers[lldb_regnum] = regloc;
1083254721Semaste        UnwindLogMsg ("supplying caller's stack pointer (%d) value, computed from CFA", lldb_regnum);
1084254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1085254721Semaste    }
1086254721Semaste
1087254721Semaste    // Look through the available UnwindPlans for the register location.
1088254721Semaste
1089254721Semaste    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1090254721Semaste    bool have_unwindplan_regloc = false;
1091254721Semaste    RegisterKind unwindplan_registerkind = (RegisterKind)-1;
1092254721Semaste
1093254721Semaste    if (m_fast_unwind_plan_sp)
1094254721Semaste    {
1095254721Semaste        UnwindPlan::RowSP active_row = m_fast_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1096254721Semaste        unwindplan_registerkind = m_fast_unwind_plan_sp->GetRegisterKind ();
1097254721Semaste        uint32_t row_regnum;
1098254721Semaste        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1099254721Semaste        {
1100254721Semaste            UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1101254721Semaste                    lldb_regnum, (int) unwindplan_registerkind);
1102254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1103254721Semaste        }
1104254721Semaste        if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1105254721Semaste        {
1106254721Semaste            UnwindLogMsg ("supplying caller's saved reg %d's location using FastUnwindPlan", lldb_regnum);
1107254721Semaste            have_unwindplan_regloc = true;
1108254721Semaste        }
1109254721Semaste    }
1110254721Semaste
1111254721Semaste    if (!have_unwindplan_regloc)
1112254721Semaste    {
1113254721Semaste        // m_full_unwind_plan_sp being NULL means that we haven't tried to find a full UnwindPlan yet
1114254721Semaste        if (!m_full_unwind_plan_sp)
1115254721Semaste            m_full_unwind_plan_sp = GetFullUnwindPlanForFrame ();
1116254721Semaste
1117254721Semaste        if (m_full_unwind_plan_sp)
1118254721Semaste        {
1119254721Semaste            UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1120254721Semaste            unwindplan_registerkind = m_full_unwind_plan_sp->GetRegisterKind ();
1121254721Semaste            uint32_t row_regnum;
1122254721Semaste            bool row_register_rewritten_to_return_address_reg = false;
1123254721Semaste
1124254721Semaste            // If we're fetching the saved pc and this UnwindPlan defines a ReturnAddress register (e.g. lr on arm),
1125254721Semaste            // look for the return address register number in the UnwindPlan's row.
1126254721Semaste            if (lldb_regnum == pc_regnum && m_full_unwind_plan_sp->GetReturnAddressRegister() != LLDB_INVALID_REGNUM)
1127254721Semaste            {
1128254721Semaste               row_regnum = m_full_unwind_plan_sp->GetReturnAddressRegister();
1129254721Semaste               row_register_rewritten_to_return_address_reg = true;
1130254721Semaste               UnwindLogMsg ("requested caller's saved PC but this UnwindPlan uses a RA reg; getting reg %d instead",
1131254721Semaste                       row_regnum);
1132254721Semaste            }
1133254721Semaste            else
1134254721Semaste            {
1135254721Semaste                if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindLLDB, lldb_regnum, unwindplan_registerkind, row_regnum))
1136254721Semaste                {
1137254721Semaste                    if (unwindplan_registerkind == eRegisterKindGeneric)
1138254721Semaste                        UnwindLogMsg ("could not convert lldb regnum %d into eRegisterKindGeneric reg numbering scheme", lldb_regnum);
1139254721Semaste                    else
1140254721Semaste                        UnwindLogMsg ("could not convert lldb regnum %d into %d RegisterKind reg numbering scheme",
1141254721Semaste                                lldb_regnum, (int) unwindplan_registerkind);
1142254721Semaste                    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1143254721Semaste                }
1144254721Semaste            }
1145254721Semaste
1146254721Semaste            if (active_row->GetRegisterInfo (row_regnum, unwindplan_regloc))
1147254721Semaste            {
1148254721Semaste                have_unwindplan_regloc = true;
1149254721Semaste                UnwindLogMsg ("supplying caller's saved reg %d's location using %s UnwindPlan", lldb_regnum,
1150254721Semaste                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1151254721Semaste            }
1152254721Semaste
1153254721Semaste            // This is frame 0 and we're retrieving the PC and it's saved in a Return Address register and
1154254721Semaste            // it hasn't been saved anywhere yet -- that is, it's still live in the actual register.
1155254721Semaste            // Handle this specially.
1156254721Semaste
1157254721Semaste            if (have_unwindplan_regloc == false
1158254721Semaste                && row_register_rewritten_to_return_address_reg == true
1159254721Semaste                && IsFrameZero()
1160254721Semaste                && row_regnum != LLDB_INVALID_REGNUM)
1161254721Semaste            {
1162254721Semaste                uint32_t ra_regnum_in_lldb_reg_numbering;
1163254721Semaste                if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, row_regnum, eRegisterKindLLDB, ra_regnum_in_lldb_reg_numbering))
1164254721Semaste                {
1165254721Semaste                    lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1166254721Semaste                    new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1167254721Semaste                    new_regloc.location.register_number = ra_regnum_in_lldb_reg_numbering;
1168254721Semaste                    m_registers[lldb_regnum] = new_regloc;
1169254721Semaste                    regloc = new_regloc;
1170254721Semaste                    UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0, saved in %d", lldb_regnum, ra_regnum_in_lldb_reg_numbering);
1171254721Semaste                    return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1172254721Semaste                }
1173254721Semaste            }
1174254721Semaste
1175254721Semaste            // If this architecture stores the return address in a register (it defines a Return Address register)
1176254721Semaste            // and we're on a non-zero stack frame and the Full UnwindPlan says that the pc is stored in the
1177254721Semaste            // RA registers (e.g. lr on arm), then we know that the full unwindplan is not trustworthy -- this
1178254721Semaste            // is an impossible situation and the instruction emulation code has likely been misled.
1179254721Semaste            // If this stack frame meets those criteria, we need to throw away the Full UnwindPlan that the
1180254721Semaste            // instruction emulation came up with and fall back to the architecture's Default UnwindPlan so
1181254721Semaste            // the stack walk can get past this point.
1182254721Semaste
1183254721Semaste            // Special note:  If the Full UnwindPlan was generated from the compiler, don't second-guess it
1184254721Semaste            // when we're at a call site location.
1185254721Semaste
1186254721Semaste            // arch_default_ra_regnum is the return address register # in the Full UnwindPlan register numbering
1187254721Semaste            uint32_t arch_default_ra_regnum = LLDB_INVALID_REGNUM;
1188254721Semaste            if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_RA, unwindplan_registerkind, arch_default_ra_regnum)
1189254721Semaste                && arch_default_ra_regnum != LLDB_INVALID_REGNUM
1190254721Semaste                && pc_regnum != LLDB_INVALID_REGNUM
1191254721Semaste                && pc_regnum == lldb_regnum
1192254721Semaste                && unwindplan_regloc.IsInOtherRegister()
1193254721Semaste                && unwindplan_regloc.GetRegisterNumber() == arch_default_ra_regnum
1194254721Semaste                && m_full_unwind_plan_sp->GetSourcedFromCompiler() != eLazyBoolYes
1195254721Semaste                && !m_all_registers_available)
1196254721Semaste            {
1197254721Semaste                UnwindLogMsg ("%s UnwindPlan tried to restore the pc from the link register but this is a non-zero frame",
1198254721Semaste                              m_full_unwind_plan_sp->GetSourceName().GetCString());
1199254721Semaste
1200254721Semaste                // Throw away the full unwindplan; install the arch default unwindplan
1201269024Semaste                if (TryFallbackUnwindPlan())
1202254721Semaste                {
1203269024Semaste                    // Now re-fetch the pc value we're searching for
1204269024Semaste                    uint32_t arch_default_pc_reg = LLDB_INVALID_REGNUM;
1205269024Semaste                    UnwindPlan::RowSP active_row = m_full_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1206269024Semaste                    if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, m_full_unwind_plan_sp->GetRegisterKind(), arch_default_pc_reg)
1207269024Semaste                        && arch_default_pc_reg != LLDB_INVALID_REGNUM
1208269024Semaste                        && active_row
1209269024Semaste                        && active_row->GetRegisterInfo (arch_default_pc_reg, unwindplan_regloc))
1210269024Semaste                    {
1211269024Semaste                        have_unwindplan_regloc = true;
1212269024Semaste                    }
1213269024Semaste                    else
1214269024Semaste                    {
1215269024Semaste                        have_unwindplan_regloc = false;
1216269024Semaste                    }
1217254721Semaste                }
1218254721Semaste            }
1219254721Semaste        }
1220254721Semaste    }
1221254721Semaste
1222254721Semaste
1223254721Semaste    ExecutionContext exe_ctx(m_thread.shared_from_this());
1224254721Semaste    Process *process = exe_ctx.GetProcessPtr();
1225254721Semaste    if (have_unwindplan_regloc == false)
1226254721Semaste    {
1227254721Semaste        // If a volatile register is being requested, we don't want to forward the next frame's register contents
1228254721Semaste        // up the stack -- the register is not retrievable at this frame.
1229254721Semaste        ABI *abi = process ? process->GetABI().get() : NULL;
1230254721Semaste        if (abi)
1231254721Semaste        {
1232254721Semaste            const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1233254721Semaste            if (reg_info && abi->RegisterIsVolatile (reg_info))
1234254721Semaste            {
1235263363Semaste                UnwindLogMsg ("did not supply reg location for %d (%s) because it is volatile",
1236263363Semaste                    lldb_regnum, reg_info->name ? reg_info->name : "??");
1237254721Semaste                return UnwindLLDB::RegisterSearchResult::eRegisterIsVolatile;
1238254721Semaste            }
1239254721Semaste        }
1240254721Semaste
1241254721Semaste        if (IsFrameZero ())
1242254721Semaste        {
1243254721Semaste            // This is frame 0 - we should return the actual live register context value
1244254721Semaste            lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1245254721Semaste            new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1246254721Semaste            new_regloc.location.register_number = lldb_regnum;
1247254721Semaste            m_registers[lldb_regnum] = new_regloc;
1248254721Semaste            regloc = new_regloc;
1249254721Semaste            UnwindLogMsg ("supplying caller's register %d from the live RegisterContext at frame 0", lldb_regnum);
1250254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1251254721Semaste        }
1252254721Semaste        else
1253254721Semaste        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1254254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1255254721Semaste    }
1256254721Semaste
1257254721Semaste    // unwindplan_regloc has valid contents about where to retrieve the register
1258254721Semaste    if (unwindplan_regloc.IsUnspecified())
1259254721Semaste    {
1260254721Semaste        lldb_private::UnwindLLDB::RegisterLocation new_regloc;
1261254721Semaste        new_regloc.type = UnwindLLDB::RegisterLocation::eRegisterNotSaved;
1262254721Semaste        m_registers[lldb_regnum] = new_regloc;
1263254721Semaste        UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1264254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1265254721Semaste    }
1266254721Semaste
1267254721Semaste    if (unwindplan_regloc.IsSame())
1268254721Semaste    {
1269254721Semaste        if (IsFrameZero ())
1270254721Semaste        {
1271254721Semaste            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1272254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1273254721Semaste        }
1274254721Semaste        else
1275254721Semaste        {
1276254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1277254721Semaste        }
1278254721Semaste    }
1279254721Semaste
1280254721Semaste    if (unwindplan_regloc.IsCFAPlusOffset())
1281254721Semaste    {
1282254721Semaste        int offset = unwindplan_regloc.GetOffset();
1283254721Semaste        regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1284254721Semaste        regloc.location.inferred_value = m_cfa + offset;
1285254721Semaste        m_registers[lldb_regnum] = regloc;
1286269024Semaste        UnwindLogMsg ("supplying caller's register %d, value is CFA plus offset %d", lldb_regnum, offset);
1287254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1288254721Semaste    }
1289254721Semaste
1290254721Semaste    if (unwindplan_regloc.IsAtCFAPlusOffset())
1291254721Semaste    {
1292254721Semaste        int offset = unwindplan_regloc.GetOffset();
1293254721Semaste        regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1294254721Semaste        regloc.location.target_memory_location = m_cfa + offset;
1295254721Semaste        m_registers[lldb_regnum] = regloc;
1296269024Semaste        UnwindLogMsg ("supplying caller's register %d from the stack, saved at CFA plus offset %d", lldb_regnum, offset);
1297254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1298254721Semaste    }
1299254721Semaste
1300254721Semaste    if (unwindplan_regloc.IsInOtherRegister())
1301254721Semaste    {
1302254721Semaste        uint32_t unwindplan_regnum = unwindplan_regloc.GetRegisterNumber();
1303254721Semaste        uint32_t row_regnum_in_lldb;
1304254721Semaste        if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (unwindplan_registerkind, unwindplan_regnum, eRegisterKindLLDB, row_regnum_in_lldb))
1305254721Semaste        {
1306254721Semaste            UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1307254721Semaste            return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1308254721Semaste        }
1309254721Semaste        regloc.type = UnwindLLDB::RegisterLocation::eRegisterInRegister;
1310254721Semaste        regloc.location.register_number = row_regnum_in_lldb;
1311254721Semaste        m_registers[lldb_regnum] = regloc;
1312254721Semaste        UnwindLogMsg ("supplying caller's register %d, saved in register %d", lldb_regnum, row_regnum_in_lldb);
1313254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1314254721Semaste    }
1315254721Semaste
1316254721Semaste    if (unwindplan_regloc.IsDWARFExpression() || unwindplan_regloc.IsAtDWARFExpression())
1317254721Semaste    {
1318254721Semaste        DataExtractor dwarfdata (unwindplan_regloc.GetDWARFExpressionBytes(),
1319254721Semaste                                 unwindplan_regloc.GetDWARFExpressionLength(),
1320254721Semaste                                 process->GetByteOrder(), process->GetAddressByteSize());
1321263363Semaste        ModuleSP opcode_ctx;
1322263363Semaste        DWARFExpression dwarfexpr (opcode_ctx, dwarfdata, 0, unwindplan_regloc.GetDWARFExpressionLength());
1323254721Semaste        dwarfexpr.SetRegisterKind (unwindplan_registerkind);
1324254721Semaste        Value result;
1325254721Semaste        Error error;
1326254721Semaste        if (dwarfexpr.Evaluate (&exe_ctx, NULL, NULL, this, 0, NULL, result, &error))
1327254721Semaste        {
1328254721Semaste            addr_t val;
1329254721Semaste            val = result.GetScalar().ULongLong();
1330254721Semaste            if (unwindplan_regloc.IsDWARFExpression())
1331254721Semaste             {
1332254721Semaste                regloc.type = UnwindLLDB::RegisterLocation::eRegisterValueInferred;
1333254721Semaste                regloc.location.inferred_value = val;
1334254721Semaste                m_registers[lldb_regnum] = regloc;
1335254721Semaste                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsDWARFExpression)", lldb_regnum);
1336254721Semaste                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1337254721Semaste            }
1338254721Semaste            else
1339254721Semaste            {
1340254721Semaste                regloc.type = UnwindLLDB::RegisterLocation::eRegisterSavedAtMemoryLocation;
1341254721Semaste                regloc.location.target_memory_location = val;
1342254721Semaste                m_registers[lldb_regnum] = regloc;
1343254721Semaste                UnwindLogMsg ("supplying caller's register %d via DWARF expression (IsAtDWARFExpression)", lldb_regnum);
1344254721Semaste                return UnwindLLDB::RegisterSearchResult::eRegisterFound;
1345254721Semaste            }
1346254721Semaste        }
1347254721Semaste        UnwindLogMsg ("tried to use IsDWARFExpression or IsAtDWARFExpression for reg %d but failed", lldb_regnum);
1348254721Semaste        return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1349254721Semaste    }
1350254721Semaste
1351254721Semaste    UnwindLogMsg ("could not supply caller's reg %d location", lldb_regnum);
1352254721Semaste
1353254721Semaste    // FIXME UnwindPlan::Row types atDWARFExpression and isDWARFExpression are unsupported.
1354254721Semaste
1355254721Semaste    return UnwindLLDB::RegisterSearchResult::eRegisterNotFound;
1356254721Semaste}
1357254721Semaste
1358254721Semaste// If the Full unwindplan has been determined to be incorrect, this method will
1359269024Semaste// replace it with the architecture's default unwindplan, if one is defined.
1360254721Semaste// It will also find the FuncUnwinders object for this function and replace the
1361254721Semaste// Full unwind method for the function there so we don't use the errant Full unwindplan
1362254721Semaste// again in the future of this debug session.
1363254721Semaste// We're most likely doing this because the Full unwindplan was generated by assembly
1364254721Semaste// instruction profiling and the profiler got something wrong.
1365254721Semaste
1366269024Semastebool
1367269024SemasteRegisterContextLLDB::TryFallbackUnwindPlan ()
1368254721Semaste{
1369254721Semaste    UnwindPlan::Row::RegisterLocation unwindplan_regloc;
1370269024Semaste    if (m_fallback_unwind_plan_sp.get() == NULL)
1371269024Semaste        return false;
1372269024Semaste
1373269024Semaste    UnwindPlanSP original_full_unwind_plan_sp = m_full_unwind_plan_sp;
1374269024Semaste    UnwindPlan::RowSP active_row = m_fallback_unwind_plan_sp->GetRowForFunctionOffset (m_current_offset);
1375269024Semaste
1376269024Semaste    if (active_row && active_row->GetCFARegister() != LLDB_INVALID_REGNUM)
1377254721Semaste    {
1378269024Semaste        FuncUnwindersSP func_unwinders_sp;
1379269024Semaste        if (m_sym_ctx_valid && m_current_pc.IsValid() && m_current_pc.GetModule())
1380254721Semaste        {
1381269024Semaste            func_unwinders_sp = m_current_pc.GetModule()->GetObjectFile()->GetUnwindTable().GetFuncUnwindersContainingAddress (m_current_pc, m_sym_ctx);
1382269024Semaste            if (func_unwinders_sp)
1383254721Semaste            {
1384269024Semaste                func_unwinders_sp->InvalidateNonCallSiteUnwindPlan (m_thread);
1385254721Semaste            }
1386254721Semaste        }
1387269024Semaste        m_registers.clear();
1388269024Semaste        m_full_unwind_plan_sp = m_fallback_unwind_plan_sp;
1389269024Semaste        addr_t cfa_regval = LLDB_INVALID_ADDRESS;
1390269024Semaste        if (ReadGPRValue (m_fallback_unwind_plan_sp->GetRegisterKind(), active_row->GetCFARegister(), cfa_regval))
1391269024Semaste        {
1392269024Semaste            m_cfa = cfa_regval + active_row->GetCFAOffset ();
1393269024Semaste        }
1394269024Semaste
1395269024Semaste        UnwindLogMsg ("full unwind plan '%s' has been replaced by architecture default unwind plan '%s' for this function from now on.",
1396269024Semaste                      original_full_unwind_plan_sp->GetSourceName().GetCString(), m_fallback_unwind_plan_sp->GetSourceName().GetCString());
1397269024Semaste        m_fallback_unwind_plan_sp.reset();
1398254721Semaste    }
1399269024Semaste
1400269024Semaste    return true;
1401254721Semaste}
1402254721Semaste
1403254721Semaste// Retrieve a general purpose register value for THIS frame, as saved by the NEXT frame, i.e. the frame that
1404254721Semaste// this frame called.  e.g.
1405254721Semaste//
1406254721Semaste//  foo () { }
1407254721Semaste//  bar () { foo (); }
1408254721Semaste//  main () { bar (); }
1409254721Semaste//
1410254721Semaste//  stopped in foo() so
1411254721Semaste//     frame 0 - foo
1412254721Semaste//     frame 1 - bar
1413254721Semaste//     frame 2 - main
1414254721Semaste//  and this RegisterContext is for frame 1 (bar) - if we want to get the pc value for frame 1, we need to ask
1415254721Semaste//  where frame 0 (the "next" frame) saved that and retrieve the value.
1416254721Semaste
1417254721Semastebool
1418254721SemasteRegisterContextLLDB::ReadGPRValue (int register_kind, uint32_t regnum, addr_t &value)
1419254721Semaste{
1420254721Semaste    if (!IsValid())
1421254721Semaste        return false;
1422254721Semaste
1423254721Semaste    uint32_t lldb_regnum;
1424254721Semaste    if (register_kind == eRegisterKindLLDB)
1425254721Semaste    {
1426254721Semaste        lldb_regnum = regnum;
1427254721Semaste    }
1428254721Semaste    else if (!m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindLLDB, lldb_regnum))
1429254721Semaste    {
1430254721Semaste        return false;
1431254721Semaste    }
1432254721Semaste
1433254721Semaste    const RegisterInfo *reg_info = GetRegisterInfoAtIndex(lldb_regnum);
1434254721Semaste    RegisterValue reg_value;
1435254721Semaste    // if this is frame 0 (currently executing frame), get the requested reg contents from the actual thread registers
1436254721Semaste    if (IsFrameZero ())
1437254721Semaste    {
1438254721Semaste        if (m_thread.GetRegisterContext()->ReadRegister (reg_info, reg_value))
1439254721Semaste        {
1440254721Semaste            value = reg_value.GetAsUInt64();
1441254721Semaste            return true;
1442254721Semaste        }
1443254721Semaste        return false;
1444254721Semaste    }
1445254721Semaste
1446254721Semaste    bool pc_register = false;
1447254721Semaste    uint32_t generic_regnum;
1448254721Semaste    if (register_kind == eRegisterKindGeneric && regnum == LLDB_REGNUM_GENERIC_PC)
1449254721Semaste    {
1450254721Semaste        pc_register = true;
1451254721Semaste    }
1452254721Semaste    else if (m_thread.GetRegisterContext()->ConvertBetweenRegisterKinds (register_kind, regnum, eRegisterKindGeneric, generic_regnum)
1453254721Semaste             && generic_regnum == LLDB_REGNUM_GENERIC_PC)
1454254721Semaste    {
1455254721Semaste        pc_register = true;
1456254721Semaste    }
1457254721Semaste
1458254721Semaste    lldb_private::UnwindLLDB::RegisterLocation regloc;
1459254721Semaste    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, pc_register))
1460254721Semaste    {
1461254721Semaste        return false;
1462254721Semaste    }
1463254721Semaste    if (ReadRegisterValueFromRegisterLocation (regloc, reg_info, reg_value))
1464254721Semaste    {
1465254721Semaste        value = reg_value.GetAsUInt64();
1466254721Semaste        return true;
1467254721Semaste    }
1468254721Semaste    return false;
1469254721Semaste}
1470254721Semaste
1471254721Semaste// Find the value of a register in THIS frame
1472254721Semaste
1473254721Semastebool
1474254721SemasteRegisterContextLLDB::ReadRegister (const RegisterInfo *reg_info, RegisterValue &value)
1475254721Semaste{
1476254721Semaste    if (!IsValid())
1477254721Semaste        return false;
1478254721Semaste
1479254721Semaste    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1480254721Semaste    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1481254721Semaste
1482254721Semaste    // If this is the 0th frame, hand this over to the live register context
1483254721Semaste    if (IsFrameZero ())
1484254721Semaste    {
1485254721Semaste        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1486254721Semaste        return m_thread.GetRegisterContext()->ReadRegister (reg_info, value);
1487254721Semaste    }
1488254721Semaste
1489254721Semaste    lldb_private::UnwindLLDB::RegisterLocation regloc;
1490254721Semaste    // Find out where the NEXT frame saved THIS frame's register contents
1491254721Semaste    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1492254721Semaste        return false;
1493254721Semaste
1494254721Semaste    return ReadRegisterValueFromRegisterLocation (regloc, reg_info, value);
1495254721Semaste}
1496254721Semaste
1497254721Semastebool
1498254721SemasteRegisterContextLLDB::WriteRegister (const RegisterInfo *reg_info, const RegisterValue &value)
1499254721Semaste{
1500254721Semaste    if (!IsValid())
1501254721Semaste        return false;
1502254721Semaste
1503254721Semaste    const uint32_t lldb_regnum = reg_info->kinds[eRegisterKindLLDB];
1504254721Semaste    UnwindLogMsgVerbose ("looking for register saved location for reg %d", lldb_regnum);
1505254721Semaste
1506254721Semaste    // If this is the 0th frame, hand this over to the live register context
1507254721Semaste    if (IsFrameZero ())
1508254721Semaste    {
1509254721Semaste        UnwindLogMsgVerbose ("passing along to the live register context for reg %d", lldb_regnum);
1510254721Semaste        return m_thread.GetRegisterContext()->WriteRegister (reg_info, value);
1511254721Semaste    }
1512254721Semaste
1513254721Semaste    lldb_private::UnwindLLDB::RegisterLocation regloc;
1514254721Semaste    // Find out where the NEXT frame saved THIS frame's register contents
1515254721Semaste    if (!m_parent_unwind.SearchForSavedLocationForRegister (lldb_regnum, regloc, m_frame_number - 1, false))
1516254721Semaste        return false;
1517254721Semaste
1518254721Semaste    return WriteRegisterValueToRegisterLocation (regloc, reg_info, value);
1519254721Semaste}
1520254721Semaste
1521254721Semaste// Don't need to implement this one
1522254721Semastebool
1523254721SemasteRegisterContextLLDB::ReadAllRegisterValues (lldb::DataBufferSP &data_sp)
1524254721Semaste{
1525254721Semaste    return false;
1526254721Semaste}
1527254721Semaste
1528254721Semaste// Don't need to implement this one
1529254721Semastebool
1530254721SemasteRegisterContextLLDB::WriteAllRegisterValues (const lldb::DataBufferSP& data_sp)
1531254721Semaste{
1532254721Semaste    return false;
1533254721Semaste}
1534254721Semaste
1535254721Semaste// Retrieve the pc value for THIS from
1536254721Semaste
1537254721Semastebool
1538254721SemasteRegisterContextLLDB::GetCFA (addr_t& cfa)
1539254721Semaste{
1540254721Semaste    if (!IsValid())
1541254721Semaste    {
1542254721Semaste        return false;
1543254721Semaste    }
1544254721Semaste    if (m_cfa == LLDB_INVALID_ADDRESS)
1545254721Semaste    {
1546254721Semaste        return false;
1547254721Semaste    }
1548254721Semaste    cfa = m_cfa;
1549254721Semaste    return true;
1550254721Semaste}
1551254721Semaste
1552254721Semaste
1553254721SemasteRegisterContextLLDB::SharedPtr
1554254721SemasteRegisterContextLLDB::GetNextFrame () const
1555254721Semaste{
1556254721Semaste    RegisterContextLLDB::SharedPtr regctx;
1557254721Semaste    if (m_frame_number == 0)
1558254721Semaste      return regctx;
1559254721Semaste    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number - 1);
1560254721Semaste}
1561254721Semaste
1562254721SemasteRegisterContextLLDB::SharedPtr
1563254721SemasteRegisterContextLLDB::GetPrevFrame () const
1564254721Semaste{
1565254721Semaste    RegisterContextLLDB::SharedPtr regctx;
1566254721Semaste    return m_parent_unwind.GetRegisterContextForFrameNum (m_frame_number + 1);
1567254721Semaste}
1568254721Semaste
1569254721Semaste// Retrieve the address of the start of the function of THIS frame
1570254721Semaste
1571254721Semastebool
1572254721SemasteRegisterContextLLDB::GetStartPC (addr_t& start_pc)
1573254721Semaste{
1574254721Semaste    if (!IsValid())
1575254721Semaste        return false;
1576254721Semaste
1577254721Semaste    if (!m_start_pc.IsValid())
1578254721Semaste    {
1579254721Semaste        return ReadPC (start_pc);
1580254721Semaste    }
1581254721Semaste    start_pc = m_start_pc.GetLoadAddress (CalculateTarget().get());
1582254721Semaste    return true;
1583254721Semaste}
1584254721Semaste
1585254721Semaste// Retrieve the current pc value for THIS frame, as saved by the NEXT frame.
1586254721Semaste
1587254721Semastebool
1588254721SemasteRegisterContextLLDB::ReadPC (addr_t& pc)
1589254721Semaste{
1590254721Semaste    if (!IsValid())
1591254721Semaste        return false;
1592254721Semaste
1593254721Semaste    if (ReadGPRValue (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc))
1594254721Semaste    {
1595254721Semaste        // A pc value of 0 or 1 is impossible in the middle of the stack -- it indicates the end of a stack walk.
1596254721Semaste        // On the currently executing frame (or such a frame interrupted asynchronously by sigtramp et al) this may
1597254721Semaste        // occur if code has jumped through a NULL pointer -- we want to be able to unwind past that frame to help
1598254721Semaste        // find the bug.
1599254721Semaste
1600254721Semaste        if (m_all_registers_available == false
1601254721Semaste            && (pc == 0 || pc == 1))
1602254721Semaste        {
1603254721Semaste            return false;
1604254721Semaste        }
1605254721Semaste        else
1606254721Semaste        {
1607254721Semaste            return true;
1608254721Semaste        }
1609254721Semaste    }
1610254721Semaste    else
1611254721Semaste    {
1612254721Semaste        return false;
1613254721Semaste    }
1614254721Semaste}
1615254721Semaste
1616254721Semaste
1617254721Semastevoid
1618254721SemasteRegisterContextLLDB::UnwindLogMsg (const char *fmt, ...)
1619254721Semaste{
1620254721Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1621254721Semaste    if (log)
1622254721Semaste    {
1623254721Semaste        va_list args;
1624254721Semaste        va_start (args, fmt);
1625254721Semaste
1626254721Semaste        char *logmsg;
1627254721Semaste        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1628254721Semaste        {
1629254721Semaste            if (logmsg)
1630254721Semaste                free (logmsg);
1631254721Semaste            va_end (args);
1632254721Semaste            return;
1633254721Semaste        }
1634254721Semaste        va_end (args);
1635254721Semaste
1636254721Semaste        log->Printf ("%*sth%d/fr%u %s",
1637254721Semaste                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1638254721Semaste                      logmsg);
1639254721Semaste        free (logmsg);
1640254721Semaste    }
1641254721Semaste}
1642254721Semaste
1643254721Semastevoid
1644254721SemasteRegisterContextLLDB::UnwindLogMsgVerbose (const char *fmt, ...)
1645254721Semaste{
1646254721Semaste    Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
1647254721Semaste    if (log && log->GetVerbose())
1648254721Semaste    {
1649254721Semaste        va_list args;
1650254721Semaste        va_start (args, fmt);
1651254721Semaste
1652254721Semaste        char *logmsg;
1653254721Semaste        if (vasprintf (&logmsg, fmt, args) == -1 || logmsg == NULL)
1654254721Semaste        {
1655254721Semaste            if (logmsg)
1656254721Semaste                free (logmsg);
1657254721Semaste            va_end (args);
1658254721Semaste            return;
1659254721Semaste        }
1660254721Semaste        va_end (args);
1661254721Semaste
1662254721Semaste        log->Printf ("%*sth%d/fr%u %s",
1663254721Semaste                      m_frame_number < 100 ? m_frame_number : 100, "", m_thread.GetIndexID(), m_frame_number,
1664254721Semaste                      logmsg);
1665254721Semaste        free (logmsg);
1666254721Semaste    }
1667254721Semaste}
1668254721Semaste
1669269024Semaste
1670